Django2学习笔记--入门篇(2)

    科技2024-09-29  24

    django基本应用结构

    个人学习笔记,内容不作为各位学习参考

    创建应用

    1、在项目文件路径下打开cmd执行命令python manage.py startapp article ,article是应用名。

    2、对应用下的models.py文件进行编辑(后台数据库字段设计)

    from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Douban(models.Model): title = models.CharField(max_length=30) content = models.TextField() created_time = models.DateTimeField(default=timezone.now) last_updated_time = models.DateTimeField(auto_now=True) author = models.ForeignKey(User,on_delete=models.DO_NOTHING,default=1) is_deleted = models.BooleanField(default=False) def __str__(self): return "<Douban:%s>" % self.title

    3、对应用下的views.py文件进行编辑(网页内容)

    from django.shortcuts import render_to_response,get_object_or_404 from .models import Douban # Create your views here. def douban_detail(request,douban_id): douban = get_object_or_404(Douban,pk=douban_id) context = {} context['douban_obj'] = douban return render_to_response("douban_detail.html",context) def douban_list(request): doubans = Douban.objects.filter(is_deleted=False) context = {} context['doubans'] = doubans return render_to_response("douban_list.html",context)

    4、在应用下新建文件夹templates,在文件夹下建立douban_detail.html、douban_list.html两个文件,分别为(分离网页代码)

    <html> <head> </head> <body> <h2>{{ douban_obj.title }}</h2> <hr></hr> <p>{{ douban_obj.content }}</p> </body> </html> <html> <head> </head> <body> {% for douban in doubans %} <a href="{%url 'douban_detail' douban.pk%}">{{douban.title}}</a> {% endfor%} </body> </html>

    5、对应用下的admin.py文件进行编辑(网页后台)

    from django.contrib import admin from .models import Douban # Register your models here. @admin.register(Douban) class DoubanAdmin(admin.ModelAdmin): list_display = ("id","title","content","is_deleted","author","created_time","last_updated_time") orering = ("id")

    6、在应用下新建urls.py文件进行编辑(链接内容)

    from django.urls import path from.import views urlpatterns = [ path('',views.douban_list,name="douban_list"), path('<int:douban_id>',views.douban_detail,name="douban_detail"), ]

    项目配置

    1、对项目下的urls.py文件进行编辑(链接管理)

    from django.contrib import admin from django.urls import path,include from.import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.index), path('douban/',include('douban.urls')) ]

    2、对项目下的settings.py文件进行编辑(配置)

    INSTALLED_APPS = [ '...', 'douban', ] LANGUAGE_CODE = 'zh-Hans' TIME_ZONE = 'Asia/Shanghai'

    运行

    回到项目路径下的cmd: 1、初始化(生成)数据库文件,python manage.py makemigrations 2、迁移 , python manage.py migrate 3、运行,python manage.py runserver

    Processed: 0.011, SQL: 8