• Django开发博客一(搭建模型和准备数据)


    一.环境搭建

    1.创建虚拟环境

    virtualenv blogenv

    2.安装django1.11

    pip install django==1.11

    3.新建工程

    django-admin startproject myblog

    4.创建工程下的应用(进入工程目录下)

    django-admin startapp blog

    django-admin startapp comment

    5.打开pycharm,在setting文件中完成基本设置

    LANGUAGE_CODE = 'zh-hans'
    
    TIME_ZONE = 'Asia/Shanghai'
    #在INSTALLED_APPS中激活blog,comment
    INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
    'comment'
    ]
    #在Templates中设置templates更目录位置
    'DIRS': [os.path.join(BASE_DIR,'templates')],

    二.编写模型

    1.在models文件中编写Post模型

    from django.db import models
    from django.contrib.auth.models import User
    # Create your models here.
    from django.utils import timezone
    import markdown
    from django.utils.html import strip_tags


    class Category(models.Model):
    name=models.CharField(max_length=100,verbose_name='类别')
    slug=models.SlugField()
    def __str__(self):
    return self.name
    class Meta:
    ordering=('name',)
    verbose_name='类别'
    verbose_name_plural=verbose_name
    class Post(models.Model):
    category=models.ForeignKey(Category,verbose_name='类别',on_delete=models.CASCADE)
    auth=models.ForeignKey(User,verbose_name='作者',on_delete=models.CASCADE)
    slug=models.SlugField()
    title=models.CharField(max_length=200,verbose_name='标题')
    excert=models.CharField(max_length=200,verbose_name='摘要')
    content=models.TextField(verbose_name='正文')
    created=models.DateTimeField(auto_now_add=True,verbose_name='创建时间')
    updated=models.DateTimeField(auto_now=True,verbose_name='更新时间')
    status=models.CharField(choices=(('publish','已发表'),('unpublish','未发表')),default='publish',max_length=20)
    publish=models.DateTimeField(verbose_name='发表时间',default=timezone.now)
    def __str__(self):
    return self.title
    class Meta:
    verbose_name='博文'
    verbose_name_plural=verbose_name
    ordering=['status','-publish']
      #用markdown处理文本内容,根据文本内容生成摘要
    def save(self,*args,**kwargs):
    md = markdown.Markdown(
    extensions=[
    'markdown.extensions.extra',
    'markdown.extensions.codehilite',
    ]
    )
        #markdown处理
    self.content=md.convert(self.content)
    if not self.excert:
            #strip_tags将HTML转成字符串
    self.excert=strip_tags(self.content)[:54]
    super(Post, self).save(*args,**kwargs)

    2.生成数据迁移表

    #python manage.py makemigrations

    3.数据迁移

    #python manage.py migrate

    4.在admin.py中注册模型(django自带的后台管理系统,提供一个良好的管理界面,更强大的有xadmin)

    from django.contrib import admin
    from .models import Post,Category
    # Register your models here.
    class CategoryAdmin(admin.ModelAdmin):
        #需要显示字段
        list_display = ['name']
        #当slug为空时,根据name字段生成slug
        prepopulated_fields = {'slug':('name',)}
    admin.site.register(Category,CategoryAdmin)
    class PostAdmin(admin.ModelAdmin):
        list_display = ['title','excert','status','publish']
        #字段筛选器
        list_filter = ['publish']
        prepopulated_fields = {'slug':('title',)}
        #搜索框
        search_fields = ['title','content']
        #排序
        ordering = ['status','-publish']
    admin.site.register(Post,PostAdmin)

    5.创建管理员账号

    #python manage.py createsuperuser

    6.启动服务,并登录http://127.0.0.1:8000/admin/

    python manage.py runsever

    三.从Excel读取数据到django数据库中

     1.新建data文件夹,将3-wp_posts.xlsx放入该文件夹

    2.代码编写,详情看注释

    import openpyxl
    '''
    2007版以前的Excel(xls结尾的),需要使用xlrd读,xlwt写。
    2007版以后的Excel(xlsx结尾的),需要使用openpyxl来读写。
    '''
    def read07Excel(path,mlst):
        wb=openpyxl.load_workbook(path)
        sheet=wb.get_sheet_by_name('wp_posts')
        j=0
        for row in sheet.rows:
            i=0
            if j!=0:
                 mlst2 = []
                 for cell in row:
                    if i==4 or i==5:
                        mlst2.append(cell.value)
                    i=i+1
                 mlst.append(mlst2)
            j+=1
    file_path='data/3-wp_posts.xlsx'
    mlst=[]
    read07Excel(file_path,mlst)
    # print(mlst)
    import os
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myblog.settings")
    import django
    import random
    django.setup()
    from blog.models import Post,Category
    from django.contrib.auth.models import User
    from django.shortcuts import get_object_or_404
    def main(category,user,content,title):
        Post.objects.create(category=category,auth=user,content=content,title=title)
    categories=Category.objects.all()
    user=get_object_or_404(User,username='admin')
    for i in range(25):
        category=random.choice(categories)
        for lst in mlst:
             main(category,user,lst[0],lst[1])
  • 相关阅读:
    bryce1010的图像处理课程设计
    linux常用命令
    linux自动连接校园网设置
    LoadRunner12学习之路(6-8)
    LoadRunner12学习之路(1-5)
    Windows软件推荐
    LoadRunner_11破解教程完整版
    linux的SHELL编程
    菜鸡CodeFoces打卡单
    21天记完托福单词打卡
  • 原文地址:https://www.cnblogs.com/hhy-love-python/p/8496316.html
Copyright © 2020-2023  润新知