【问题标题】:Django Requiring Optional Form Field ErrorDjango 需要可选表单字段错误
【发布时间】: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>    

【问题讨论】:

    标签: django image model upload


    【解决方案1】:

    如果表单无效,您的视图不会返回响应。要修复它,像这样重写视图:

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

    【讨论】:

    • 效果很好,非常感谢。你不知道我在这上面花了多长时间。另一方面,您有什么想法,为什么图像字段不是可选的?
    • @FANCY_HOOMAN 欢迎您!尝试在表单中设置 required=False:image = forms.FileField(label='Select an image file', help_text='Please select a photo to upload', required=False)
    • 这最终给了我一个 MultiValueDictKeyError : (
    猜你喜欢
    • 1970-01-01
    • 2019-06-11
    • 2021-06-21
    • 2021-03-31
    • 2019-06-11
    • 2012-06-13
    • 1970-01-01
    • 2015-10-10
    • 1970-01-01
    相关资源
    最近更新 更多