繁体   English   中英

选择一个有效的选项。 该选择不是可用的选择之一。 Django 表单出错

[英]Select a valid choice. That choice is not one of the available choices. error with Django Form

我有一个评论部分 html 页面,每当我尝试填写字段并单击 sumbit 时,它都会出现以下错误 - Select a valid choice. That choice is not one of the available choices. Select a valid choice. That choice is not one of the available choices.

视图.py

@login_required(login_url='/accounts/login')
def add_comment(request, slug):
    movie = Movie.objects.get(slug=slug)
    form = CommentForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect('movie:movie_list')

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

表格.py

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('commenter_name', 'comment_body')
        widgets = {
            'commenter_name': forms.TextInput(attrs={'class': 'form-control'}),
            'comment_body': forms.Textarea(attrs={'class': 'form-control'}),
        }

模型.py

class Comment(models.Model):
    movie = models.ForeignKey(Movie, related_name="comments", on_delete=models.CASCADE)
    commenter_name = models.ForeignKey(User, default=None, on_delete=models.CASCADE)
    comment_body = models.TextField()
    date_added = models.DateTimeField(auto_now=True)

    def __str__(self):
        return '%s - %s' % (self.movie.title, self.commenter_name)

请注意,我可以通过 /admin 面板添加评论,但是一旦我尝试向其中添加 API,事情就出错了。

我从 form.py 中删除了widgets ,这给了我以下错误。 之后我遇到了另一个错误 - NOT NULL constraint failed: movie_comment.post_id ,在更改views.py后我能够成功发布

@login_required(login_url='/accounts/login/')
def comment_create(request, slug):
    movie = Movie.objects.get(slug=slug)
    if request.method == 'POST':
        form = forms.CommentForm(request.POST, request.FILES)
        if form.is_valid:
            comment = form.save(commit=False)
            comment.post = movie
            comment.author = request.user
            form.save()
            return redirect('movies:movie_detail', slug=slug)
    else:
        form = forms.CommentForm()
    return render(request, 'add_comment.html', {'form': form})

现在可以了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM