Django:表单处理错误。处理与其他模型关联的表单

时间:2017-09-16 21:12:13

标签: python django django-forms

我希望能够为教师提交评论。我有2个型号:

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中复制粘贴它,但删除了表单处理,我只是定义变量并重定向到另一个带有成功消息的页面。

我认为为什么答案中的逻辑是错误的,因为它首先检查表单是否有效,这是因为教师缺失而无效。然后我们在检查教师是否有效后定义教师。我尝试在review_form['teacher']=teacher之前添加form.is_valid()来操纵代码,但始终会收到错误:

  

'ReviewForm'对象不支持项目分配

1 个答案:

答案 0 :(得分:1)

如果ReviewForm有效,您似乎想要添加教师:

def teacher_profile(request,**kwargs):
    teacher = Teacher.objects.get(pk=kwargs['pk'])
    reviews = teacher.review_set.all()
    star = reviews.aggregate(Avg('star'))
    no_of_ratings = reviews.count()

    form = BookingForm()
    review_form = ReviewForm()

    if request.method == "POST":
        if 'booking' in request.POST:
            form = BookingForm(request.POST)
            if form.is_valid():
                #Correct handling
                return redirect('users:index')
        elif 'review' in request.POST:
            review_form = ReviewForm(request.POST)
            if review_form.is_valid():
                review = review_form.save(commit=False)
                review.teacher = teacher
                review.save()
                return redirect('users:index')
    context = {
       "form":form,
       "review_form":review_form,
       "teacher":teacher,
       "reviews":reviews,
       "star":star,
       "no_of_ratings":no_of_ratings,})
    return render(request, "users/teacher_detail.html", context)

teacher_detail.html添加,

{{ review_form.errors }}