我需要在django中创建admin面板,admin将能够添加“从用户扩展而来”的学生,我最终能够添加他们,但之后我得到“AnonymousUser”对象没有属性“\u meta” 用户已正确添加到数据库,但django已将我注销! 如何保持当前的用户会话
class student(models.Model):
Computers = 1
Communications = 2
Dep_CHOICES = (
(Computers, 'Computers'),
(Communications, 'Communications'),
)
user = models.OneToOneField(User, on_delete=models.CASCADE)
dep = models.PositiveSmallIntegerField(choices=Dep_CHOICES, null=True, blank=True)
deg = models.FloatField(null=True, blank=True)
def __str__(self): # __unicode__ for Python 2
return self.user.username
def create_user_profile(sender, instance, created):
if created:
student.objects.create(user=instance)
def save_user_profile(sender, instance , **kwargs):
instance.student.save()
class UserForm(ModelForm):
class Meta:
model = User
fields = ('username', 'email', 'password')
class studentForm(ModelForm):
class Meta:
model = student
fields = ('dep', 'deg')
景色
def add_stu(request):
if request.method == 'GET':
return render(request, "add_student.html")
else:
user_form = UserForm(request.POST, instance=request.user)
profile_form = studentForm(request.POST, instance=request.user.student)
user_form.save()
profile_form.save()
您不能直接保存配置文件表单,因为它与用户有外键关系,并且是必需的。因此,在保存配置文件表单之前,需要先保存用户,然后将用户添加到配置文件中
相关问题 更多 >
编程相关推荐