使用当前用户在Django CreateView中初始化ForeignKey用户

时间:2015-08-27 06:18:14

标签: python django django-views django-class-based-views

我收到错误:

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描述了错误的原因。

0 个答案:

没有答案