Django(完整)

本文档详细介绍了在Django框架下如何管理文章。从在models.py中设置文章模型,到在admin.py中注册模型,再到数据库迁移和后台添加文章,最后通过views.py、templates和urls.py实现文章内容的显示。
##一. 创建 Django project
C:\Users\Administrator>cd C:\Users\Administrator\Desktop\standardweb

C:\Users\Administrator\Desktop\standardweb>django-admin startproject firstsite
文件结构为:
##二. 创建 Django App ###1.创建Django app Django project和Django app的区别 ![这里写图片描述](https://img-blog.youkuaiyun.com/20170520102251491?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvR2Vla0xlZWU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
C:\Users\Administrator\Desktop\standardweb>cd firstsite

C:\Users\Administrator\Desktop\standardweb\firstsite>python manage.py startapp firstapp
文件结构如下:
###2.settings.py中增加app ###
##三. 创建数据库 ###1.合并运行数据库
C:\Users\Administrator\Desktop\standardweb\firstsite>python manage.py makemigrat
ions
No changes detected

C:\Users\Administrator\Desktop\standardweb\firstsite>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying sessions.0001_initial... OK

C:\Users\Administrator\Desktop\standardweb\firstsite>python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
May 20, 2017 - 10:33:13
Django version 1.11.1, using settings 'firstsite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
##四. 把 html,CSS,图片放到模板里 ###1.在firstapp中创建templates和static文件夹 ### html文件放在templates文件夹下,css、images所有静态文件放在static文件夹下
###2.在settings.py中修改模板路径
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR), 'templates'.replace('\\','/')],####
        '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',
            ],
        },
    },
]
###3.在html中增加模板标签,修改css、images等静态文件路径
#在html首行增加
{% load staticfiles %}
#把css路径替换为这个
href="{% static 'css/semantic.css' %}"
#把所有图片路径替换为类似这个格式
{% static 'images/star_banner.jpg' %}
##五. 创建后台和超级管理员## ###1.cd 到 firstsite目录下,创建超级管理员
python manage.py createsuperuser

执行runserver,进入管理员页面http://127.0.0.1:8000/admin/,登录密码

###2.在admin管理后台增加管理后台的数据 在firstapp/models.py中创建数据库模型
from django.db import models

# Create your models here.
class People(models.Model):
    name = models.CharField(null=True, blank=True,max_length=200)
    job = models.CharField(null=True, blank=True, max_length=200)
在firstapp/admin.py中引入注册数据库模型
from django.contrib import admin
from firstapp.models import People

# Register your models here.
admin.site.register(People)
###3.迁移数据库,合并数据库,运行服务器,刷新管理员页面
C:\Users\Administrator\Desktop\website\firstsite>python manage.py makemigrations
C:\Users\Administrator\Desktop\website\firstsite>python manage.py migrate
C:\Users\Administrator\Desktop\website\firstsite>python manage.py runserver
###4.管理后台新增内容 ###

5.在models里面设置列表直接显示内容的标题

为了让内容列表里能直接显示标题,需要到models.py里面增加一个直接显示名字的函数

from django.db import models

# Create your models here.
class People(models.Model):
    name = models.CharField(null=True, blank=True,max_length=200)
    job = models.CharField(null=True, blank=True, max_length=200)
    def __str__(self):#新增
        return self.name#新增

刷新页面可以直接看到内容标题。

6.在admin中继续增加文章管理

(1)在firstapp/models.py中创建文章的数据库模型
from django.db import models

# Create your models here.
class People(models.Model):
    name = models.CharField(null=True, blank=True,max_length=200)
    job = models.CharField(null=True, blank=True, max_length=200)
    def __str__(self):
        return self.name

class Aritcle(models.Model):#新增
    headline = models.CharField(null=True, blank=True,max_length=500)#新增
    content = models.TextField(null=True, blank=True)#新增
    def __str__(self):#新增
        return self.headline#新增
(2)在firstapp/admin.py中注册文章的数据库模型
from django.contrib import admin
from firstapp.models import People,Aritcle#新增

# Register your models here.
admin.site.register(People)
admin.site.register(Aritcle)#新增
(3)在models.py下的cmd中迁移数据库和合并数据库
C:\Users\Administrator\Desktop\standardweb\firstsite>python manage.py makemigrations
Migrations for 'firstapp':
  firstapp\migrations\0002_aritcle.py
    - Create model Aritcle

C:\Users\Administrator\Desktop\standardweb\firstsite>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, firstapp, sessions
Running migrations:
  Applying firstapp.0002_aritcle... OK
(4)在后台管理员页面添加文章标题和内容

这里写图片描述

这里写图片描述
填写完文章,刷新页面

(5)在view层(fristapp/views.py)引入models中的文章数据
from django.shortcuts import render, HttpResponse
from firstapp.models import People, Aritcle
from django.template import Context, Template

# Create your views here.
def index(request):
    context = {}#新建字典
    article_list = Aritcle.objects.all()#变量article_list储存Article所有的文章
    context['article_list'] = article_list #字典context中的article_list键(html中通过检索键提取文章内容)对应article_list变量的值
    index_page = render(request, 'first_web_2.html', context)
    return index_page
(6)在template层中替换文章变量,遍历文章
{% load staticfiles %}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>first web</title>
        <link rel="stylesheet" href="{% static 'css/semantic.css' %}"  media="screen" title="no title" charset="utf-8">
        <link href="https://fonts.googleapis.com/css?family=Oswald|Raleway" rel="stylesheet">


        <style type="text/css">
            h1 {
                font-family:'Oswald', sans-serif!important;
                font-size:40px;
            }

            body {
                font-family: 'Raleway', sans-serif;
            }
            p {
                font-family: 'Raleway', sans-serif;
                font-size:18px;
            }
            .ui.vertical.segment.masthead {
                height: 300px;
                background-image: url({% static 'images/star_banner.jpg' %});
                background-size: cover;
                background-position: 100% 80%;
            }

            .ui.container.segment {
                width: 800px;
            }

            .ui.center.aligned.header.blogslogon {
                margin-top: 40px;
            }

            .ui.center.aligned.header.blogslogon p {
                margin-top: 10px;
                color: white;
                font-size: 10px;
            }
            .ui.container.nav {
                width: 500px;
            }

        </style>
    </head>
    <body>
        <div class="ui inverted vertical  segment masthead">

            <h1 class="ui center aligned header blogslogon" style="font-size:50px;font-family: 'Raleway', sans-serif!important;">
                Bloger
                <p class="ui sub header">
                    everyone has a story to tell
                </p>

            </h1>
        </div>
        <div class="ui container nav">
            <div class="ui borderless text three item menu ">
                <div class="ui simple dropdown  item">
                    Categories
                    <i class="dropdown icon"></i>
                    <div class="menu">
                        <a class="item" href="">life</a>
                        <a class="item" href="">tech</a>
                    </div>
                </div>
                <a class="item">
                    Popular
                </a>
                <a class="item">
                    About
                </a>

            </div>
        </div>

        <div class="ui divider"></div>

        <div class="ui  vertical segment">
            {% for article in article_list %}
                <div class="ui container vertical segment">
                    <a href="#">
                        <h1 class="ui header">
                            {{ article.headline }}
                        </h1>
                    </a>

                    <i class="icon grey small unhide">10,000</i>
                    <p>
                        {{ article.content|truncatewords:100 }}
                        <a href="#">
                            <i class="angle tiny double grey right icon">READMORE</i>
                        </a>
                    </p>

                    <div class="ui mini  tag label">
                        life
                    </div>
                </div>
            {% endfor %}


        </div>

        <div class="ui inverted  vertical very padded  segment">
            Mugglecoding®
        </div>
    </body>
</html>
(7)在firstsite/urls.py中给函数分配url地址
"""firstsite URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/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. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from firstapp.views import index#从view层引入函数index

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index', index, name='index'),#url(‘url地址’,函数名,查找方便名)
]
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值