目前我有以下结构。
我有用户,可以是教师或学生。学生可以为老师留下评论。我为教师设置了详细视图,并为get_context_data
添加了“评论”属性,以循环浏览评论以显示它们。
目标:作为学生的每个用户都可以提交对教师的评论。我想在详细视图的底部显示一个表单。如果用户已经有过评论,那么我们会调用update。如果用户没有审核,我们会创建它。
的 Models.py
class Teacher(models.Model):
user = models.OneToOneField(User, on_delete=models.PROTECT, related_name='Teacher')
availability = models.BooleanField(default=False)
def __str__(self):
return self.user.username
class Student(models.Model):
user = models.OneToOneField(User, on_delete=models.PROTECT, related_name='Student')
teacher = models.ForeignKey(Teacher)
reviewed = models.BooleanField(default=False)
def __str__(self):
return self.user.username
class Review(models.Model):
teacher = models.ForeignKey(Teacher)
student = models.OneToOneField(Student, on_delete=models.PROTECT, related_name='Student')
star = models.IntegerField(default=5)
body = models.TextField()
Views.py
class ReviewSubmitForm(forms.Form):
star = forms.IntegerField()
body = forms.CharField()
class TeacherView(generic.DetailView):
model = Teacher
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(TeacherView, self).get_context_data(**kwargs)
# Add extra context from another model
context['reviews'] = Review.objects.filter(teacher_id=self.kwargs['pk'])
context['rating'] = Review.objects.filter(teacher_id=self.kwargs['pk']).aggregate(Avg('star'))
context['form'] = ReviewSubmitForm()
return context
class ReviewSubmit(SingleObjectMixin, FormView):
template_name = 'users/teacher_detail.html'
form_class = ReviewSubmitForm
model = Review
def post(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return HttpResponseForbidden()
self.object = self.get_object()
return super(ReviewSubmit, self).post(request, *args, **kwargs)
def get_success_url(self):
return reverse('users:detail', kwargs={'pk': self.object.pk})
我现在能够看到form
并在我的模板中使用它。
我的教师视图位于/users/<pk>
我想要的逻辑是:寻找,检查当前的学生ID。
如果有pk = pk和student_id = student_id的条目,则加载更新表单。否则,如果是学生加载创建表单。
This example有些相似,但不完全相同。
修改: form_template.html
{% for field in form %}
<div class="form-group">
<span color="red">{{ field.errors }}</span>
<label>
{{ field.label_tag }}
</label>
<div>{{ field }}</div>
</div>
{% endfor %}