zoukankan      html  css  js  c++  java
  • django 应用各个py文件代码

    views.py
    
    from . import models
    # Create your views here.
    
    def welcome(request):
        s = '你好哇,李银河'
        return HttpResponse(s)
    
    
    def user_info(request):
        username = 'changcaixia'
        username_zh = '常彩霞-使用的replace'
        return render(request,'welcome.html',{'username_zh':username_zh})
        # 下面是模拟render的实现原理
        # f = open(r'C:UsersliuliPycharmProjectssszsky	emplateswelcome.html',encoding='utf-8')
        # content = f.read()
        # new_content = content.replace('{{ username_zh }}',username_zh)
        # return HttpResponse(new_content)
    
    def index(request):
        categories = models.Category.objects.all()  #从数据库取到所有数据
        articles = models.Article.objects.all()
        return render(request,'index.html',{'categories':categories,'articles':articles})
    
    models.py
    
    from django.db import models
    
    # 创建分类表
    class Category(models.Model):
        # 分类名称是不能重复的,所以要加unique=True
        name = models.CharField(verbose_name='分类名称',max_length=20,unique=True)
        create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
        update_time = models.DateTimeField(verbose_name='更新时间', auto_now=True)
    
        # 修改了表结构,只要修改了表结构,就要执行python manage.py makemigrations,python manage.py migrate
        class Meta:
            db_table = 'category'  #创建表的时候表名
            verbose_name = '分类'
            verbose_name_plural = verbose_name
            ordering = ['create_time','name'] #默认升序,可以根据多个字段排序
            # ordering =  [-'create_time']  #降序
    
    def category_fun():
        return 883
    
    # Create your models here.
    class Article(models.Model):
        # 如果是CharField类型的话,必须得写最长的字符串是多少max_length
        # title = models.CharField(verbose_name='标题', max_length=25,default='',blank=True) default是默认的标题,如果文章标题可以为空的话,加blank=True,
        title = models.CharField(verbose_name='标题',max_length=25)  #对应数据库的varchar类型,字符串
        content = models.TextField(verbose_name='文章内容')  #长文本类型,文本比较大的时候用它,如果用TextField,就不用指定max_length, CharField存比较短的字符串
        img = models.ImageField(upload_to='article',blank=True)  #upload_to代表上传到哪里
        category = models.ForeignKey(Category,on_delete=models.SET(category_fun),db_constraint=False,verbose_name='分类')
        # category = models.ForeignKey(Category, on_delete=models.CASCADE) #假如分类被删除,文章也会被删除
        '''
        db_constraint=False 实际不会真的在表里面创建外键关系,
        on_delete=models.PROTECT 删除关联数据,引发错误ProtectedError,是受保护的,不让删除,由django级别抛出的,
        只要这个分类下面有文章,这个分类就不能被删除
        on_delete=models.DO_NOTHING 假如分类下面有2个文章,分类被删除,文章不受影响
        on_delete=models.CASCADE 关联的数据也会被删除;假如分类下面有2个文章,文章被删除,文章里面的分类也会被删除
        on_delete=models.SET_NULL分类被删除,分类被设置成空,前提是允许这个字段为空
        on_delete=models.SET_DEFAULT分类被删除,分类被设置成默认值,前提是这个字段有默认值
        on_delete=models.SET 指定一个函数,分类被删除后调用传过来的方法,用方法返回值
        比如执行这条删除命令后,查看效果models.Category.objects.get(id=5).delete()
        '''
        create_time = models.DateTimeField(verbose_name='创建时间',auto_now_add=True)  #自动创建时间,只对时间类型有效
        update_time = models.DateTimeField(verbose_name='更新时间',auto_now=True)  #自动修改时间,只对时间类型有效
    
        class Meta:
            db_table = 'article'  #创建表的时候表名
            verbose_name = '文章表'
            verbose_name_plural = verbose_name
            ordering = ['create_time'] #默认升序,可以根据多个字段排序
            # ordering =  [-'create_time']  #降序
    # 默认的表名:sky_user_category  :app的名字+类名
    
    tests.py
    
    from django.test import TestCase
    import os,django
    # Create your tests here.
    # 先定义,再导入,如果不定义就导入就会报错,因为你还没有设置配置文件,他不知道从哪个目录导入
    os.environ.setdefault('DJANGO_SETTINGS_MODULE','sky.settings')
    django.setup()
    from sky_user import models
    
    # 基本的增删改查
    
    #增
    '''方式1'''
    category = models.Category(name='Java')
    category.save()
    
    '''方式2'''
    models.Category.objects.create(name='明天要考试啦')
    models.Category.objects.create(name='加油啊')
    
    '''
    方式1和方式2的区别:
    方式1,一次只能增加一条;方式1采用实例化的方法,需要手动save一下
    方式2,一次可以增加多条;方式2不需要save
    '''
    # 删
    # 单个删除
    c1 = models.Category.objects.get(id =4)
    c1.delete()
    # 批量删除
    q = models.Category.objects.filter(name='python1')
    q.delete()
    
    # 改
    '''
    方式1:单个数据修改
    '''
    c1 = models.Category.objects.get(id =3)
    c1.name = 'Java'
    c1.save()
    '''
    方式2
    '''
    q = models.Category.objects.filter(name='Python')
    q.update(name = 'python1')
    # print(dir(q)) 查询有哪些方法的命令
    # 查
    '''
    方法1:get
    get只能返回一条数据,如果返回多条会报错,就是指定的条件必须是唯一的,
    如果指定的条件查询不到数据,也会报错,但是查询条件可以有多个
    返回的c1是一个对象,要取值的话,方法如下'''
    c1 = models.Category.objects.get(id =1)
    c1 = models.Category.objects.get(name ='Python')  #  条件不唯一,会报错
    c1 = models.Category.objects.get(name='Linux',id =2) #多个查询条件
    print(c1.name)
    print(c1.id)
    
    '''方法2: filter'''
    query_set = models.Category.objects.filter(id =1,name='Python')  #返回的是list,即使只有一条数据,()里面有多个值就是多个查询条件,相当于and
    query_set = models.Category.objects.filter() #什么条件也不传,就是查询全部的
    print(query_set)
    # c = query_set.first()  #查询第一条数据
    c = query_set[0]  #查询第一条数据,也可以通过下标来取值
    print(c.id)
    print(c.name)
    
    # models.Category.objects.all() #也是查询所有的数据
    
    # 在文章表插入外键的两种方式
    c = models.Category.objects.get(id=5)
    a = models.Article(title='django项目配置',content='django项目配置django项目配置django项目配置',category=c)
    a.save()
    a2 = models.Article(title='django项目配置',content='django项目配置django项目配置django项目配置',category_id=6)
    a2.save()
    a2 = models.Article(title='mary项目配置',content='mary项目配置django项目配置django项目配置',category_id=7)
    a2.save()
    
    # 查询外键的方式
    a = models.Article.objects.get(id=1)
    print(a.title)
    print(a.category.name)
    print(a.category.id)
    
    
    templates下面的index.html
    文章内容返回的代码:
    
    <div class="summary-list">
                        {% for article in articles %}
                        <div class="media mb-1 mb-sm-2 p-2 p-lg-3">
                            <div class="align-self-center mr-2 mr-lg-3 w-25 modal-open">
                                <a href="./detail.html" target="_blank">
                                    <img class="w-100 article-img" src="https://tendcode.com/cdn/article/191029/python_shell.png"
                                         alt="{{article.title}}">
                                </a>
                            </div>
                            <div class="media-body">
    
                                <div class="text-muted mb-2 f-12">
    
    
                                    <img class="avatar"
                                         src="https://tendcode.com/media/avatar/2019/07/27/91ef76c6a7efce1b99717f97a851f3deb48f6510.png"
                                         alt="Hopetree">
    
                                    <span>Hopetree</span>
                                    <span><i class="fa fa-calendar-times-o ml-2 mr-1"></i>2 周,3天前</span>
                                </div>
                                <h2 class="mt-0 font-weight-bold text-info f-17">
                                    <a href="/article/yaml_and_jinja2/" target="_blank">{{article.title}}</a>
                                </h2>
                                <p class="d-none d-sm-block mb-2 f-15">{{article.content}}</p>
                                <div class="text-muted mb-0 f-12">
                                    <a class="cate" href="/category/hello-python/" title="查看当前分类下更多文章">
                                        <i class="fa fa-book mr-1"></i>{{article.category.name}}</a>
                                    <span><i class="fa fa-eye ml-2 mr-1"></i>226</span>
                                    <a href="/article/yaml_and_jinja2/#comment-block" target="_blank" title="查看文章评论">
                                        <i class="fa fa-comments ml-2 mr-1"></i>8</a>
                                </div>
                            </div>
                        </div>
                        {% endfor %}
    
    
    文章分类返回的代码:
    
                            {% for category in categories %}
                            <li class="list-group-item d-flex justify-content-between align-items-center pr-2 py-2">
                                <a class="category-item" href="./category.html"
                                   title="查看{{category.name}}分类下所有文章">{{category.name}}</a>
                                <span class="badge text-center" title="当前分类下有6篇文章">6</span>
                            </li>
                            {% endfor %}
    
  • 相关阅读:
    leetcode--Populating Next Right Pointers in Each Node II
    leetcode—Populating Next Right Pointers in Each Node
    Pascal's Triangle II
    leetcode—pascal triangle
    leetcode—triangle
    October 23rd, 2017 Week 43rd Monday
    October 22nd, 2017 Week 43rd Sunday
    October 21st 2017 Week 42nd Saturday
    October 20th 2017 Week 42nd Friday
    October 19th 2017 Week 42nd Thursday
  • 原文地址:https://www.cnblogs.com/liulilitoday/p/13543722.html
Copyright © 2011-2022 走看看