Ad

Assign Foreign Key Value After Creating ( Logged In User )

I have a createview using CBV

class StudentCreate(LoginRequiredMixin, CreateView):

    login_url = '/signin/'
    model = Student
    fields = ['first_name', 'last_name' ]
    success_url = '/dashboard/'

Respective models.py

class Class_teacher(models.Model):

    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    standard = models.IntegerField()
    division = models.CharField(max_length=1)
    subject = models.CharField(max_length=200)
    email = models.CharField(max_length=30)


class Student(models.Model):

    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    classteacher = models.ForeignKey('Class_teacher', on_delete=models.SET_NULL,blank=True, null=True )

The webapp has a login feature . When the user ( classteacher ) login they can add students. What I want is classteacher field in Student(model Form ) should be automatically set as user which is the classteacher. ( Classteacher ) and should be saved in the db after creating the student. Classteacher model is updated with respective required fields .

Ad

Answer

Look here for the various methods of a CreateView that you can override.

In your case, you want to override the form_valid() method, which is called when the new Student will be saved.

from django.shortcuts import get_object_or_404

def form_valid(self, form):
    self.object = form.save(commit=False)
    self.object.classteacher = get_object_or_404(Class_teacher, email=self.request.user.email)
    self.object.save()
    return super().form_valid(form)
Ad
source: stackoverflow.com
Ad