項目工具:Python 2.7.11 Django 1.10.2 Bootstrap 3.3.0 IDE:eclipse Pydev
1. 首先確保settings中已有'django.contrib.auth'
例如:
myproject下settings
1 INSTALLED_APPS = [ 2 'account', 3 'django.contrib.admin', 4 'django.contrib.auth', 5 'django.contrib.contenttypes', 6 'django.contrib.sessions', 7 'django.contrib.messages', 8 'django.contrib.staticfiles', 9 'blog', 10 ]
MIDDLEWARE,和TEMPLATES帶有AuthenticationMiddleware和'django.contrib.auth.context_processors.auth',等
一般用Pydev創建Django project會自動添加。
2. 添加urls
2.1 添加主url:
在project的urls中添加
1 from django.conf.urls import url, include 2 from blog import views as blog_views 3 4 urlpatterns = [ 5 url(r'^admin/', admin.site.urls), 6 7 url(r'^blog/', include("blog.urls")), 8 9 url(r'^account/', include("account.urls")), 10 ]
2.2 在account子app下urls中添加
1 from django.conf.urls import url 2 from django.conf.urls.static import static 3 from django.contrib.auth import views as auth_views 4 from account import views as account_views 5 6 7 urlpatterns = [ 8 url(r'^$', account_views.account_info, name='account'), 9 url(r'^edit/$', account_views.account_edit, name='accountedit'), 10 url(r'^register/$', account_views.register, name='register'), 11 12 # 使用系統自帶auth:login,logout,password_change,password_change/done 13 # password_reset, password_reset/done, 14 # login / logout urls 15 url(r'^login/$', auth_views.login, name='login'), 16 url(r'^logout/$', auth_views.logout, name='logout'), 17 url(r'^logout-then-login/$', auth_views.logout_then_login, name='logout_then_login'), 18 19 # change password urls 20 url(r'^password-change/$', auth_views.password_change, name='password_change'), 21 url(r'^password-change/done/$', auth_views.password_change_done, name='password_change_done'), 22 23 # restore password urls 24 url(r'^password-reset/$', auth_views.password_reset, name='password_reset'), 25 url(r'^password-reset/done/$', auth_views.password_reset_done, name='password_reset_done'), 26 url(r'^password-reset/confirm/(?P<uidb64>[-\w]+)/(?P<token>[-\w]+)/$', auth_views.password_reset_confirm, name='password_reset_confirm'), 27 url(r'^password-reset/complete/$', auth_views.password_reset_complete, name='password_reset_complete'), 28 ]
3. 完成models部分:
from django.db import models from django.conf import settings
1 class Profile(models.Model): 2 3 user = models.OneToOneField(settings.AUTH_USER_MODEL) 4 image = models.ImageField(upload_to='static/image/%Y/%m', default='static/image/default.jpg', max_length=200, 5 blank=True, null=True, verbose_name='用戶頭像') 6 created_dt = models.DateTimeField(auto_now_add=True, db_index=True) 7 date_of_birth = models.DateField(blank=True, null=True) 8 9 def __unicode__(self): 10 return self.user.username
這里采用的是外鏈User表的方法。利用Django自有auth。還可以采用繼承User的AbstractUser的方法,后續會嘗試使用該方法。
4. 完成注冊部分:
4.1 完成注冊所需的forms
1 class UserRegForm(forms.ModelForm): 2 password = forms.CharField(label='Password', widget=forms.PasswordInput) 3 password2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput) 4 5 class Meta: 6 model = User 7 fields = ('username', 'email') 8 9 def clean_password2(self): 10 cd = self.cleaned_data 11 if cd['password'] != cd['password2']: 12 raise forms.ValidationError(u"校驗密碼錯誤") 13 return cd['password2']
4.2 完成注冊的views
1 # 用戶注冊 2 def register(request): 3 if request.method == "POST": 4 user_form = UserRegForm(request.POST) 5 if user_form.is_valid(): 6 new_user = user_form.save(commit=False) 7 new_user.set_password(user_form.cleaned_data['password']) 8 new_user.save() 9 profile = Profile.objects.create(user=new_user) 10 messages.success(request, u"用戶注冊成功") 11 return HttpResponseRedirect(reverse('login')) 12 else: 13 user_form = UserRegForm() 14 return render(request, 'account/register.html', {'regform': user_form})
4.3 完成注冊所需的template
{% extends "account_base.html" %} {% block title %}注冊用戶{% endblock %} {% block content %} <div id="container"> <div id="regform" > {% if regform.errors%} <p id="erroralarm"> Please correct the error{{regform.errors|pluralize}} below. </p> {% endif %} <form action="" method="post"> <table border =2> {{regform.as_table}} </table> <input type="submit" name='register' value="注冊"> </form> </div> <div id="protocoldiv" style="display:none"></div> <div id="logoimg"></div> </div> {%endblock content%}
此處擴展account_base.html另行說明:
代碼如下:
1 {% load staticfiles %} 2 <!DOCTYPE html> 3 <html> 4 <head> 5 <title>{% block title %}{% endblock %}</title> 6 <link href="{% static "css/bootstrap.min.css" %}" rel="stylesheet"> 7 </head> 8 9 <body> 10 <div id="header"> 11 <span class="logo">用戶管理>>></span> 12 {% if request.user.is_authenticated %} 13 <ul class="menu"> 14 <li {% if section == "blog" %}class="selected"{% endif %}><a href="{% url "blog" %}">My Blog</a></li> 15 <li {% if section == "account" %}class="selected"{% endif %}><a href="{% url "account" %}">Account</a></li> 16 </ul> 17 {% endif %} 18 19 <span class="user"> 20 {% if request.user.is_authenticated %} 21 Hello {{ request.user.username }}, <a href="{% url "logout" %}">Logout</a> 22 {% endif %} 23 </span> 24 25 <span class="home"> 26 <a href="{% url "index" %}">首頁</a> 27 </span> 28 </div> 29 30 {% if messages %} 31 <ul class="messages"> 32 {% for message in messages %} 33 <li class="{{ message.tags }}"> 34 {{ message|safe }} 35 <a href="#" class="close">×</a> 36 </li> 37 {% endfor %} 38 </ul> 39 {% endif %} 40 41 <div id="content"> 42 {% block content %} 43 {% endblock %} 44 </div> 45 </body> 46 47 </html>
至此注冊部分完成