首页 > 编程学习 > Django(二)

Django(二)

发布时间:2022/10/1 14:14:33

例一:

django-admin startproject wangzhe

cd wangzhe

python manage.py startapp app

# settings.py
INSTALLED_APPS = [
    'app',
]

TEMPLATES = [
    {
        'DIRS':  [os.path.join(BASE_DIR, 'templates')],
    },
]

LANGUAGE_CODE = 'zh-hans'
# models.py

from django.db import models


# Create your models here.


# 英雄类型表
class HeroType(models.Model):
    title = models.CharField(verbose_name='名称', max_length=5)

    def __str__(self):
        return self.title


# 英雄
class Hero(models.Model):
    name = models.CharField(verbose_name='名字', max_length=10)
    gender = models.IntegerField(verbose_name='性别')
    age = models.IntegerField(verbose_name='年龄')
    ht = models.ForeignKey(to=HeroType, on_delete=models.CASCADE)

    def __str__(self):
        return self.name


# 技能表
class Kill(models.Model):
    name = models.CharField(verbose_name='技能名字', max_length=10)
    cd = models.IntegerField(verbose_name='冷却时间')
    da = models.IntegerField(verbose_name='伤害值')
    hero = models.ForeignKey(to=Hero, on_delete=models.CASCADE)

    def __str__(self):
        return self.name
# views.py
from django.shortcuts import render
from .models import HeroType, Hero, Kill
from django.http import HttpResponse


# Create your views here.


def index(request):
    '''
    接受用户请求,处理业务逻辑
    :param request:
    :return:
    '''

    '''
    找数据
    '''
    hts = HeroType.objects.all()  # 查询全部

    # 构造字典
    ctx = {
        'hts': hts
    }

    return render(request, 'index.html', ctx)


def show(request, id):
    '''

    :param request:
    :param id: 英雄类型的主键
    :return:
    select * from app_hero where ht_id = id
    '''
    heros = Hero.objects.filter(ht=id).all()

    # ctx = {
    #     'heros':heros
    # }
    return render(request, 'show.html', locals())


def kill(request, id):
    kills = Kill.objects.filter(hero=id).all()
    return render(request, 'kill.html', locals())
# urls.py
from django.contrib import admin
from django.urls import path
from app import views


urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index),
    path('type/<int:id>/', views.show),
    path('kill/<int:id>/', views.kill),
]

 新建一个templates文件夹

{#index.html#}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<h1>欢迎来到王者学院</h1>
<ul>
    {% for ht in hts %}
        <li><a href="/type/{{ ht.id }}/">{{ ht.title }}</a></li>
    {% endfor %}

</ul>

</body>
</html>



{#kill.html#}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>技能列表</title>
</head>
<body>
<ul>
    {% for kill in kills %}
        <li>{{ kill.name }}</li>
    {% endfor %}

</ul>


</body>
</html>

{#show.html#}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>英雄列表</title>
</head>
<body>
<ul>
    {% for hero in heros %}
        <li><a href="/kill/{{ hero.id }}/">{{ hero.name }}---{{ hero.age }}---{{ hero.gender }}</a></li>
    {% endfor %}


</ul>


</body>
</html>


python manage.py makemigrations

python manage.py migrate

# admin.py
from django.contrib import admin
from .models import *

# Register your models here.

admin.site.register(Hero)
admin.site.register(HeroType)
admin.site.register(Kill)

python manage.py createsuperuser

python manage.py runserver 8001

打开浏览器,输入网址http://127.0.0.1:8001/admin/

 

例二:

django-admin startproject top_news

cd top_news

python manage.py startapp news

# settings.py

INSTALLED_APPS = [
    'news.apps.NewsConfig',
]

TEMPLATES = [
    {
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
    }
]

# 配置数据库
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db_1907',
        'USER': 'root',
        'PASSWORD': '123456',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'


#models.py

from django.db import models


# Create your models here.

class BaseModel(models.Model):
    isdelete = models.BooleanField(verbose_name='是否删除', default=False)
    ext = models.CharField(verbose_name='扩展字段', default='{}', max_length=1024)
    created_time = models.DateTimeField(verbose_name='名字', auto_now_add=True)
    update_time = models.DateTimeField(verbose_name='名字', auto_now=True)

    class Meta:  # 如果该类不生成表,把该类写成抽象类,只做为继承作用
        abstract = True


# 分类表
class Category(BaseModel):
    name = models.CharField(verbose_name='名字', max_length=6, null=False, unique=True)
    position = models.IntegerField(verbose_name='排序', null=False)

    class Meta:
        verbose_name = '分类'
        verbose_name_plural = verbose_name
        ordering = ['-position']

    def __str__(self):
        return self.name


# 新闻类
class News(BaseModel):
    title = models.CharField(verbose_name='标题', max_length=255, null=False, unique=True)
    content = models.TextField(verbose_name='内容', null=False, max_length=4000)
    src = models.URLField(verbose_name='封面', null=False)
    vnum = models.IntegerField(verbose_name='浏览量', default=0)
    isoriginal = models.BooleanField(verbose_name='是否原创')
    istop = models.BooleanField(verbose_name='是否置顶', default=False)
    category = models.ForeignKey(to=Category, on_delete=models.CASCADE)

    class Meta:
        verbose_name = '新闻'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.title
#admin.py

from django.contrib import admin
from .models import *


# Register your models here.
class NewManager(admin.ModelAdmin):
    list_display = ['id', 'vnum', 'isdelete']


admin.site.register(Category)
admin.site.register(News, NewManager)
# views.py

from django.shortcuts import render
from .models import Category, News
from django.http import HttpResponse
from django.shortcuts import redirect  # 重定向


# Create your views here.
def index(request):
    categorys = Category.objects.filter(isdelete=False).order_by('-position').all()
    return render(request, 'index.html', locals())


def detail(request, id):
    # News.objects.filter(id=id).all() # 返回的列表
    news = News.objects.get(id=id)  # 返回的对象
    return render(request, 'detail.html', locals())


def delete(request, id):
    news = News.objects.filter(id=id).first()
    if news:
        # news.delete()
        news.isdelete = True
        news.save()
        return redirect('/')  # 首页

    else:
        return HttpResponse('数据不存在')
# urls.py

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('news.urls')),
]

在news文件夹中新建一个urls.py文件

from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index),
    path('news/<int:id>/', views.detail),
    path('del/<int:id>/', views.delete),
]

 

# index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>


<div>
    {% for category in categorys %}
        <h3>{{ category.name }}</h3>
        <ul>
            {% for news in category.news_set.all %}
                {% if not news.isdelete %}
                    <li><a href="/news/{{ news.id }}/">{{ news.title }}</a>-----------<a
                            href="/del/{{ news.id }}/">删除</a></li>
                {% endif %}
            {% endfor %}
        </ul>

    {% endfor %}


</div>
<ul>


</ul>

</body>
</html>
# detail.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ news.title }}</title>
    <link rel="stylesheet" type="text/css" href="/static/css/style.css">
</head>
<body>

<div class="center">
    <h1>{{ news.title }}</h1>
    <span>时间:{{ news.created_time }}</span>
    <span>浏览量:{{ news.vnum }}</span>
    <div>
        <img src="{{ news.src }}" alt="">
        <p>{{ news.content }}</p>
    </div>

</div>

</body>
</html>

新建一个static文件夹

css文件夹

.center {
    text-align: center;
}

python manage.py makemigrations

python manage.py migrate

python manage.py createsuperuser

python manage.py runserver 8002

打开浏览器,输入网址http://127.0.0.1:8002/admin/

如果报错:django.core.exceptions.ImproperlyConfigured: mysqlclient 1.4.0 or newer is required; you have 0.9.3.

原因:MySQLclient 版本跟不上自己高版本的 python

解决方案:

# top_news/__init__.py
import pymysql
pymysql.version_info = (1, 4, 13, "final", 0)
pymysql.install_as_MySQLdb()  # 使用pymysql代替mysqldb连接数据库

Copyright © 2010-2022 mfbz.cn 版权所有 |关于我们| 联系方式|豫ICP备15888888号