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

标签 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 在下面描述了错误的原因。

最佳答案

它不起作用的原因是您的表单类中缺少必填字段;回想一下,模型表单验证也将 validate the model instance :

Validation on a ModelForm

There are two main steps involved in validating a ModelForm:

Validating the form
Validating the model instance

在您的类中,继承的 post 方法正在调用 is_valid():

def post(self, request, *args, **kwargs):
    """
    Handles POST requests, instantiating a form instance with the passed
    POST variables and then checked for validity.
    """
    form = self.get_form()
    if form.is_valid():
        return self.form_valid(form)
    else:
        return self.form_invalid(form)

您可以看到,如果 is_valid() 返回 true,它只会调用 form_valid();在您的情况下,它无法返回 true,因为您缺少必需的属性。

您可以通过在模型中将 user 外键设置为可选来轻松解决此问题。

关于python - 在Django CreateView中使用当前用户初始化ForeignKey用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32241991/

相关文章:

django - 快速申请电子邮件注册,django 登录授权

javascript - 在django中长时间处理时显示加载gif?

python - Django 模板上下文未显示

python - 使用 "with tf.Session()"的目的?

python - 防止eventlet中的greenthread切换

python - Django - 以geoJSON格式获取多边形的质心

python - Django:下订单时如何减少库存数量?

python - 如何添加一条最适合散点图的线

python - 在 Pandas 数据框替换功能中使用正则表达式匹配组

python - bytearray 不是 JSON 可序列化的