我确实阅读了官方文件,但它在阅读后单独描述了每个设施
'Django中的用户认证','第一步','模型层',' View 层'和'模板层'和'表单',我仍然不知道如何创建帐户系统。
似乎没有 django 1.6 和 python 3 内置帐户应用程序源代码或教程。哪里可以买到,谢谢。
更新:
我只是一个帐户应用程序,我可以将其插入任何新项目。它的网址如下所示:
account/register(这个页面的表单类是从django.contrib.auth中的User类创建的)
帐户/登录
帐户/注销
帐户/配置文件(此页面的表单类是从具有 OneToOneField(User)
字段的模型创建的)
最佳答案
在你的 views.py 中
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from django.core.context_processors import csrf
#Import a user registration form
from YourApp.forms import UserRegisterForm
# User Login View
def user_login(request):
if request.user.is_anonymous():
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
#This authenticates the user
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
#This logs him in
login(request, user)
else:
return HttpResponse("Not active")
else:
return HttpResponse("Wrong username/password")
return HttpResponseRedirect("/")
# User Logout View
def user_logout(request):
logout(request)
return HttpResponseRedirect('/')
# User Register View
def user_register(request):
if request.user.is_anonymous():
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid:
form.save()
return HttpResponse('User created succcessfully.')
else:
form = UserRegisterForm()
context = {}
context.update(csrf(request))
context['form'] = form
#Pass the context to a template
return render_to_response('register.html', context)
else:
return HttpResponseRedirect('/')
在你的 forms.py 中
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserRegisterForm(UserCreationForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'username', 'password1', 'password2')
在你的 urls.py 中:
# Accounts urls
url(r'accounts/login/$', 'YourApp.views.user_login'),
url(r'accounts/logout/$', 'YourApp.views.user_logout'),
url(r'accounts/register/$', 'YourApp.views.user_register'),
最后,在 register.html 中:
<form action="/accounts/register/" method="POST"> {% csrf_token %}
<h2>Please enter your details . . .</h2>
{{ form.as_p }}
<input type="submit" value="Sign Up">
</form>
希望这可以帮助。
关于django - django 1.6 和 python 3 中是否有示例来构建帐户应用程序(包括 :register , login 和 logout ),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20856800/