如何扩展Django的"登录"形成? [英] How do I extend the Django "login" form?

查看:99
本文介绍了如何扩展Django的"登录"形成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,现在我做的基本的登录。在urls.py,我去Django的contrib请登录:

So, right now I'm doing the basic login. In urls.py, I go to django contrib login:

(r'^login/?$','django.contrib.auth.views.login',{'template_name':'login.html'}),

这是拍摄到这里:

@csrf_protect
@never_cache
def login(request, template_name='registration/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm):

这视图使用AuthenticationForm形式的模型:

That view uses the AuthenticationForm forms model:

class AuthenticationForm(forms.Form):
    """
    Base class for authenticating users. Extend this to get a form that accepts
    username/password logins.
    """
    username = forms.CharField(label=_("Username"), max_length=30)
    password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)

所以... 我的目标是要更改用户名的形式!通过添加这它:部件= forms.TextInput(ATTRS = {'占位':'用户名'})。而已。这就是我想要添加到用户名输入框。但是,我并不想改变实际的Django forms.py文件,因为这是Django的contrib请的一部分,我觉得不好更改该文件。

So...my objective is to to change the username form! By adding this to it: widget = forms.TextInput(attrs={'placeholder': 'username'}). That's it. That's all I want to add to the username input box. But, I don't want to change the actual django forms.py file, since that's part of django contrib and I feel bad changing that file.

我该怎么办?我应该创建一个扩展AuthenticationForm一种形式?如果是这样,我怎么导入?我如何传递作为通过我的urls.py参数?我不知道该怎么办。

What do I do? Should I create a form that extends AuthenticationForm? If so, how do I import that? And how do I pass that in as an argument via my urls.py? I don't know what to do.

推荐答案

您需要继承的 AuthenticationForm 类,然后你需要改变你的 urls.py

You need to subclass the AuthenticationForm class, and then you need to change your urls.py,

class MyAuthenticationForm(AuthenticationForm):
    # add your form widget here
    widget = .....

然后导入这个类到你的 urls.py 文件并更新调用

(r'^login/?$','django.contrib.auth.views.login',{'template_name':'login.html', 'authentication_form':MyAuthenticationForm}),

我太累了查找的文档站点的链接查看你需要使用什么类型的字段,但是这应该做的伎俩,让你开始,而无需修改Django的的形式。 PY 您绝对心疼有关更改!

这篇关于如何扩展Django的"登录"形成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆