目錄:
1.要求
1、用戶可以注冊、登錄
2、登陸后,用戶可以發表博客、查看博客列表、修改博客、刪除博客;博客包含標題、內容、照片
3、如果用戶沒有登錄就嘗試發表博客、修改博客、刪除博客,提示用戶去登錄
4、每個用戶只能看見自己發表的博客
5、提供標題關鍵詞查找功能,查找后列出所有標題包含關鍵字的博客
2.代碼操作
blogapp文件樹形圖
- blogForm.py
# -*- coding:utf-8 -*-
from django.forms import Form,widgets,fields,ValidationError
class register(Form):
userName = fields.CharField(max_length=10)
password = fields.CharField(max_length=10,widget=widgets.PasswordInput)
repassword = fields.CharField(max_length=10,widget=widgets.PasswordInput)
def clean(self):
password = self.cleaned_data['password']
repassword = self.cleaned_data['repassword']
if not password == repassword:
myerror = '兩次密碼不一致,請重新輸入'
raise ValidationError(myerror)
return self.cleaned_data
class login(Form):
userName = fields.CharField(max_length=10)
password = fields.CharField(max_length=10,widget=widgets.PasswordInput)
class BlogForm(Form):
title = fields.CharField(max_length=20)
content = fields.CharField(max_length=200)
pic = fields.ImageField()
- html
- addblog.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加博客</title>
</head>
<body>
<form action="{{request.path}}" enctype="multipart/form-data" method="POST">
{% csrf_token %}
標題:{{blogform.title}}<br>
內容:{{blogform.content}}<br>
配圖:{{blogform.pic}}<br>
<input type="submit" value="發表">
</form>
<a href="{% url 'blogapp:bloglist' %}">返回文章列表</a>
</body>
</html>
- html
- bloglist.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>顯示博客列表</title>
</head>
<body>
<form action="{% url 'blogapp:search' %}" method="get">
<input type="text" name="keyword" value="{{ keyword }}">
<input type="submit" value="查詢">
</form>
<a href="{% url 'blogapp:addblog' %}">寫博客</a>
<h1>文章列表:</h1><br>
{% for blog in blogs %}
<a href="{% url 'blogapp:detailblog' %}?blogid={{blog.id}}">{{blog.title}}</a>
<a href="{% url 'blogapp:editblog' %}?blogid={{blog.id}}">修改</a>|
<a href="{% url 'blogapp:delblog' %}?blogid={{blog.id}}">刪除</a><br>
{% endfor %}
<!--這里'blogapp:detailblog'是因為setting中給blogapp加了命名空間,為了區別不同的代碼功能,也看不加-->
<a href="{% url 'blogapp:bloglist' %}">返回文章列表</a>
<a href="{% url 'blogapp:logout' %}">用戶注銷</a>
</body>
</html>
- html
- detailblog.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>顯示每篇博客的內容</title>
</head>
<body>
文章標題:{{blog.title}}<br>
內 容:{{blog.content}}<br>
配 圖:
</body>
</html>
- html
- editblog.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加博客</title>
</head>
<body>
<form action="{{request.path}}" enctype="multipart/form-data" method="post">
{% csrf_token %}
<input type="hidden" value="{{ id }}">
標題:{{blogform.title}}<br>
內容:{{blogform.content}}<br>
配圖:{{blogform.pic}}<br>
<input type="submit" value="修改">
</form>
<a href="{% url 'blogapp:bloglist' %}">返回文章列表</a>
</body>
</html>
- html
- login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登錄</title>
</head>
<body>
<form action="{{request.path}}" method="POST">
{% csrf_token %}
<a href="{% url 'register' %}">沒有賬號?去注冊</a><br>
用戶名:{{loginform.userName}}<br>
密 碼:{{loginform.password}}<br>{{error}}<br>
<input type="submit" value="登錄">
<a href="{% url 'blogapp:bloglist' %}">博客列表</a>
</form>
</body>
</html>
- html
- register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注冊頁面</title>
</head>
<body>
<form action="" method="post">
{% csrf_token %}
用戶名:{{form.userName}}{{error}}<br>
密 碼:{{form.password}}<br>
確認密碼:{{form.repassword}}<br>{{form.non_field_errors}}<br>
<input type="submit" value="注冊">
<a href="{% url 'bloglogin' %}">已有賬號,去登錄</a>
</form>
</body>
</html>
- html
- loginsuc.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登錄成功</title>
</head>
<body>
登陸成功了,開不開心,意不意外。怎么還有一個網頁?哈哈哈哈哈哈~
<a href="{% url 'blogapp:bloglist' %}">博客列表</a>
</body>
</html>
- html
- search.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>顯示博客列表</title>
</head>
<body>
文章列表:<br>
{% for blog in blogs %}
<a href="{% url 'blogapp:detailblog' %}?blogid={{blog.id}}">{{blog.title}}</a>
<a href="{% url 'blogapp:editblog' %}?blogid={{blog.id}}">修改</a>|
<a href="{% url 'blogapp:delblog' %}?blogid={{blog.id}}">刪除</a><br>
{% endfor %}
<!--這里'blogapp:detailblog'是因為setting中給blogapp加了命名空間,為了區別不同的代碼功能,也看不加-->
</body>
</html>
- views
- user_views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render,redirect
from blogapp.models import User
from django.http import HttpResponse
from blogapp import models
from blogapp.blogForms import blogForm
# Create your views here.
#注冊功能
def register(request):
if request.method == 'GET':
form = blogForm.register()
return render(request,'blogapp/register.html',{'form':form})
elif request.method == 'POST':
form = blogForm.register(request.POST)
if form.is_valid():
temp = models.User.objects.filter(userName=form.cleaned_data['userName']).exists()
if temp == False:
userModel = User()
userModel.userName = form.cleaned_data['userName']
userModel.password = form.cleaned_data['password']
userModel.save()
return HttpResponse('數據提交成功!快去登錄吧.')
else:
error = '用戶名已經存在,請換一個用戶名試試!'
return render(request,'blogapp/register.html',{'form':form,'error':error})
else:
return render(request,'blogapp/register.html',{'form':form})
#登錄功能
def login(request):
if request.method == 'GET':
loginform = blogForm.login()
return render(request,'blogapp/login.html',{'loginform':loginform})
elif request.method == 'POST':
loginform = blogForm.login(request.POST,)
if loginform.is_valid():
userName = loginform.cleaned_data['userName']
password = loginform.cleaned_data['password']
user = models.User.objects.filter(userName=userName).filter(password=password)
if user.exists():
request.session['user_id'] = user[0].id
return render(request,'blogapp/loginsuc.html')
else:
error = '用戶名或者密碼輸入有誤,請重試'
return render(request,'blogapp/login.html',{'loginform':loginform,'error':error})
else:
return render(request,'blogapp/login.html',{'loginform':loginform})
else:
return redirect('https://www.zhihu.com/')
#注銷功能
def logout(request):
userId = request.session.get('user_id',None)
if not userId == None:
del request.session['user_id']
return HttpResponse('注銷成功')
else:
return HttpResponse('你的操作不合法')
- views
- blog_views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render,redirect
from blogapp.models import User
from django.http import HttpResponse
from blogapp import models
from blogapp.blogForms import blogForm
from django.core.urlresolvers import reverse #引入重定向的包
#驗證用戶是否登錄
def checkLogin(session):
#session 鍵user_id如果不存在對應的值
id = session.get('user_id',None)
if id==None:
#轉到登錄頁面
return False,redirect(reverse('blogapp:bloglogin'))
else:
return True,id
#增加博客內容
def addBlog(request):
#強制登錄驗證
isPassed,next=checkLogin(request.session)
if not isPassed:
return next
if request.method == 'GET':
blogform = blogForm.BlogForm()
return render(request,'blogapp/addblog.html',{'blogform':blogform})
elif request.method == 'POST':
submitForm = blogForm.BlogForm(request.POST,request.FILES)
if submitForm.is_valid():
newBlog = models.Blog()
newBlog.pic = submitForm.cleaned_data['pic']
newBlog.title = submitForm.cleaned_data['title']
newBlog.content = submitForm.cleaned_data['content']
newBlog.authorId = request.session['user_id']
newBlog.save()
return HttpResponse('發表成功QAQ.')
else:
return render(request,'blogapp/addblog.html',{'blogform':submitForm})
#顯示首頁
def index(request):
return render(request,'blogapp/index.html')
#顯示博客列表
def list(request):
isPassed,next=checkLogin(request.session)
if not isPassed:
return next
userId = request.session.get('user_id')
#查找authorId和session中和user_id一致的博客
list = models.Blog.objects.filter(authorId=userId).filter(isDelete=1)
return render(request,'blogapp/bloglist.html',{'blogs':list})
#顯示博客文章內容
def detailBlog(request):
isPassed,next=checkLogin(request.session)
if not isPassed:
return next
#從選擇器中提取博客ID
blogId = request.GET.get('blogid',0) #默認為0
blog = models.Blog.objects.get(pk=blogId)
return render(request,'blogapp/detailblog.html',{'blog':blog})
#修改博客內容
def editBlog(request):
isPassed,next=checkLogin(request.session)
if not isPassed:
return next
if request.method == 'GET':
#從選擇器中提取博客ID
blogId = request.GET.get('blogid',0)
blog = models.Blog.objects.get(pk=blogId)
blogform = blogForm.BlogForm(initial={
'title':blog.title,
'content':blog.content,
'pic':blog.pic
})
return render(request,'blogapp/editblog.html',{'blogform':blogform,'id':blogId})
elif request.method == 'POST':
submitForm = blogForm.BlogForm(request.POST,request.FILES)
id = request.POST.get('id',0)
if submitForm.is_valid():
user_id = request.session['user_id']
#查找當前用戶發表的博客
newBlog = models.Blog.objects.filter(authorId=user_id)[0]
newBlog.pic = submitForm.cleaned_data['pic']
newBlog.title = submitForm.cleaned_data['title']
newBlog.content = submitForm.cleaned_data['content']
newBlog.save()
return redirect(reverse('blogapp:bloglist')) #重定向到博客首頁
else:
return render(request,'blogapp/editblog.html',{'blogform':submitForm,'id':id})
#刪除博客內容
def delBlog(request):
isPassed,next=checkLogin(request.session)
if not isPassed:
return next
if request.method == 'GET':
blogId = request.GET.get('blogid',0)
blog = models.Blog.objects.get(pk=blogId)
if blog.authorId == request.session['user_id']:
blog.isDelete=0
blog.save()
blog = models.Blog.objects.all().filter(isDelete=1)
return redirect(reverse('blogapp:bloglist')) #重定向到博客首頁
else:
return HttpResponse('抱歉,您無權進行此操作!!!')
#查找博客內容
def search(request):
isPassed,next=checkLogin(request.session)
if not isPassed:
return next
userId = request.session.get('user_id')
#得到關鍵詞
keyword = request.GET.get('keyword',None)
# 查找authorId和session中和user_id一致的博客
list = models.Blog.objects.filter(authorId=userId).filter(isDelete=1).filter(title__contains=keyword)
#注意這里的title__contains是雙劃線
return render(request, 'blogapp/bloglist.html', {'blogs': list})
- APP下的urls.py
from django.conf.urls import url
from views import user_views,blog_views
urlpatterns=[
url(r'^register/$',user_views.register,name='blogregister'),
url(r'^login/$',user_views.login,name='bloglogin'),
url(r'^addblog/$',blog_views.addBlog,name='addblog'),
url(r'^bloglist/$',blog_views.list,name='bloglist'),
url(r'^detailblog/$',blog_views.detailBlog,name='detailblog'),
url(r'^editblog/$', blog_views.editBlog, name='editblog'),
url(r'^delblog/$', blog_views.delBlog, name='delblog'),
url(r'^search/$',blog_views.search,name='search'),
url(r'^logout/$',user_views.logout,name='logout'),
]
- models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class User(models.Model):
userName = models.CharField(max_length=10)
password = models.CharField(max_length=10)
class Blog(models.Model):
title = models.CharField(max_length=20)
content = models.CharField(max_length=200)
pic = models.ImageField(upload_to='mypics/')
authorId = models.IntegerField()
isDelete = models.BooleanField(default=1)
- 項目下的urls.py
from django.conf.urls import url,include
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^blogapp/',include('blogapp.urls',namespace='blogapp')),
url(r'^admin/', admin.site.urls),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
- settings.py文件中加入以下內容
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
#INSTALLED_APPS中加入app名
INSTALLED_APPS = [
'blogapp',
]
SESSION_SERIALIZER='django.contrib.sessions.serializers.PickleSerializer'
效果展示: