Django的优势在于构建很多整套应用的数据模型,显示模版和响应事件能力,这一次我们来体会一下社交网站。
如果大家看了之前的文章,就知道我们需要通过虾面的命令创建一个社交网站项目。在settings.py里面的INSTALLED_APPS部分增加account。
source activate myenv
mkdir bookmarks
django-admin startproject bookmarks
cd bookmarks
django-admin startapp account
然后运行同步数据库相应表格。
python manage.py migrate
接下来,开始创建登录界面,在account目录下创建一个forms.py
from django import forms
class LoginForm(forms.Form):
username = forms.CharField()
password = form.CharField(widget=forms.PasswordInput)
然后在view.py里面把account加进来
from django.http import HttpResponse
from django.shortcuts import render
from django.contrib.auth import authenticate,login
from .forms import LoginForm
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(username=cd['username'],password=['password'])
if user is not None:
if user.is_active:
login(request,user)
return HttpResponse('Login successfully.')
else:
return HttpResponse("Failed.")
else:
return HttpResponse("Invalid Login.")
else:
form = LoginForm()
return render(request,'account/login.html',{'form':form})
下面需要增加一个account的超链接入口,在account目录下面创建一个新的urls.py
from django.conf.urls import url
from .import views
urlpatterns = [url(r'^login/$', view.user_login,name='login'),]
然后在整个项目的urls.py里面增加:
url(r'^account/',include('account.urls'))
接下来在account目录下创建模版如下
templates/
account/
login.html
base.html
然后在base.html里面增加框架
{% load staticfiles%}
<!DOCTYPE html>
<html>
<head>
<title>{%block title%}{%endblock%}</title>
<link href="{% static "css/base.css" %}" rel="stylesheet">
</head>
<body>
<div id="header">
<span class="logo">Bookmarks</span>
</div>
<div id="content">
{% block content %}
{% endblock %}
</div>
</body>
</html>
<% extends "base.html" %>
{% block title %}Login{% endblock %}
{% block content %}
<h1>Login</h1>
<p> Please input username and password here:</p>
<form action="." method="post">
{{form.as_p}}
{%csrf_token %}
<p><input type="submit" value="Login"></p>
</form>
{% endblock %}
以此类推,修改密码,登入登出等界面和动作也照此构建。