首页 文章

Django登录验证不起作用

提问于
浏览
0

我正在尝试使用Django提供的通用登录视图 . 我想在同一页面上注册和登录表单 . 这是我的urls.py

from django.conf.urls import patterns, include, url
from myApp.forms import UsersForm

urlpatterns = patterns('',

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

这是我的login.html

<html>
    <body>
    <form method="post" action="">{% csrf_token %}
        {{ authentication_form.first_name }} {{authentication_form.last_name }} <br>
        {{ authentication_form.username }} {{ authentication_form.password }} <br>
        <input type="submit" value="Register"/>
    </form>


    {% for field, error in form.errors.items %}
        {% if forloop.counter == 1 %}
            {{ error | striptags }}
        {% endif %}
    {% endfor %}

    <form method="post" action="{% url 'django.contrib.auth.views.login' %}">{% csrf_token%}
        {{authentication_form.username.label_tag}}
        {{authentication_form.username}}
        {{authentication_form.password.label_tag}}
        {{authentication_form.password}}
    <input type="submit" value="login" />
    <input type="hidden" name="next" value="{{ next }}" />
    </form>
    </body>
</html>

当我运行服务器并转到127.0.0.1时,只显示登录和注册按钮,实际字段不显示(我无法在页面的任何位置键入任何内容,只有两个按钮,一个显示'登录'和另一个说'注册' . 只有一个空白的空格,实际的字段应该是 . 如何显示用户名,密码,名字和姓氏的框?

编辑:当我将authentication_form.username更改为form.username时,它会给出模板错误

'WSGIRequest' object has no attribute 'get'

以及对此的追溯

Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  140.                     response = response.render()
File "/usr/local/lib/python2.7/dist-packages/django/template/response.py" in render
  105.             self.content = self.rendered_content
File "/usr/local/lib/python2.7/dist-packages/django/template/response.py" in rendered_content
  82.         content = template.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
  140.             return self._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in _render
  134.         return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
  830.                 bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
  74.             return node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render
  87.             output = force_text(output)
File "/usr/local/lib/python2.7/dist-packages/django/utils/encoding.py" in force_text
  99.                 s = s.__unicode__()
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in __str__
  411.         return self.as_widget()
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in as_widget
  458.         return widget.render(name, self.value(), attrs=attrs)
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in value
  494.                 self.data, self.form.initial.get(self.name, self.field.initial)
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in _data
  480.         return self.field.widget.value_from_datadict(self.form.data, self.form.files, self.html_name)
File "/usr/local/lib/python2.7/dist-packages/django/forms/widgets.py" in value_from_datadict
  209.         return data.get(name, None)

Exception Type: AttributeError at /
Exception Value: 'WSGIRequest' object has no attribute 'get'

我的通用登录视图就是这样

def login(request, template_name='registration/login.html',
      redirect_field_name=REDIRECT_FIELD_NAME,
      authentication_form=AuthenticationForm,
      current_app=None, extra_context=None):
"""
Displays the login form and handles the login action.
"""
redirect_to = request.REQUEST.get(redirect_field_name, '')

if request.method == "POST":
    form = authentication_form(data=request.POST)
    if form.is_valid():

        # Ensure the user-originating redirection url is safe.
        if not is_safe_url(url=redirect_to, host=request.get_host()):
            redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

        # Okay, security check complete. Log the user in.
        auth_login(request, form.get_user())

        if request.session.test_cookie_worked():
            request.session.delete_test_cookie()

        return HttpResponseRedirect(redirect_to)
else:
    form = authentication_form(request)

request.session.set_test_cookie()

current_site = get_current_site(request)

context = {
    'form': form,
    redirect_field_name: redirect_to,
    'site': current_site,
    'site_name': current_site.name,
}
if extra_context is not None:
    context.update(extra_context)
return TemplateResponse(request, template_name, context,
                        current_app=current_app)

我没有对template_name进行任何更改(尽管我在urls.py中指定了template_name,可以在上面看到)或current_app . 我在forms.py中的表单类是这样的

class UsersForm(forms.ModelForm):

class Meta:
model = Users
widgets = {'password':forms.PasswordInput()}

def __init__(self, *args, **kwargs):
    super( UsersForm, self ).__init__(*args, **kwargs)
    self.fields[ 'first_name' ].widget.attrs[ 'placeholder' ]="First Name"  
    self.fields[ 'last_name' ].widget.attrs[ 'placeholder' ]="Last Name"
    self.fields[ 'username' ].widget.attrs[ 'placeholder' ]="Username"
    self.fields[ 'password' ].widget.attrs[ 'placeholder' ]="Password"
    self.fields['first_name'].error_messages = {'required': 'Please enter your First Name.', 'max_length': 'Your First Name must be shorter than 50 characters.'}
    self.fields['last_name'].error_messages = {'required': 'Please enter your Last Name.', 'max_length': 'Your last Name must be shorter than 50 characters.'}
    self.fields['password'].error_messages = {'required': 'Please enter a Password.', 'max_length': 'Your Password must be shorter than 50 characters.', 'invalid': 'Your Password can only contain letters, numbers, underscores, and hyphens.'}
    self.fields['username'].error_messages = {'required': 'Please enter a Username.', 'max_length': 'Your Username must be shorter than 50 characters.', 'invalid': 'Your Username can only contain letters, numbers, underscores, and hyphens.',}

def clean_date_of_birth_month(self):
    data = self.cleaned_data.get('date_of_birth_month')
    if data == 'Month':
        raise forms.ValidationError('Please enter a correct Month for your date of birth.')

    return data

def clean_date_of_birth_day(self):
    data = self.cleaned_data.get('date_of_birth_day')
    if data == 'Day':
        raise forms.ValidationError('Please enter a correct Day for your date of birth.')

    return data

def clean_date_of_birth_year(self):
    data = self.cleaned_data.get('date_of_birth_year')
    if data == 'Year':
        raise forms.ValidationError('Please enter a correct Year for your date of birth.')

    return data

它是从现有模型创建的表单,就是这样

class Users(models.Model): 
    months = (
    ('Month','Month'), ('January', 'January'), ('February','February'), ('March','March'), ('April','April'), ('May','May'), ('June','June'), 
    ('July','July'), ('August','August'), ('September','September'), ('October','October'), ('November','November'), ('December','December'),
)

    days = (
    ('Day', 'Day'), ('1','1'), ('2','2'), ('3','3'), ('4','4'), ('5','5'), ('6','6'), ('7','7'), ('8','8'), ('9','9'), ('10','10'), ('11','11'),
    ('12','12'), ('13','13'), ('14','14'), ('15','15'), ('16','16'), ('17','17'), ('18','18'), ('19','19'), ('20','20'), ('21','21'), ('22','22'),
    ('23','23'), ('24','24'), ('25','25'), ('26','26'), ('27','27'), ('28','28'), ('29','29'), ('30','30'),('31','31'),
)

    years = (
('Year','Year'), ('2013','2013'), ('2012','2012'), ('2011','2011'), ('2010','2010'), ('2009','2009'), ('2008','2008'),
)

    alpha_field = RegexValidator(regex=r'^[a-zA-Z]+$', message='Name can only contain letters.')

    user_id = models.AutoField(unique=True, primary_key=True)

    first_name = models.CharField(max_length=50, validators=[alpha_field]) 
    last_name = models.CharField(max_length=50, validators=[alpha_field])

    username = models.SlugField(max_length=50, unique=True, error_messages={'unique': u'A user with that Username already exists. Please choose a different Username.'})
    password = models.SlugField(max_length=50)

    date_of_birth_month = models.CharField(verbose_name='', max_length=9, choices=months, default='Month')
    date_of_birth_day = models.CharField(verbose_name='', max_length=3, choices=days, default='Day')
    date_of_birth_year = models.CharField(verbose_name='', max_length=4, choices=years, default='Year')

1 回答

  • 1

    试试吧

    {{form.username}}
    

    因为通用视图以这种方式命名:

    form = authentication_form(request)
    

相关问题