django.auth操纵模型字段/允许用户名中的空格 [英] django.auth manipulate model fields/allow space in usernames

查看:105
本文介绍了django.auth操纵模型字段/允许用户名中的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在为应用程式执行用户注册。我正在修改django.auth默认行为以使用电子邮件而不是用户名。我想我会使用一个定制的auth后端。我希望用户仍然能够提供一个用户名。


  1. 如何在john doe中允许用户名中的空格,而无需更改django.auth模型中的字段。 p>


  2. 如何使邮箱需要。目前,如果电子邮件为空,我的UserCreation表单中的clean_email方法会引发验证错误。谢谢布兰登和安德鲁·斯克里奇这里是我的解决方案:


  3. b
    $ b

      class RegisterForm(UserCreationForm):
    username = forms.RegexField(label =(Username),max_length = 30,regex = r '^ [\t\r\\\
    \f\w. @ + * - ] + $',
    help_text =(必填,30个字符或更少字母,数字和@ /。 / / / / / / / _个字符。))
    error_messages = {'invalid':(此值可能只包含字母,数字和@ /。/ + / - / _字符。 $ b class Meta:
    model = User

    我复制了UserCreationForm中的字段。重要的部分是向正则表达式添加\t/\\\\\f。 \s无法工作。

    解决方案

    您可以随时从contrib.auth.forms中覆盖UserCreationForm,以实现用户名不同的字段并提供您自己的验证。只需继承表单并添加您自己的用户名字段,或者在该类的 __ init __ 中覆盖它。


    I'm currently implementing a user registration for an app. I'm tying to change the django.auth default behaviour to use email instead of username. I think i'll use a custom auth backend. I want the users still be able to provide an username.

    1. How can I allow spaces in the username like "john doe" without changing the fields in django.auth models.

    2. How do I make the emailfield required. currently the clean_email method in my UserCreation Form raises an validation error if email is empty. There must be a better way.

    Thanks to Brandon and Andrew Sledge here is my solution:

    class RegisterForm(UserCreationForm):
        username = forms.RegexField(label=("Username"), max_length=30, regex=r'^[ \t\r\n\f\w.@+*-]+$',
            help_text = ("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."),
            error_messages = {'invalid': ("This value may contain only letters, numbers and @/./+/-/_ characters.")})
    class Meta:
        model = User
    

    i copied the field from UserCreationForm. The important part is to add \t\r\n\f to the regex. \s wont work.

    解决方案

    You can always override the UserCreationForm from contrib.auth.forms to implement a different field for username and provide your own validation. Just inherit the form and add your own username field, or override it in the __init__ of the class.

    这篇关于django.auth操纵模型字段/允许用户名中的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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