我希望能夠爲教師提交評論。我有2種型號:Django:表單處理錯誤。處理與另一個模型關聯的表格
models.py
class Teacher(models.Model):
user = models.OneToOneField(User, on_delete=models.PROTECT, related_name='Teacher')
class Review(models.Model):
teacher = models.ForeignKey(Teacher)
#other fields
def __str__(self):
return self.name
forms.py
class ReviewForm(forms.ModelForm):
class Meta:
model = Review
#Note no 'teacher' in fields below
fields = ('title','star','body')
views.py我有以下形式處理:
def teacher_view(request,**kwargs):
teacher = Teacher.objects.get(pk=kwargs['pk'])
#if request.method == 'POST':
#handle the form
review_form = ReviewForm(request.POST, instance=teacher)
review_form.teacher=teacher
if review_form.is_valid():
review_form.save()
return redirect('users:index')
else:
出於某種原因,我似乎也得到了其他循環。例如。該表格無效。
Urls.py
url(r'^(?P<pk>[0-9]+)/$', views.teacher_view, name='detail')
全部Views.py
def teacher_profile(request, **kwargs):
teacher = Teacher.objects.get(pk=kwargs['pk'])
reviews = Review.objects.filter(teacher_id=kwargs['pk'])
star = Review.objects.filter(teacher_id=kwargs['pk']).aggregate(Avg('star'))
no_of_ratings = Review.objects.filter(teacher_id=kwargs['pk']).count()
if request.method == "POST":
if 'booking' in request.POST:
form = BookingForm(request.POST)
if form.is_valid():
#handle the form
return redirect('users:index')
else:
review_form = ReviewForm()
elif 'review' in request.POST:
review_form = ReviewForm(request.POST)
review_form['teacher']=teacher
if review_form.is_valid():
review_form.save()
return redirect('users:index')
else:
form = BookingForm()
else:
form = BookingForm()
review_form = ReviewForm()
else:
form = BookingForm()
review_form = ReviewForm()
return render(request, "users/teacher_detail.html", context={"form": form,
"review_form":review_form,
"teacher":teacher,
"reviews":reviews,
"star":star,
"no_of_ratings":no_of_ratings,
})
我又加了碼。我複製粘貼它從我的views.py,但刪除表單處理,我只是定義變量和重定向到另一個頁面與成功消息。
我想爲什麼你的答案中的邏輯是錯誤的,因爲它首先檢查表單是否有效,這是因爲教師丟失而無效。然後我們在檢查它是否有效之後定義教師。我試圖通過form.is_valid()
前加入review_form['teacher']=teacher
操縱的代碼,但總是出現錯誤:
'ReviewForm' object does not support item assignment
在您的'ReviewForm'中使用'model = Review',但是在初始數據中您提供了'Teacher'模型的實例 –
你的意思是實例=老師部分?即使它不在那裏,我仍然無效 – Roma