Django auth_user_model

时间:2016-08-02 00:23:21

标签: django

我想要进行auth_user_model登录,但我需要使用电子邮件和密码登录。所以如果我可以在'用户名'字段中保存电子邮件值,我想我可以这样做。

class HeepooUser(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    phone = models.CharField(max_length=15, null=True)
    allow_phone = models.BooleanField(default=False)
    school = models.ForeignKey(School)
    date_join = models.DateTimeField(auto_now_add=True)


def register(request):
    registered = False

    if request.method == 'POST':
        user_form = UserForm(request.POST)
        profile_form = RegisterForm(request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save(commit=False)
            user.set_password(user.password)
            user = user_form.save()

            profile = profile_form.save(commit=False)
            profile.user = user
            profile = profile_form.save()

            registered = True
            return HttpResponseRedirect("/books/")
        else:
            return HttpResponse('Wrong access1')

    else:
        user_form = UserForm()
        profile_form = RegisterForm()

    return render(request, "register.html", {
        'user_form': user_form,
        'profile_form': profile_form,
        'registered': registered,
})

forms.py

class UserForm(forms.ModelForm):
    email = forms.EmailField(max_length=50, required=True,
                         widget=forms.TextInput(attrs={'class':'form-control', }),
)
    password = forms.CharField(widget=forms.PasswordInput())
    class Meta:
        model = User
        fields = ('email', 'password',)


class RegisterForm(forms.ModelForm):
    class Meta:
        model = HeepooUser
        exclude = ('allow_phone', 'user',)

Register.html

    <form action="" method="post">
        {% csrf_token %}
        {{ user_form.as_p }}
        {{ profile_form.as_p }}
        <input type="submit" value="Register">
    </form>
你可以帮我吗? 谢谢!

1 个答案:

答案 0 :(得分:0)

您可以在登录表单中向用户请求电子邮件而不是用户名,以便将其用于登录他,然后只为该用户生成用户名,您可以使用他的电子邮件或姓名来完成。

编辑: 您只需要生成用户名。我们假设您要为用户请求姓名和姓氏。让我们创建一个生成它的方法。

def generate_username(first_name, last_name):
        username = '%s.%s' % (first_name.lower(), last_name.lower())
        username = '{:.29}'.format(username)
        counter = User.objects.filter(first_name=first_name,last_name=last_name).count()
        if counter > 0:
            username += '%s' % (counter + 1)
        return username

然后您可以在视图中使用它。

        user = user_form.save(commit=False)
        user.set_password(user.password)
        user.username = generate_username(first_name, last_name)
        .....

如果您不想申请名字或姓氏,也可以使用他的电子邮件生成用户名。