Django需要可选的表单字段错误

时间:2018-05-26 18:28:41

标签: django image model upload

对于新读者:Neverwalkaloner的解决方案解决了初始错误,但仍需要照片上传,并在forms.py中填写必需的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>    

1 个答案:

答案 0 :(得分:0)

如果表单无效,您的视图不会返回响应。为了解决这个问题,重写视图如下:

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})