1. 程式人生 > >Just for fun的專欄

Just for fun的專欄

pip install Django==1.11.1

import django

print(django.get_version()) 建立一個Django專案:django-admin startproject mysite

python3 manage.py runserver

建立應用:python3 manage.py startapp blog

manage.py是對django-admin的簡單封裝

./mysite/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
]

./blog/models.py

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

# Create your models here.
class BlogArticles(models.Model):
	title = models.CharField(max_length=300)
	author = models.ForeignKey(User, related_name="blog_posts", on_delete=models.DO_NOTHING)
	body = models.TextField()
	publish = models.DateTimeField(default=timezone.now)

	class Meta:
		ordering = ("-publish",)

	def __str__(self):
		return self.title

建立資料庫表的檔案:python3 manage.py makemigrations

python3 manage.py sqlmigrate blog 0001

真正建立資料庫:python3 manage.py migrate

建立超級管理員:python3 manage.py createsuperuser

python3 manage.py runserver

釋出文章:./blog/admin.py

from django.contrib import admin
from .models import BlogArticles
# Register your models here.
admin.site.register(BlogArticles) #將類加入當前環境

pip3 install pytz 用於django.utils.timezone

./blog/admin.py

from django.contrib import admin
from .models import BlogArticles
# Register your models here.
class BlogArticlesAdmin(admin.ModelAdmin):
	list_display = ("title", "author", "publish")
	list_filter = ("publish", "author")
	search_fields = ("titles", "body")
	raw_id_fields = ("author",)
	date_hierarchy = "publish"
	ordering = ['publish', 'author']
admin.site.register(BlogArticles, BlogArticlesAdmin)

顯示部落格資訊

./blog/views.py

from django.shortcuts import render
from .models import BlogArticles
# Create your views here.
def blog_title(request):
	blogs = BlogArticles.objects.all()
	return render(request, "blog/titles.html", {"blogs":blogs})

mysite/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls', namespace="blog")),
]

blog/urls.py

from django.conf.urls import url, re_path
from . import views
app_name = 'blog'

urlpatterns = [
	#url(r'^$', views.blog_title, name="blog_titles")
	re_path('$', views.blog_title, name="blog_titles")
]