![](/img/trans.png)
[英]Select a valid choice. ["objects"] is not one of the available choices. in 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.
@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)
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'}),
}
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.