添加用户django后禁用注销

时间:2018-01-24 23:46:43

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

我需要在django中创建管理面板,管理员将能够添加“从用户扩展”的学生,我终于能够添加它们,但之后我得到“'AnonymousUser'对象没有属性'_meta' 用户正确地添加到数据库中,但是django将我退出了! 我如何保持当前的用户会话!

a$rooster<-paste(a$pig,a$cow,a$chicken,sep="-")

视图

 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')

1 个答案:

答案 0 :(得分: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()