Django实战(一)- 搭建简单的博客系统

0.096字数 298阅读 3590

目录:

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>
    配   图:![]({{blog.pic.url}})


</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'

效果展示:

推荐阅读更多精彩内容