【发布时间】:2017-12-15 09:20:53
【问题描述】:
forms.py
class ImageCreateForm(forms.ModelForm):
class Meta:
model = Image
fields = {'title', 'url', 'description'}
widgets = {
'url':forms.HiddenInput,
}
def clean_url(self):
url = self.cleaned_data['url']
valid_extensions = ['jpg', 'jpeg']
#The two below codes do exactly the same thing but partition is faster
extention = url.rpartition('.')[2].lower()
#extension = url.rsplit('.',1)[1].lower()
if extension not in valid_extensions:
raise forms.ValidationError('The given URL does not match valid image extensions')
return url
def save(self, force_insert=False,force_update=False,commit=True):
image = super(ImageCreateForm, self).save(commit=False)
image_url = self.cleaned_data['url']
image_name = '{}.{}'.format(slugify(image.title), image_url.rpartition('.')[2].lower())
#download image from the given URL
response = request.urlopen(image_url)
image.image.save(image_name,ContentFile(response.read()),save=False)
if commit:
image.save()
return image
图像显示正常,但字段未显示
index.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title %}Bookmark an image{% endblock %}
{% block content %}
<h1>Bookmark an image</h1>
<img src="{{ request.GET.url }}" class="image-preview">
<form action="." method="post">
{{ forms.as_p }}
{% csrf_token %}
<input type="submit" value= 'Bookmark it!'>
</form>
{% endblock %}
【问题讨论】:
-
您是否在视图中定义了“表单”?
-
在您的模板中,您有
{{ forms.as_p }}。通常,我希望{{ form.as_p }}(没有 s)。你没有展示你的观点,所以我无法判断这是否是问题。 -
是的,我做了'form = ImageCreateForm(data=request.POST)}'
-
贴出你的观点代码,方便我们理解
-
发布你的views.py文件的代码。您在其中呈现带有表单的模板的函数在哪里。我想你忘了定义“表单”所以它没有出现......