我正在尝试使用 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')