【问题标题】:disable logout after adding user django添加用户 django 后禁用注销
【发布时间】: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.userinstance=request.user.student,你需要了解注册为新用户时没有登录用户。
  • 我试图删除它们,用户创建成功但学生没有得到输入数据我在 /add_stu/ NOT NULL 约束处​​得到完整性错误:helwan_student.user_id
  • 是的,那是因为您还试图保存与用户有外键关系的学生。您还需要学生的用户字段才能保存学生表格
  • 是的,这就是问题所在,谢谢你:)

标签: python django authentication django-models django-forms


【解决方案1】:

您不能直接保存 profile_form,因为它与用户有外键关系并且是必需的。因此,在您保存 profile_form 之前,您需要先保存用户,然后将用户添加到配置文件中。

def add_stu(request):
    if request.method == 'GET':
        return render(request, "add_student.html")
    else:
        user_form = UserForm(request.POST)
        profile_form = studentForm(request.POST)
        new_user = user_form.save()
        profile = profile_form.save(commit=False)
        profile.user = new_user
        profile.save()

【讨论】:

  • 很高兴为您提供帮助。 :)
猜你喜欢
  • 2021-11-23
  • 2015-08-29
  • 2011-06-26
  • 2019-01-05
  • 2013-02-13
  • 1970-01-01
  • 2022-10-15
  • 2023-04-06
  • 2014-05-30
相关资源
最近更新 更多