从 CharField 获取字符串

Getting string from CharField

我一直在网上寻找但无济于事。我正在尝试从 Django 中的 CharField 获取 url 字符串。

class EntryForm(forms.ModelForm):
    class Meta:
        model = Entry
        fields = ['url']

def get_url(self):
    temp = self.fields['url']
    string = temp.to_python(temp)
    return string

这个 returns 一个 unicode 对象,但是它没有正确打印,正如我们在终端输出中看到的那样:

url is: 
<django.forms.fields.CharField object at 0x10781b410>

模特在这里:

class Entry(models.Model):
    url = models.CharField(max_length=200)
    article_title = models.CharField(max_length=200, default="generic title")

    def __unicode__(self):
        val = str(self.url) + ", " + str(self.article_title)
        return val

使用Python 2.7。 有人能帮忙吗? 谢谢!

使用Form.clean()函数获取表单数据。

def get_url(self):
    cleaned_data = self.clean()
    return cleaned_data.get('url')

为什么不使用 is_valid()

is_valid() calls clean() on the form automatically. You use is_valid() in your views, and clean() in your form classes.

这个函数是Form函数,不是View函数。

你应该在你的 views.py:

form = EntryForm(request.POST, instance=instance)
if form.is_valid():
    url = form.cleaned_data['url']