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' ] su
Solution 1:
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
defform_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()
returnsuper().form_valid(form)
Solution 2:
You need to define your own form_valid()
.
I assume the Teacher as a one to one Relationship with your User model.
defform_valid(self, form):
student = form.save(commit=False)
#retrieve the current logged_in teacher, of course you have to be sure this view is only accesible for teachers (in dispatch for exemple)
self.object.classteacher = self.request.user.teacher
self.object.save()
returnsuper(StudentCreate, self).form_vaild(form)
#bonus the dispatchdefdispatch(self, request, *args, **kwargs):
#get the loged in userif request.user.teacher:
returnsuper(StudentCreate, self).dispatch(request, *args, **kwargs)
else:
raise Http404
Post a Comment for "Assign Foreign Key Value After Creating ( Logged In User )"