一、進入虛擬環境: workon 虛擬環境名javascript
二、找到咱們的項目管理文件夾django,進入建立項目django-admin startproject blogphp
三、進入到咱們的項目文件夾當中,建立咱們的第一個應用 python manage.py startapp user 用於用戶管理css
建立咱們的第二個應用python manage.py startapp articles 用於文章管理html
四、使用pycharm打開建立的項目blog,在pycharm當中設置項目的虛擬環境前端
五、因爲咱們在建立項目的過程當中會遇到兩個或者以上的應用,爲了便於管理,咱們通常建立一個新的文件夾(apps)用於管理全部的應用:java
六、而後將apps設置成爲根目錄:python
七、將應用拖入apps中:mysql
八、設置settingsjquery
""" 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')
九、再到mysql數據庫裏建立數據庫blog。android
十、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}) ]
十一、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)
十二、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
1三、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'), ]
1四、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'))
1五、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)
1六、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
1七、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'), ]
1八、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'))
1九、在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>
2一、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 }}">下一頁 »</a></li> {% endif %} </ul> </div> </div> {% endblock %}
2二、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>
2三、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>
2四、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>
2五、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="">»去登陸</a> <a href="">»去註冊</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: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url=""> </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 %}