【问题标题】:Poll is not saving投票未保存
【发布时间】:2021-06-01 08:19:35
【问题描述】:

我正在构建一个 PollApp,但遇到了一个问题..

我为在投票中添加images 构建了一个poll add 功能。但是images 没有添加到Poll

当我在字段中选择图像然后保存时重定向到同一页面并说"This field is required"

models.py

class ImageChoice(models.Model):
    image_poll = models.ForeignKey(ImagePoll, on_delete=models.CASCADE)
    choice_image = models.FileField()

views.py

def polls_add(request):
    if request.method == 'POST':
        form = ImagePollAddForm(request.POST)
        if form.is_valid():
            poll = form.save(commit=False)
            poll.owner = request.user
            poll.save()
            new_choice1 = ImageChoice(poll=poll, image=form.cleaned_data['choice1']).save()

    context = {
        'form': form,
    }
    return render(request, 'add_poll.html', context)

forms.py

class ImagePollAddForm(forms.ModelForm):

    choice1 = forms.FileField()


    class Meta:
        model = ImagePoll
        fields = ['choice1']

当我尝试在每个字段中上传images 然后点击save 然后它没有上传。

我还尝试在 form = ImagePollAddForm(request.POST) 添加 request.FILES 但它显示 ImageChoice() got an unexpected keyword argument 'poll'

【问题讨论】:

    标签: python html django django-views django-forms


    【解决方案1】:

    您使用了无效的字段名称,您的模型有 image_poll 字段但没有投票。而且您的模型没有图像字段,而是 choice_image

    ImageChoice(image_poll=poll, choice_image=form.cleaned_data['choice1']).save()
    

    【讨论】:

    • 改名后的投票依然不是saving。并且当我用户 request.FILES 然后它说ImageChoice() got an unexpected keyword argument 'image'.
    • @GOO 检查我编辑了我的答案。您的错误消息从字面上告诉您出了什么问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    • 1970-01-01
    • 2012-10-29
    相关资源
    最近更新 更多