首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在django的登录表单中添加一个新字段以及用户名和密码

在django的登录表单中添加一个新字段以及用户名和密码
EN

Stack Overflow用户
提问于 2017-08-02 14:07:07
回答 2查看 1.2K关注 0票数 0

我想要编辑django提供的登录表单,并且不想因为安全问题而构建新的表单。我已经看过像How to use another field for logging in with Django Allauth?这样的其他解决方案,这是一个很好的例子,但它根据手机号码分配电子邮件id。但是,我想添加另一个字段,该字段并不是专门用于身份验证,只是为了根据重定向完成的输入进行身份验证。我对我的方法以及是否可以这样做感到相当困惑。敬请指教。谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-08-02 14:19:34

你可以在你的forms.py文件中这样做。

代码语言:javascript
复制
class UserLoginForm(forms.Form):
    username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Username'}))
    password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control','placeholder':'Password'}))
    yourfield = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'yourfield'}))
    def clean(self, *args, **kwargs):
        username = self.cleaned_data.get("username")
        password = self.cleaned_data.get("password")

        #user_qs = User.objects.filter(username=username)
        #if user_qs.count() == 1:
        #   user = user_qs.first()
        if username and password:
            user = authenticate(username=username, password=password)
            if not user:
                raise forms.ValidationError("This user does not exist")
            if not user.check_password(password):
                raise forms.ValidationError("Incorrect password")
            if not user.is_active:
                raise forms.ValidationError("This user is no longer active")
            return super(UserLoginForm, self).clean(*args, **kwargs)
票数 1
EN

Stack Overflow用户

发布于 2017-08-02 17:22:49

如果我误解了你的问题,很抱歉,但这里是我如何为用户注册添加额外的字段,这看起来非常简单。为了详细起见,我已经包含了一些额外的相关方法:

../forms.py:

代码语言:javascript
复制
class CustomRegistrationForm(RegistrationForm):
    """
    Form for registering a new user account.

    Subclasses should feel free to add any additional validation they
    need, but should avoid defining a ``save()`` method -- the actual
    saving of collected user data is delegated to the active
    registration backend.

    """
    username = forms.RegexField(regex=r'^[\w.@+-]+$',
                                max_length=30,
                                label="Username",
                                error_messages={'invalid': "This value may contain only letters, numbers and @/./+/-/_ characters."})

    email = forms.EmailField(label="E-mail")
    password1 = forms.CharField(widget=forms.PasswordInput,
                                label="Password")
    password2 = forms.CharField(widget=forms.PasswordInput,
                                label="Password (again)")

    extra_field = forms.CharField([field options])


    def clean(self):

        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError("The two password fields didn't match.")
        return self.cleaned_data

然后,只需将您的注册URL设置为使用适当的表单类:

../urls.py:

代码语言:javascript
复制
url(r'^accounts/register/$', RegistrationView.as_view(form_class=accounts.forms.CustomRegistrationForm), name='registration_register'),

这个字段不是您的标准模型的一部分吗,或者您的输入需要做一些额外的工作?您可以设置一个信号,以便在用户注册时产生一些额外的魔力:

代码语言:javascript
复制
from forms import CustomRegistrationForm
def user_created(sender, user, request, **kwargs):
    form = CustomRegistrationForm(request.POST)
    user_account = get_user_account(user)
    user_account.persona = form.data['persona_tier']
    user_account.save()

from registration.signals import user_registered
user_registered.connect(user_created)

仅供参考,我使用的是django- regardless redux后端,但这种方法应该会帮助你更接近。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45452670

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档