forms.py
"processing": true,
图片显示正常但字段未显示
的index.html
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
答案 0 :(得分:3)
将您的表单更改为此
您传递了list
中的字段,而不是set
类型{}
class ImageCreateForm(forms.ModelForm):
class Meta:
model = Image
fields = ['title', 'url', 'description']
widgets = {
'url':forms.HiddenInput,
}
在你的观点中
def image_create(request):
if request.method == 'POST':
#form is sent
form = ImageCreateForm(request.POST)
if form.is_valid():
#form data is valid
cd = form.cleaned_data
new_item = form.save(commit=False)
#assign current user to the item
new_item.user = request.user
new_item.save()
messages.success(request, 'Image added successfully')
#redirect to new created item detail view
return redirect(new_item.get_absolut_url())
else:
#build form with data provided by the bookmarklet via GET
form = ImageCreateForm()
return render(request, 'images/image/index.html',{'section':'images', 'form':form})
和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">
{{ form.as_p }}
{% csrf_token %}
<input type="submit" value= 'Bookmark it!'>
</form>
{% endblock %}
答案 1 :(得分:0)
虽然它看起来不像,但请确保if request.method及其相关的else在同一级别上。我有时会将else缩进以匹配if form.is_valid级别。