码迷,mamicode.com
首页 > Web开发 > 详细

用html页面模板使用django完成个人博客

时间:2018-05-24 18:20:20      阅读:774      评论:0      收藏:0      [点我收藏+]

标签:url   nload   微软雅黑   教你   没有   lease   previous   继承   forms   

1、进入虚拟环境: workon 虚拟环境名

技术分享图片

 

2、找到我们的项目管理文件夹django,进入创建项目django-admin startproject blog

技术分享图片

技术分享图片

3、进入到我们的项目文件夹当中,创建我们的第一个应用 python manage.py startapp user  用于用户管理

                 创建我们的第二个应用python manage.py startapp articles 用于文章管理

 

技术分享图片

技术分享图片

4、使用pycharm打开创建的项目blog,在pycharm当中设置项目的虚拟环境

技术分享图片

5、由于我们在创建项目的过程中会遇到两个或者以上的应用,为了便于管理,我们一般创建一个新的文件夹(apps)用于管理所有的应用:

技术分享图片

6、然后将apps设置成为根目录:

技术分享图片

7、将应用拖入apps中:

技术分享图片

8、设置settings

"""
Django settings for blog project.

Generated by ‘django-admin startproject‘ using Django 1.8.2.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os,sys

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0,apps)  #目的是将文件夹apps设置为根目录

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = i)hua049@1k6g-mf=b%h3-g8ma&#$i#*al8zu%gg!z-l8o_rz2

# SECURITY WARNING: don‘t run with debug turned on in production!
DEBUG = True # True为调试模式,Fasle为生产模式

ALLOWED_HOSTS = []


# Application definition
#里面写入应用名称
INSTALLED_APPS = (
    django.contrib.admin,
    django.contrib.auth,
    django.contrib.contenttypes,
    django.contrib.sessions,
    django.contrib.messages,
    django.contrib.staticfiles,
    users,
    articles, 

)

AUTH_USER_MODEL = users.UserProfile
#中间键设置,一般默认的就行了
MIDDLEWARE_CLASSES = (
    django.contrib.sessions.middleware.SessionMiddleware,
    django.middleware.common.CommonMiddleware,
    django.middleware.csrf.CsrfViewMiddleware,
    django.contrib.auth.middleware.AuthenticationMiddleware,
    django.contrib.auth.middleware.SessionAuthenticationMiddleware,
    django.contrib.messages.middleware.MessageMiddleware,
    django.middleware.clickjacking.XFrameOptionsMiddleware,
    django.middleware.security.SecurityMiddleware,
    mymiddlewears.HandlerRequestMiddleWare
)

ROOT_URLCONF = blog.urls
#设置静态文件配置,一般会创建一个templates文件夹用于存放静态文件
TEMPLATES = [
    {
        BACKEND: django.template.backends.django.DjangoTemplates,
        DIRS: [os.path.join(BASE_DIR,templates)],
        APP_DIRS: True,
        OPTIONS: {
            context_processors: [
                django.template.context_processors.debug,
                django.template.context_processors.request,
                django.contrib.auth.context_processors.auth,
                django.contrib.messages.context_processors.messages,
                django.template.context_processors.media,#用于图片的处理
            ],
        },
    },
]

WSGI_APPLICATION = blog.wsgi.application


# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    default: {
        ENGINE: django.db.backends.mysql, #处理器使用的数据库,这里是mysql
        NAME: blog, #mysql数据库名字
        USER: root, #mysql数据库用户
        PASSWORD: root,#密码
        HOST: localhost,
        PORT: 3306,
    }
}


# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
#
# 编码显示配置
LANGUAGE_CODE = zh-CN

TIME_ZONE = Asia/Shanghai

USE_I18N = True

USE_L10N = True

USE_TZ = False


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = /static/
STATICFILES_DIRS = [
    os.path.join(BASE_DIR,static)
]

#配置媒体文件夹
MEDIA_URL = /static/media/
MEDIA_ROOT = os.path.join(BASE_DIR,static/media)

 

9、再到mysql数据库里创建数据库blog。

10、blog中urls代码:

"""blog URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r‘^$‘, views.home, name=‘home‘)
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r‘^$‘, Home.as_view(), name=‘home‘)
Including another URLconf
    1. Add an import:  from blog import urls as blog_urls
    2. Add a URL to urlpatterns:  url(r‘^blog/‘, include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.views.static import serve
from users.views import index
from blog.settings import MEDIA_ROOT
urlpatterns = [
    url(r^admin/, include(admin.site.urls)),
    url(r^users/,include(users.urls,namespace=users)),
    url(r^articles/,include(articles.urls,namespace=articles)),
    url(r^$,index,name=index),
    url(r^static/media/(?P<path>.*),serve,{document_root:MEDIA_ROOT})
]

 

11、user 中forms.py中代码:

from django import forms


class UserRegistForm(forms.Form):
    username=forms.CharField(max_length=20,min_length=6,required=True,error_messages={
        max_length:用户名最大长度为20,
        min_length:用户名最小长度为6,
        required:用户名为必填
    })
    email=forms.EmailField(max_length=100,min_length=8,required=False,error_messages={
        invalid:邮箱格式为:xxx@xx.com
    })
    url=forms.URLField(max_length=100,min_length=8,required=False,error_messages={
        invalid:网址格式为:http://www.xxx.com
    })
    password=forms.CharField(max_length=20,min_length=8,required=True,error_messages={
        max_length:密码最大长度为20,
        min_length:密码名最小长度为8,
        required:密码为必填
    })
    password1=forms.CharField(max_length=20,min_length=8,required=True,error_messages={
        max_length:密码最大长度为20,
        min_length:密码名最小长度为8,
        required:密码为必填
    })
class UserloginForm(forms.Form):
    username=forms.CharField(max_length=20,min_length=6,required=True)
    password=forms.CharField(max_length=20,min_length=8,required=True)

 12、user 中models.py中代码:

from django.db import models
from django.contrib.auth.models import AbstractUser
from datetime import datetime
# Create your models here.
class UserProfile(AbstractUser):
    nick_name=models.CharField(max_length=20,verbose_name=用户昵称,null=True,blank=True)
    url=models.URLField(max_length=100,verbose_name=用户主页,null=True,blank=True)
    add_time=models.DateTimeField(default=datetime.now,verbose_name=添加时间)

    def __str__(self):
        return self.username

    class Meta:
        verbose_name=用户信息
        verbose_name_plural=verbose_name

 完成后 注意生成迁移文件命令:python3 manage.py makemigrations

 执行sql语句生成数据表命令:python3 manage.py migrate

13、user 中urls.py中代码: 

"""blog URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r‘^$‘, views.home, name=‘home‘)
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r‘^$‘, Home.as_view(), name=‘home‘)
Including another URLconf
    1. Add an import:  from blog import urls as blog_urls
    2. Add a URL to urlpatterns:  url(r‘^blog/‘, include(blog_urls))
"""
from django.conf.urls import include, url
from .views import user_regist,user_login,user_logout
urlpatterns = [
    url(r^user_regist/$,user_regist,name=user_regist),
    url(r^user_login/$,user_login,name=user_login),
    url(r^user_logout/$,user_logout,name=user_logout),

]

14、user 中views.py中代码: 

 

from django.shortcuts import render,redirect
from django.core.urlresolvers import reverse
from .forms import UserRegisterForm,UserLoginForm
from .models import UserProfile
from django.contrib.auth import authenticate,logout,login
from articles.models import ArticleInfo,TagInfo
# Create your views here.
from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage
def index(request):
    all_articles = ArticleInfo.objects.all()
    #在django内部orm模型查询集上可以支持排序和切片,但是切片不能是负索引
    #浏览排行

    date_time = all_articles.datetimes(add_time,day,order=DESC)

    click_sort = all_articles.order_by(-click_num)[:6]
    #站长推荐
    pro_arts = all_articles.order_by(-add_time)[:6]

    all_tags = TagInfo.objects.all()

    year = request.GET.get(year,‘‘)
    month = request.GET.get(month,‘‘)
    day = request.GET.get(day,‘‘)

    tagid = request.GET.get(tagid, ‘‘)

    if year and month and day:
        all_articles = all_articles.filter(add_time__year=year,add_time__month=month,add_time__day=day)
        all_articles_set = set(all_articles)

    if tagid:
        tag = TagInfo.objects.filter(id=int(tagid))[0]
        all_articles = tag.article.all()
        all_articles_set1 = set(all_articles)
            # all_articles = [article for article in all_tag_articles if article in all_articles]
    try:
        a = list(all_articles_set & all_articles_set1)
        if a:
            all_articles = a
    except:
        pass

    pa = Paginator(all_articles,2)
    pagenum = request.GET.get(pagenum,1)
    try:
        pages = pa.page(pagenum)
    except PageNotAnInteger:
        pages = pa.page(1)
    except EmptyPage:
        pages = pa.page(pa.num_pages)

    return render(request,index.html,{
        # ‘all_articles‘:all_articles
        pages:pages,
        click_sort:click_sort,
        pro_arts:pro_arts,
        all_tags:all_tags,
        tagid:tagid,
        date_time:date_time,
        year:year,
        month:month,
        day:day
    })

def user_register(request):
    if request.method == GET:
        return render(request,reg.html)
    else:
        #实例化form类,用来验证用户提交的数据
       user_register_form =  UserRegisterForm(request.POST)
        #一个判断方法:判断这个form验证是否通过(合法),如果合法返回True,不合法返回False
       if user_register_form.is_valid():
           #如果验证合法,那么会把合法的干净的数据存储在form对象的一个属性cleaned_data
           #当中,这个属性是一个字典,我们可以这样去拿干净的数据
           username = user_register_form.cleaned_data[username]
           email = user_register_form.cleaned_data[email]
           url = user_register_form.cleaned_data[url]
           password = user_register_form.cleaned_data[password]
           password1 = user_register_form.cleaned_data[password1]

           user = UserProfile.objects.filter(username=username)
           if user:
               return render(request,reg.html,{
                   msg:帐号已经存在
               })
           else:
               if password == password1:
                   a = UserProfile()
                   a.username =username
                   a.email = email
                   a.url = url
                   a.password = password
                   a.set_password(password)
                   a.save()
                   return redirect(reverse(users:user_login))
               else:
                   return render(request, reg.html, {
                       msg: 密码不一致
                   })
       else:
           return render(request, reg.html, {
                       user_register_form: user_register_form
                   })


def user_login(request):
    if request.method == GET:
        return render(request,login.html)
    else:
        user_login_form = UserLoginForm(request.POST)
        if user_login_form.is_valid():
            username = user_login_form.cleaned_data[username]
            password = user_login_form.cleaned_data[password]

            user = authenticate(username = username,password = password)
            if user:
                login(request,user)
                return redirect(reverse(index))
            else:
                return render(request,login.html,{
                    msg:用户名或者密码错误
                })
        else:
            return render(request, login.html, {
                user_login_form: user_login_form
            })

def user_logout(request):
    logout(request)
    return redirect(reverse(index))

15、articles 中admin.py中代码: 

from django.contrib import admin

from .models import ArticleInfo,Category,TagInfo,CommentInfo
# Register your models here.


# Create your models here.
class CategoryAdmin(admin.ModelAdmin):
    list_display = [name,add_time]
    fields = [name,add_time]



class ArticleInfoAdmin(admin.ModelAdmin):
    list_display = [title, author,desc,content,is_delete,click_num,love_num,image,add_time,category]
    fields = [title, author,desc,content,is_delete,click_num,love_num,image,add_time,category]



class TagInfoAdmin(admin.ModelAdmin):
    list_display = [name, add_time]
    fields = [name, add_time,article]
    filter_horizontal = [article]



class CommentInfoAdmin(admin.ModelAdmin):
    list_display = [comment_man, add_time,comment_art,comment_content,is_delete]
    fields = [comment_man, add_time,comment_art,comment_content,is_delete]

admin.site.register(Category,CategoryAdmin)
admin.site.register(ArticleInfo,ArticleInfoAdmin)
admin.site.register(TagInfo,TagInfoAdmin)
admin.site.register(CommentInfo,CommentInfoAdmin)

16、articles 中models.py中代码:

from django.db import models
from datetime import datetime
from users.models import UserProfile
# Create your models here.
class Category(models.Model):
    name = models.CharField(max_length=20,verbose_name="文章类别")
    add_time = models.DateTimeField(default=datetime.now,verbose_name="添加时间")

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "类别信息"
        verbose_name_plural = verbose_name

class ArticleInfo(models.Model):
    title = models.CharField(max_length=50,verbose_name="文章标题")
    author = models.ForeignKey(UserProfile,verbose_name=文章作者)
    category = models.ForeignKey(Category,verbose_name="所属类别",null=True,blank=True)
    desc = models.CharField(max_length=200,verbose_name="文章摘要")
    content = models.TextField(verbose_name="文章内容")
    is_delete = models.BooleanField(default=False,verbose_name="是否删除")
    click_num = models.IntegerField(default=0,verbose_name="浏览量")
    love_num = models.IntegerField(default=0,verbose_name="点赞数")
    image = models.ImageField(max_length=200,verbose_name="文章图片",upload_to=article/%y/%m/%d)
    add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间")

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = 文章信息
        verbose_name_plural = verbose_name

class TagInfo(models.Model):
    name = models.CharField(max_length=20,verbose_name=标签名称)
    article = models.ManyToManyField(ArticleInfo,verbose_name="所属文章")
    add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间")
    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "标签信息"
        verbose_name_plural = verbose_name

class CommentInfo(models.Model):
    comment_man = models.ForeignKey(UserProfile,verbose_name="评论人")
    comment_art = models.ForeignKey(ArticleInfo,verbose_name="评论文章")
    comment_content = models.TextField(verbose_name="评论内容")
    is_delete = models.BooleanField(default=False,verbose_name="是否删除")
    add_time = models.DateTimeField(default=datetime.now,verbose_name="评论时间")

    def __str__(self):
        return self.comment_content

    class Meta:
        verbose_name = "评论信息"
        verbose_name_plural = verbose_name

 完成后 注意生成迁移文件命令:python3 manage.py makemigrations

 执行sql语句生成数据表命令:python3 manage.py migrate

17、articles 中urls.py中代码: 

"""blog URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r‘^$‘, views.home, name=‘home‘)
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r‘^$‘, Home.as_view(), name=‘home‘)
Including another URLconf
    1. Add an import:  from blog import urls as blog_urls
    2. Add a URL to urlpatterns:  url(r‘^blog/‘, include(blog_urls))
"""
from django.conf.urls import include, url
from .views import article_detail,comment_add,love_add,article_add
urlpatterns = [
    url(r^article_detail/(\d+)/$,article_detail,name=article_detail),
    url(r^article_add/$, article_add, name=article_add),
    url(r^comment_add/(\d+)/$,comment_add,name=comment_add),
    url(r^love_add/(\d+)/$, love_add, name=love_add),
]

18、articles 中views.py中代码: 

from django.shortcuts import render,HttpResponse,redirect
from django.core.urlresolvers import reverse
from .models import ArticleInfo,TagInfo,Category,CommentInfo
from django.core.paginator import PageNotAnInteger,Paginator,EmptyPage
from django.contrib.auth.decorators import login_required
# import json
from django.http import JsonResponse

# Create your views here.
from blog.settings import MEDIA_ROOT
import os
def article_detail(request,art_id):
    if art_id:
        article = ArticleInfo.objects.filter(id=int(art_id))[0]
        article.click_num += 1
        article.save()

    all_articles = ArticleInfo.objects.all()
    # 在django内部orm模型查询集上可以支持排序和切片,但是切片不能是负索引
    # 浏览排行

    date_time = all_articles.datetimes(add_time, day, order=DESC)

    click_sort = all_articles.order_by(-click_num)[:6]
    # 站长推荐
    pro_arts = all_articles.order_by(-add_time)[:6]

    all_tags = TagInfo.objects.all()

    year = request.GET.get(year, ‘‘)
    month = request.GET.get(month, ‘‘)
    day = request.GET.get(day, ‘‘)

    tagid = request.GET.get(tagid, ‘‘)

    if year and month and day:
        all_articles = all_articles.filter(add_time__year=year, add_time__month=month, add_time__day=day)
        all_articles_set = set(all_articles)

    if tagid:
        tag = TagInfo.objects.filter(id=int(tagid))[0]
        all_articles = tag.article.all()
        all_articles_set1 = set(all_articles)
        # all_articles = [article for article in all_tag_articles if article in all_articles]
    try:
        a = list(all_articles_set & all_articles_set1)
        if a:
            all_articles = a
    except:
        pass

    pa = Paginator(all_articles, 2)
    pagenum = request.GET.get(pagenum, 1)
    try:
        pages = pa.page(pagenum)
    except PageNotAnInteger:
        pages = pa.page(1)
    except EmptyPage:
        pages = pa.page(pa.num_pages)

    return render(request,article.html,{
        article:article,
        pages: pages,
        click_sort: click_sort,
        pro_arts: pro_arts,
        all_tags: all_tags,
        tagid: tagid,
        date_time: date_time,
        year: year,
        month: month,
        day: day
    })

# def article_add(request):
#     if request.method == "GET":
#         all_category = Category.objects.all()
#         return render(request,‘article_add.html‘,{
#             ‘all_category‘:all_category
#         })
#     else:
#         title = request.POST.get(‘title‘)
#         desc = request.POST.get(‘desc‘)
#         image = request.FILES.get(‘image‘)
#         tag = request.POST.get(‘tag‘)
#         category = request.POST.get(‘category‘)
#         content = request.POST.get(‘content‘)
#
#         cat = Category.objects.filter(name=category)[0]
#         art = ArticleInfo()
#         art.title = title
#         art.desc = desc
#         art.content = content
#         art.image = ‘article/‘+image.name
#         art.author_id = request.user.id
#         art.category_id = cat.id
#         art.save()
#
#         tg = TagInfo()
#         tg.name = tag
#         tg.save()
#
#         tg.article.add(art)
#
#         file_name = os.path.join(MEDIA_ROOT,str(art.image))
#         with open(file_name,‘wb‘) as f:
#             for c in image.chunks():
#                 f.write(c)
#         return redirect(reverse(‘index‘))


@login_required(login_url=/users/user_login/)
def comment_add(request,art_id):
    if request.user:
        if art_id:
            content = request.POST.get(comment,‘‘)
            com = CommentInfo()
            com.comment_man_id = request.user.id
            com.comment_art_id = int(art_id)
            com.comment_content = content
            com.save()
            return redirect(reverse(articles:article_detail,args=[art_id]))


def love_add(request,art_id):
    if request.is_ajax():
        art = ArticleInfo.objects.filter(id=int(art_id))[0]
        art.love_num += 1
        art.save()
        result = {a:ok}


        return JsonResponse(result)

def article_add(request):
    if request.method == "GET":
        all_category = Category.objects.all()
        return render(request,article_add.html,{
            all_category:all_category
        })
    else:
        arttitle = request.POST.get(arttitle,‘‘)
        artdesc = request.POST.get(artdesc,‘‘)
        artimage = request.FILES.get(artimage,‘‘)
        artcategory = request.POST.get(artcategory,‘‘)
        arttag = request.POST.get(arttag,‘‘)
        artcontent = request.POST.get(artcontent,‘‘)

        cat = Category.objects.filter(name=artcategory)[0]

        art = ArticleInfo()
        art.title = arttitle
        art.desc = artdesc
        art.image = article/+artimage.name
        art.content = artcontent
        art.category_id = cat.id
        art.author_id = request.user.id
        art.save()

        tag = TagInfo()
        tag.name = arttag
        tag.save()

        tag.article.add(art)




        file_name = os.path.join(MEDIA_ROOT,str(art.image))
        with open(file_name,wb) as f:
            for c in artimage.chunks():
                f.write(c)


        return redirect(reverse(index))

19、在static文件中导入css,js,images等模板静态文件

20、templates文件中base.htms表示父模板,可以让其它与之类似的页面继承:

<!doctype html>
{% load staticfiles %}
<html>
<head>
<meta charset="utf-8">
<title>某某某的个人博客</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<link href=‘{% static ‘css/base.css‘ %}‘ rel="stylesheet">
<link href=‘{% static ‘css/index.css‘ %}‘ rel="stylesheet">
    {% block mycss %}{% endblock %}
<script type="text/javascript" src=‘{% static ‘js/jquery.min.js‘ %}‘></script>
<script type="text/javascript" src=‘{% static ‘js/sliders.js‘ %}‘></script>
<!--[if lt IE 9]>
<script src="{% static ‘js/modernizr.js‘ %}"></script>
<![endif]-->
</head>
<body>
<header>
  <div class="logo">
      <h1>某某某的个人博客</h1>
      {% if request.user.is_authenticated %}
          <ul>
          <li><a href="#">{{ request.user.username }}</a></li>
        <li><a href="{% url ‘users:user_logout‘ %}" style="border-left: 1px solid black">退出</a></li>
          </ul>

      {% else %}
      <ul>
        <li><a href="{% url ‘users:user_login‘ %}">登录</a></li>
        <li><a href="{% url ‘users:user_register‘ %}" style="border-left: 1px solid black">注册</a></li>
      </ul>
      {% endif %}
  </div>
  <nav id="topnav" class="f_r">
    <ul>
      <a href="index.html" target="_blank">首页</a> <a href="news.html" target="_blank">关于我</a> <a href="p.html" target="_blank">文章</a> <a href="a.html" target="_blank">心情</a> <a href="c.html" target="_blank">相册</a> <a href="{% url ‘articles:article_add‘ %}" >发表文章</a>
    </ul>
    <script src="{% static ‘js/nav.js‘ %}"></script>
  </nav>
</header>
<article>
    {% block left %}
    {% endblock %}

  <div class="r_box f_r">
    <div class="tit01">
      <h3>关注我</h3>
      <div class="gzwm">
        <ul>
          <li><a class="xlwb" href="#" target="_blank">新浪微博</a></li>
          <li><a class="txwb" href="#" target="_blank">腾讯微博</a></li>
          <li><a class="rss" href="portal.php?mod=rss" target="_blank">RSS</a></li>
          <li><a class="wx" href="mailto:admin@admin.com">邮箱</a></li>
        </ul>
      </div>
    </div>
    <!--tit01 end-->
    <div class="moreSelect" id="lp_right_select">
      <script>
window.onload = function ()
{
  var oLi = document.getElementById("tab").getElementsByTagName("li");
  var oUl = document.getElementById("ms-main").getElementsByTagName("div");

  for(var i = 0; i < oLi.length; i++)
  {
    oLi[i].index = i;
    oLi[i].onmouseover = function ()
    {
      for(var n = 0; n < oLi.length; n++) oLi[n].className="";
      this.className = "cur";
      for(var n = 0; n < oUl.length; n++) oUl[n].style.display = "none";
      oUl[this.index].style.display = "block"
    }
  }
}
</script>
      <div class="ms-top">
        <ul class="hd" id="tab">
          <li class="cur"><a href="/">浏览排行</a></li>
          <li><a href="/">评论排行</a></li>
          <li><a href="/">站长推荐</a></li>
        </ul>
      </div>
      <div class="ms-main" id="ms-main">
        <div style="display: block;" class="bd bd-news" >
          <ul>
              {% for sort in click_sort %}
            <li><a href="/" target="_blank">{{ sort.title }}</a></li>
              {% endfor %}
          </ul>
        </div>
        <div  class="bd bd-news">
          <ul>
            <li><a href="/" target="_blank">原来以为,一个人的勇敢是,删掉他的手机号码...</a></li>
            <li><a href="/" target="_blank">手机的16个惊人小秘密,据说99.999%的人都不知</a></li>
            <li><a href="/" target="_blank">住在手机里的朋友</a></li>
            <li><a href="/" target="_blank">教你怎样用欠费手机拨打电话</a></li>
            <li><a href="/" target="_blank">你面对的是生活而不是手机</a></li>
            <li><a href="/" target="_blank">豪雅手机正式发布! 在法国全手工打造的奢侈品</a></li>
          </ul>
        </div>
        <div class="bd bd-news">
          <ul>
              {% for pro in pro_arts %}
            <li><a href="/" target="_blank">{{ pro.title }}</a></li>
              {% endfor %}
          </ul>
        </div>
      </div>
      <!--ms-main end -->
    </div>
    <!--切换卡 moreSelect end -->

    <div class="cloud">
      <h3>标签云</h3>
      <ul>
          {% for tag in all_tags %}
        <li><a href="{% url ‘index‘ %}?tagid={{ tag.id }}&pagenum={{ pages.number }}&year={{ year }}&month={{ month }}&day={{ day }}">{{ tag.name }}</a></li>
          {% endfor %}
      </ul>
    </div>
    <div class="tuwen">
      <h3>文章归档</h3>
      <ul>
          {% for date in date_time %}
        <li>
          <p><span class="tutime font-size-18"><a href="{% url ‘index‘ %}?year={{ date.year }}&month={{ date.month }}&day={{ date.day }}">{{ date.year }}年{{ date.month }}月{{ date.day }}日文章归档</a></span></p>
        </li>
          {% endfor %}
      </ul>
    </div>
    <div class="links">
      <h3>友情链接</h3>
      <ul>
        <li><a href="/">web开发</a></li>
        <li><a href="/">前端设计</a></li>
        <li><a href="/">Html</a></li>
        <li><a href="/">CSS3</a></li>
        <li><a href="/">Html5+css3</a></li>
        <li><a href="/">百度</a></li>
      </ul>
    </div>
  </div>
  <!--r_box end -->
</article>
<footer style="position: absolute; bottom: -800px">
  <p class="ft-copyright">某某某的个人博客 蜀ICP备xxxxxxx号-1</p>
  <div id="tbox"> <a id="togbook" href="/"></a> <a id="gotop" href="javascript:void(0)"></a> </div>
</footer>
{% block myjs %}{% endblock %}
</body>
</html>

21、templates中index.html是用来显示主页的,它继承于base.html

{% extends ‘base.html‘ %}
{% load staticfiles %}
{% block left %}
  <div class="l_box f_l">
    <div class="banner">
      <div id="slide-holder">
        <div id="slide-runner"> <a href="/" target="_blank"><img id="slide-img-1" src=‘{% static ‘images/a1.jpg‘ %}‘ alt="" /></a> <a href="/" target="_blank"><img id="slide-img-2" src=‘{% static ‘images/a2.jpg‘ %}‘  alt="" /></a> <a href="/" target="_blank"><img id="slide-img-3" src=‘{% static ‘images/a3.jpg‘ %}‘ alt="" /></a> <a href="/" target="_blank"><img id="slide-img-4" src=‘{% static ‘images/a4.jpg‘ %}‘ alt="" /></a>
          <div id="slide-controls">
            <p id="slide-client" class="text"><strong></strong><span></span></p>
            <p id="slide-desc" class="text"></p>
            <p id="slide-nav"></p>
          </div>
        </div>
      </div>
      <script>
    if(!window.slider) {
    var slider={};
  }

  slider.data= [
    {
        "id":"slide-img-1", // 与slide-runner中的img标签id对应
        "client":"标题1",
        "desc":"这里修改描述 这里修改描述 这里修改描述" //这里修改描述
    },
    {
        "id":"slide-img-2",
        "client":"标题2",
        "desc":"add your description here"
    },
    {
        "id":"slide-img-3",
        "client":"标题3",
        "desc":"add your description here"
    },
    {
        "id":"slide-img-4",
        "client":"标题4",
        "desc":"add your description here"
    }
  ];

    </script>
    </div>
    <!-- banner代码 结束 -->
    <div class="topnews">
      <h2>最新文章</h2>
        {% for article in pages %}
      <div class="blogs">
        <ul>
          <h3><a href="{% url ‘articles:article_detail‘ article.id %}">{{ article.title }}</a></h3>
            <img src="{{ MEDIA_URL }}{{ article.image }}" width="600px" height="250px">
          <p>{{ article.desc }}</p>
          <p class="autor">
              <span class="lm f_l"><a href="/">{{ article.category.name }}</a></span>
              <span class="dtime f_l">{{ article.add_time }}</span>
              <span class="viewnum f_r">浏览(<a href="/">{{ article.click_num }}</a></span>
              <span class="pingl f_r">评论(<a href="/">30</a></span>
          </p>
        </ul>
      </div>
        {% endfor %}
    </div>


    <div id="pagination">
    <ul id="pagination-flickr">
        {% if pages.has_previous %}
    <li class="previous-off"><a href="{% url ‘index‘ %}?pagenum={{  pages.previous_page_number}}&tagid={{ tagid }}&year={{ year }}&month={{ month }}&day={{ day }}">上一页</a></li>
        {% endif %}
      <li class="active">{{ pages.number }}/{{ pages.paginator.num_pages }}</li>
        {% if pages.has_next %}
      <li class="next"><a href="{% url ‘index‘ %}?pagenum={{ pages.next_page_number}}&tagid={{ tagid }}&year={{ year }}&month={{ month }}&day={{ day }}">下一页 &raquo;</a></li>
        {% endif %}
   </ul>
   </div>
  </div>

{% endblock %}

22、templates中login.html用于用户登录,是一个独立的模块:

<!DOCTYPE html>
{% load staticfiles %}
<html>
<head>
        <meta charset="utf-8">
        <link href="{% static ‘css/reglogin.css‘ %}" rel=‘stylesheet‘ type=‘text/css‘ />
        <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <div class="main">
        <div class="header" >
            <h1>登录!</h1>
        </div>
        <p></p>
            <form method="post" action="{% url ‘users:user_login‘ %}">
                {% csrf_token %}
                <ul class="right-form">
                    <h2>登录:</h2>
                    <li><input type="text" placeholder="请输入你的用户名" name="username"/></li>
                    <li><input type="password" placeholder="请输入你的密码" name="password"/></li>
                    <input type="submit" value="登录" >
                    <div class="clear"> </div>
                </ul>
                <div class="clear"> </div>

            </form>
    </div>
<div>
    {{ msg }}
    {% for key,err in user_login_form.errors.items %}
        {{ err }}
    {% endfor %}
</div>
</body>
</html>

23、templates中reg.html用于用户注册,也是一个独立的模块:

<!DOCTYPE html>
{% load staticfiles %}
<html>
<head>
        <meta charset="utf-8">
        <link href="{% static ‘css/reglogin.css‘ %}" rel=‘stylesheet‘ type=‘text/css‘ />
        <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <div class="main">
        <div class="header" >
            <h1>注册帐号</h1>
        </div>
        <p></p>
            <form method="post" action="{% url ‘users:user_register‘ %}">
                {% csrf_token %}
                <ul class="left-form">
                    <h2>创建用户:</h2>
                    <li>
                        <input type="text" placeholder="请输入你的用户名"  name="username"/>
                        <a href="#" class="icon ticker"> </a>
                        <div class="clear"> </div>
                    </li> 
                    <li>
                        <input type="text" placeholder="请输入你的邮箱"  name="email"/>
                        <a href="#" class="icon ticker"> </a>
                        <div class="clear"> </div>
                    </li> 
                    <li>
                        <input type="text" placeholder="请输入你的个人主页"  name="url"/>
                        <a href="#" class="icon ticker"> </a>
                        <div class="clear"> </div>
                    </li> 
                    <li>
                        <input type="password" placeholder="请输入你的密码"   name="password"/>
                        <a href="#" class="icon into"> </a>
                        <div class="clear"> </div>
                    </li> 
                    <li>
                        <input type="password" placeholder="请确认你的密码" name="password1"/>
                        <a href="#" class="icon into"></a>
                        <div class="clear"> </div>
                    </li> 
                    <input type="submit" value="注册">
                    <div class="clear"> </div>
                </ul>
                <div class="clear"> </div>

            </form>
    </div>
<div>
    {{ msg }}
    {% for key,err in user_register_form.errors.items %}
        {{ err }}
    {% endfor %}
{#    {{ user_register_form }}#}

</div>
</body>
</html>

24、templates中article_add.html用于用户增加文章:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="{% url ‘articles:article_add‘ %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    文章标题<input type="text" name="arttitle"><br>
    文章摘要<input type="text" name="artdesc"><br>
    文章图片<input type="file" name="artimage"><br>
    文章类别<select name="artcategory">
                {% for cat in all_category %}
                    <option>{{ cat.name }}</option>
                {% endfor %}
            </select><br>
    文章标签<input type="text" name="arttag"><br>
    文章内容<textarea name="artcontent" cols="30" rows="10"></textarea>
    <input type="submit" name="提交">
</form>
</body>
</html>

25、templates中article.html用于展示用户文章,并且使用了ajax实现点赞功能:

{% extends ‘base.html‘ %}
{% load staticfiles %}
{% block left %}
  <div class="l_box f_l">
    <div class="postdate">
      <div class="month"></div>
      <div class="date"></div>
    </div>
    <div class="title">
        <h2>
            <a href="">{{ article.title }}</a>
        </h2>
        <div class="postmeta">
          <span class="postmeta_author">{{ article.author.username }}</span>
          <span class="postmeta_category"><a href="http://www.baidu.org/?cat=14" rel="category">{{ article.category.name }}</a></span>
          <span class="postmeta_time">{{ article.add_time}}</span>
            <span id="dian" style="background-color: #0063DC">点赞</span>
            <span id="zan">{{ article.love_num }}</span>
        </div><!-- end postmeta -->
        <div class="entry">
          {{ article.content }}
        </div>
        <span class="tags">
            {% for tag in article.taginfo_set.all %}
            <a href="http://www.baidu.org/?tag=android" rel="tag">{{ tag.name }}</a>
            {% endfor %}
        </span>
        <div class="info">
        Address:  <a href="http://www.baidu.org/?p=542" rel="bookmark" title="Announcement: java  开发相关下载(定期更新中)">http://www.baidu.org/?p=542</a>
        </div>

      <div class="commentstitle">
          <span class="trackback">
              <a href="http://www.baidu.org/wp-trackback.php?p=542" rel="trackback" title="Trackback URI">
              </a>
          </span>
          <h3 id="comments">
              <span class="commentsnumber">only {{ article.commentinfo_set.all.count }} comment</span>
              untill now
          </h3>
      </div>

      <ol class="commentlist">
          {% for comm in article.commentinfo_set.all %}
          <li class="alt" id="comment-59418">
                <div class="top">
                    <a href=‘http://www.yopoing.com‘ rel=‘external nofollow‘ class=‘url‘>{{ comm.comment_man.username }}</a>
                    <span class="time"> @
                        <a href="#comment-59418" title="">{{ comm.add_time }}</a>
                    </span>
                </div>
                <div>
                    <img alt=‘‘ src=‘images/default.jpg‘ class=‘avatar avatar-32 photo‘ height=‘32‘ width=‘32‘ />
                </div>
                
                <div class="body">
                                <p>{{ comm.comment_content }}</p>
                </div>
              </li>
          {% endfor %}
      </ol>

    <div id="commentform">
    <h3 id="respond">Add your comment now</h3>

    <div class=‘login_info‘>还没有登陆?可以登录后再评论哦。<big><a href="">&raquo;去登录</a>&nbsp;<a href="">&raquo;去注册</a></big></div>

    <form action="{% url ‘articles:comment_add‘ article.id %}" method="post" id="commentform">
        {% csrf_token %}





    <!--<p><small><strong>XHTML:</strong> You can use these tags: &lt;a href=&quot;&quot; title=&quot;&quot;&gt; &lt;abbr title=&quot;&quot;&gt; &lt;acronym title=&quot;&quot;&gt; &lt;b&gt; &lt;blockquote cite=&quot;&quot;&gt; &lt;cite&gt; &lt;code class=&quot;&quot; title=&quot;&quot; data-url=&quot;&quot;&gt; &lt;del datetime=&quot;&quot;&gt; &lt;em&gt; &lt;i&gt; &lt;q cite=&quot;&quot;&gt; &lt;strike&gt; &lt;strong&gt; &lt;pre class=&quot;&quot; title=&quot;&quot; data-url=&quot;&quot;&gt; &lt;span class=&quot;&quot; title=&quot;&quot; data-url=&quot;&quot;&gt; </small></p>-->

    <p><textarea name="comment" id="comment" cols="25" rows="5" tabindex="4" class="message_input" ></textarea></p>

    <p><input name="submit" type="submit" id="submit" tabindex="5" value="发表" class="button" />
    <input type="hidden" name="comment_post_ID" value="542" />
    <p style="display: none;"><input type="hidden" id="akismet_comment_nonce" name="akismet_comment_nonce" value="999f94e7bf" /></p><p style="display: none;"><input type="hidden" id="ak_js" name="ak_js" value="87"/></p></p>

    </form>
    </div>
    </div>

  </div>
{% endblock %}
{% block myjs %}
    <script src="{% static ‘js/jquery.min.js‘ %}"></script>
    <script>
    $(function () {
        $(#dian).click(function () {
            $.get("{% url ‘articles:love_add‘ article.id %}",function(callback){
                if(callback.a == ok){
                    {#$(#zan).text((parseInt($(#zan).text()) + 1))#}
                     {# 拿zan的数据#}
                    value = parseInt($(#zan).text());
                    value = value + 1;
                    $(#zan).text(value);
                    setTimeout(function () {
                        window.location.href = /;
                    },5000)
                }
            })
        })
    })
    </script>
{% endblock %}

 

用html页面模板使用django完成个人博客

标签:url   nload   微软雅黑   教你   没有   lease   previous   继承   forms   

原文地址:https://www.cnblogs.com/cz-basic/p/9083693.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!