我收到错误:
AttributeError at /courses/create/
'CourseStudentForm' object has no attribute 'user'
当我尝试通过将其用户字段设置为当前用户来创建新对象时:
class CourseStudentCreate(CreateView):
model = CourseStudent
fields = ['semester', 'block', 'course', 'grade']
success_url = reverse_lazy('quests:quests')
@method_decorator(login_required)
def form_valid(self, form):
data = form.save(commit=False)
data.user = self.request.user
data.save()
return super(CourseStudentCreate, self).form_valid(form)
这是模型:
class CourseStudent(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
semester = models.ForeignKey(Semester)
block = models.ForeignKey(Block)
course = models.ForeignKey(Course)
grade = models.PositiveIntegerField()
active = models.BooleanField(default=True)
表单显示正确,但是当我提交时,我收到错误。
解答:
从这里: Pass current user to initial for CreateView in Django
如果我想将用户保留为必填字段,则可以将form_valid
更改为:
def form_valid(self, form):
form.instance.user = self.request.user
return super(CourseStudentCreate, self).form_valid(form)
下面的Burhan Khalid描述了错误的原因。