【发布时间】:2018-01-24 23:46:42
【问题描述】:
我需要在 django 中创建管理面板,管理员将能够添加“从用户扩展”的学生,我终于可以添加它们,但之后我得到“'AnonymousUser' 对象没有属性 '_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()
【问题讨论】:
-
你为什么要加
instance=request.user和instance=request.user.student,你需要了解注册为新用户时没有登录用户。 -
我试图删除它们,用户创建成功但学生没有得到输入数据我在 /add_stu/ NOT NULL 约束处得到完整性错误:helwan_student.user_id
-
是的,那是因为您还试图保存与用户有外键关系的学生。您还需要学生的用户字段才能保存学生表格
-
是的,这就是问题所在,谢谢你:)
标签: python django authentication django-models django-forms