代码之家  ›  专栏  ›  技术社区  ›  asciitaxi

使用电子邮件和密码登录django站点时出现30个字符的限制错误

  •  2
  • asciitaxi  · 技术社区  · 15 年前

    "Ensure this value has at most 30 characters (it has 35)."
    

    在我的应用程序的url.py文件中,我重写了用户名字段的最大长度,如下所示:

    from django.contrib.auth.forms import AuthenticationForm
    AuthenticationForm.base_fields['username'].max_length = 75
    

    我甚至尝试过这里描述的课堂准备信号技术:

    http://stackoverflow.com/questions/2610088/can-djangos-auth-user-username-be-varchar75-how-could-that-be-done/2613385#2613385
    

    我不知道我在这里哪里出错了,我很感激你的帮助。

    3 回复  |  直到 15 年前
        1
  •  4
  •   Gabriel Hurley    15 年前

    如果您的目标只是更改表单的用户名字段的长度(而不是更改数据库中用户名字段的长度),那么正确的解决方案是将AuthenticationForm子类化,如下所示:

    from django import forms
    from django.contrib.auth.forms import AuthenticationForm
    
    class MyAuthenticationForm(AuthenticationForm):
        username = forms.CharField(label="Username", max_length=75)
    

    在模板、视图等中使用新表单代替旧的AuthenticationForm。

    至于为什么你的代码不起作用,我的猜测是,在将AuthenticationForm导入其他地方之前,你的应用程序的url.py没有被加载。我不能保证这就是原因,但这是最有可能的。

        2
  •  0
  •   Paulo Scardine    15 年前

    我的猜测:在url.py上使用:

    from django.contrib.auth.views import login
    
    ...
    
        (r'^accounts/login/$', login),
    

    而不是“惰性评估”表单:

    (r'^accounts/login/$', 'django.contrib.auth.views.login'),
    
        3
  •  0
  •   keithhackbarth    13 年前

    最好的方法是将此代码添加到顶级init:

    # Added so the login field can take email addresses longer than 30 characters
    from django.contrib.auth.forms import AuthenticationForm
    
    AuthenticationForm.base_fields['username'].max_length = 75
    AuthenticationForm.base_fields['username'].widget.attrs['maxlength'] = 75
    AuthenticationForm.base_fields['username'].validators[0].limit_value = 75
    

    但是,如果您选择上面的@Gabriel Hurley answer,则可以使用以下代码将其传递到登录表单:

    (r'^accounts/login/$', 'django.contrib.auth.views.login', {
        'authentication_form': AuthenticationForm
    }),