创建后分配外键值(登录用户) [英] Assign Foreign Key Value after creating ( Logged In User )
问题描述
我使用CBV有一个createview
I have a createview using CBV
class StudentCreate(LoginRequiredMixin, CreateView):
login_url = '/signin/'
model = Student
fields = ['first_name', 'last_name' ]
success_url = '/dashboard/'
各个模型。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 )
webapp具有登录功能。当用户(classteacher)登录时,他们可以添加学生。我想要的是Student(模型Form)中的classteacher字段应自动设置为user,即classteacher。 (Classteacher),并且在创建该学生之后应将其保存在数据库中。 Classteacher模型已使用相应的必填字段进行了更新。
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 .
推荐答案
查看此处了解 CreateView
的各种方法,您可以覆盖。
Look here for the various methods of a CreateView
that you can override.
在您的情况下,您想覆盖 form_valid()
方法,当新的学生
将被保存。
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)
这篇关于创建后分配外键值(登录用户)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!