我正在使用Django自定義窗體: 我調試過那個form.is_valid函數沒有運行,即使所有的數據都進入了視圖。Django窗體無法運行form.is_valid
models.py
choices = (
('yes', 'Yes'),
('no', 'No'),
('not sure', 'Not Sure'),
)
class TaggedArticle(models.Model):
user = models.ForeignKey(User, related_name='tagging')
category_fit = models.CharField(choices=choices, max_length=255)
article = models.ForeignKey(Article, related_name='articles')
relevant_feedback = models.TextField(blank=True)
created_at = models.DateTimeField(default=timezone.now, editable=False)
forms.py
class TagForm(forms.ModelForm):
class Meta:
model = TaggedArticle
fields = ('user', 'category_fit', 'article', 'relevant_feedback')
widgets = {
'category_fit': forms.RadioSelect()
}
views.py
def post(self, request, *args, **kwargs):
if request.method == 'POST':
post_data = request.POST.copy()
post_data.update({'user': request.user.pk})
form = forms.TagForm(post_data)
print('request recieved')
if form.is_valid():
tag = TaggedArticle()
tag.user = request.user
article = Article.objects.all().filter(id=form.cleaned_data['article'])
tag.category_fit = form.cleaned_data['category_fit']
tag.article = article
tag.relevant_feedback = form.cleaned_data['relevant_feedback']
tag.save()
return HttpResponse('Tagged Successfully!', status=200)
更新 我認爲這是單選按鈕錯誤: 以下是我最模板得到這個:
<td><label class="radio-inline"><input type="radio" name="category_fit">Yes</label></td>
<td><label class="radio-inline"><input type="radio" name="category_fit">No</label></td>
<td><label class="radio-inline"><input type="radio" name="category_fit">Not Sure</label>
請幫助我! 在此先感謝!
嗨,@Bear!它返回目標錯誤! –
您的表單有錯誤,我更新了答案,您可以試試 –
我認爲這是category_fit radio選項的錯誤,我如何在我的模板中使用這個單選按鈕?請! –