Nabeel Ayub
Nabeel Ayub

Reputation: 1250

add foreign key (user) value in fields of createview django

I want to insert data and I am using create view. The problem is I also want to pass a foreign key in a field which is not coming from form how to do it?

example:

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

All the fields except teacher are coming from a form.Whereas the teacher will the be user object who is logged in, how to save it in a fields(teacher)?

Upvotes: 0

Views: 231

Answers (2)

Ayush
Ayush

Reputation: 57

You need to add a foreign key constraint in your models.py file like which should look like

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()

Upvotes: 1

Shobi
Shobi

Reputation: 11451

you will have to override the form_valid function and inside that, you need to bind the foreign key accordingly

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

Upvotes: 1

Related Questions