我一直在研究django注册脚本,它正在工作,没有改变它停止工作的任何东西,我不完全确定原因。当我注册时,它会将我带到登录页面并说用户名和密码不匹配。就好像它甚至没有将数据传递给视图。我不确定这是我的代码,它可能只是一个django,我做错了。
经过进一步调查,我意识到它没有在views.py中调用register函数。
我在寄存器视图中添加了一些打印行,以查看它是否正在执行
@csrf_protect
def register(request):
print 'test'
if request.method == 'POST':
form = RegistrationForm(request.POST)
print form
if form.is_valid():
user = User.objects.create_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
email=form.cleaned_data['email']
)
save_userdata = UserProfile(username = form.cleaned_data['username'] ,
title=form.cleaned_data['profile_title'],
first_name = form.cleaned_data['first_name'],
last_name = form.cleaned_data['last_name'],
about = form.cleaned_data['about'],
user_score = 0,
dob = form.cleaned_data['dob'],
occupation = form.cleaned_data['occupation'],
pub_date = datetime.now())
save_userdata.save()
return HttpResponseRedirect('/register/success/')
else:
form = RegistrationForm()
variables = RequestContext(request, {
'form': form
})
return render_to_response(
'register.html',
variables,
)
from django.conf.urls import patterns, include, url
from django.contrib import admin
from ChompMe.views import *
urlpatterns = patterns('',
url(r'^$', 'django.contrib.auth.views.login'),
url(r'^logout/$', logout_page),
url(r'^accounts/login/$', 'django.contrib.auth.views.login'), # If user is not login it will redirect to login page
url(r'^register$', register),
url(r'^register/$', register),
url(r'^home$', home),
url(r'^home/$', home),
url(r'^register/success/$', register_success),
url(r'^register/success$', register_success),
url(r'^admin/', include(admin.site.urls)),
url(r'^gettoken/$', getToken),
url(r'^addfriend/$', addFriend),
url(r'^[A-Za-z0-9_.]+$', friends),
)
@csrf_protect
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
email=form.cleaned_data['email']
)
save_userdata = UserProfile(username = form.cleaned_data['username'] ,
title=form.cleaned_data['profile_title'],
first_name = form.cleaned_data['first_name'],
last_name = form.cleaned_data['last_name'],
about = form.cleaned_data['about'],
user_score = 0,
dob = form.cleaned_data['dob'],
occupation = form.cleaned_data['occupation'],
pub_date = datetime.now())
save_userdata.save()
return HttpResponseRedirect('/register/success/')
else:
form = RegistrationForm()
variables = RequestContext(request, {
'form': form
})
return render_to_response(
'register.html',
variables,
)
def register_success(request):
return render_to_response(
'success.html',
)
#files.py
import re
from django import forms
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
class RegistrationForm(forms.Form):
username = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs=dict(required='True', max_length=30)),
label=_("Username"), error_messages={ 'invalid': _("This value must contain only letters, numbers and underscores.") })
email = forms.EmailField(widget=forms.TextInput(attrs=dict(required='True', max_length=30)), label=_("Email address"))
password1 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required='True', max_length=30, render_value='False')), label=_("Password"))
password2 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required='True', max_length=30, render_value='False')), label=_("Password (again)"))
dob = forms.RegexField(regex=r'^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$',
widget=forms.TextInput(attrs=dict(required='True', max_length=11)),
label=_("Birthday YYYY-MM-DD"), error_messages={ 'invalid':_("This must be in the proper format YYYY-MM-DD")})
first_name = forms.CharField(widget=forms.TextInput(attrs=dict(required='True', max_length=20)), label=_("First Name"))
last_name = forms.CharField(widget=forms.TextInput(attrs=dict(required='True', max_length=20)), label=_("Laast Name"))
about= forms.CharField(widget=forms.TextInput(attrs=dict(required='True', max_length=90000)), label=_("About"))
occupation = forms.CharField(widget=forms.TextInput(attrs=dict(required='True', max_length=40)), label=_("Occupation"))
profile_title = forms.CharField(widget=forms.TextInput(attrs=dict(required='True', max_length=40)), label=_("Profile Title"))
def clean_userdata(self):
self.cleaned_data['dob'] = self.dob
self.cleaned_data['first_name'] = self.first_name
self.cleaned_data['last_name'] = self.last_name
self.cleaned_data['about'] = self.about
self.cleaned_data['occupation'] = self.occupation
self.cleaned_data['profile_title'] = self.profile_title
def clean_username(self):
try:
user = User.objects.get(username__iexact=self.cleaned_data['username'])
except User.DoesNotExist:
return self.cleaned_data['username']
raise forms.ValidationError(_("The username already exists. Please try another one."))
def clean(self):
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError(_("The two password fields did not match."))
return self.cleaned_data
模板
{% extends "base.html" %}
{% block title %}User Registration{% endblock %}
{% block head %}User Registration{% endblock %}
{% block content %}
<form method="post" action=".">
{% csrf_token %}
<table border="0">
{{ form.as_table }}
</table>
<input type="submit" value="Register" />
</form>
<a href="/">Login</a>
{% endblock %}
答案 0 :(得分:1)
控制台会将POST
请求显示为/
,但必须指向/register/
,对吧?将表单中的action
更改为给定网址:
<form action="{% url "register" %}" method="post">
+
urlpatterns = patterns('',
url(r'^register$', register, name='register'),
...
)