【发布时间】:2018-11-05 20:04:54
【问题描述】:
致新读者:Neverwalkaloner 的解决方案解决了最初的错误,但仍然需要上传照片,并且在 forms.py 中将 required 设为 false 会给我一个 MultiValueDictKeyError。任何有关使其成为可选的帮助将不胜感激。
我有一个模型和表单来上传图片和文本,或者只是文本。我的意图实际上是让它在图像、文本或两者之间做出选择,任何帮助都将不胜感激,但我离题了。仅在包含图像时才可以上传,如果只是文本,则会出现错误:
The view lesyeux.views.posts didn't return an HttpResponse object. It
returned None instead.The view lesyeux
我的模型是:
class Post(models.Model):
image = models.ImageField(upload_to='uploaded_images', blank=True,
null=True)
text_post = models.CharField(max_length=1000)
author = models.ForeignKey(User)
我的表格是:
class PostForm(forms.ModelForm):
image = forms.FileField(label='Select an image file',
help_text='Please select a photo to upload')
text_post = forms.CharField(help_text="Please enter some text.")
class Meta:
model = Post
fields = ('image', 'text_post',)
exclude = ('author',)
我的看法是:
def posts(request, id=None):
neighborhood = get_object_or_404(Neighborhood, id=id)
form = PostForm()
if request.method == 'POST':
form = PostForm(request.POST, request.FILES)
if form.is_valid():
post = Post(image = request.FILES['image'])
post = form.save(commit=False)
post.author = request.user
post = post.save()
next = request.POST.get('next', '/')
return HttpResponseRedirect(next)
else:
form = PostForm()
posts = Post.objects.all().order_by('-id')
return render(request, 'posts.html', context = {'form':form,
'posts':posts, 'neighborhood':neighborhood})
我的表格是:
<form id="PostForm" method="post" action="/view/{{ neighborhood.id }}/posts/" enctype="multipart/form-data">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<input type="hidden" name="next" value="{{ request.path }}">
<input type="submit" name="submit" value="Post" />
</form>
【问题讨论】: