在createview django的字段中添加外键(用户)值

时间:2018-10-08 06:34:38

标签: django django-views

我想插入数据,并且正在使用create view。问题是我还想在不是来自表单的字段中传递外键怎么办?

示例:

class Addfile(CreateView):  
model=uploadAssignment
fields=['teacher','title','description','deadline']

除教师以外的所有字段都来自表单。教师将成为登录的用户对象,如何将其保存在字段(教师)中?

2 个答案:

答案 0 :(得分:0)

您将不得不覆盖form_valid函数,在该函数中,您需要相应地绑定外键

class Addfile(CreateView):
  success_message = 'Added Successfully'
  form_class = ...

  def form_valid(self, form):
    form.instance.teacher = self.request.user #here you bind the foreign key teacher to the current user

    response = super(Addfile, self).form_valid(form)

    return response

答案 1 :(得分:0)

您需要在models.py文件中添加外键约束,看起来像这样

import <teacher/user>model as User
class UploadAssignment(models.Model):
     models.ForeignKey(User,blank=True,null=True,default=None,
                             on_delete=models.CASCADE)
     title = models.CharField(max_length=250, blank=False)
     description = models.CharField(max_length=250, blank=False)
     deadline = models.DateField()