美文网首页运维工程师的进阶之路
2019-06-13 django2.2 一般项目步骤(初步)

2019-06-13 django2.2 一般项目步骤(初步)

作者: Gswu | 来源:发表于2019-06-13 20:33 被阅读0次

    Django一般步骤记录

    新建app

    python manage.py startapp myapp
    

    新增app路由

    myapp下新建urls.py

    from django.urls import path,include
    from . import views
    
    app_name='blog'
    
    urlpatterns = [
        path('', views.index,name='blogindex'),
    ]
    

    项目下的urls.py

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

    数据库模型

    myapp下的models.py

    from django.db import models
    
    # Create your models here.
    
    class Blog(models.Model):
        name=models.CharField(max_length=100)
        tagline=models.TextField()
    
        def __str__(self):
            return self.name
    
    class Author(models.Model):
        name=models.CharField(max_length=200)
        email=models.EmailField()
    
        def __str__(self):
            return self.name
    
    class Entry(models.Model):
        blog=models.ForeignKey(Blog,on_delete=models.CASCADE)
        headline=models.CharField(max_length=200)
        body_text=models.TextField()
        pub_date=models.DateField()
        mod_date=models.DateField()
        author=models.ManyToManyField(Author)
        n_comments=models.IntegerField()
        n_pingbacks=models.IntegerField()
        rating=models.IntegerField()
    
        def __str__(self):
            return self.headline
    
    

    项目下的settings.py ,将myapp加入Installedapp中

    数据库迁移:

    python manage.py makemigrations
    python manage.py migrate
    

    后台管理

    myapp下的admin.py 中将models中的数据库表注册

    from django.contrib import admin
    from .models import Blog,Author,Entry
    # Register your models here.
    
    
    admin.site.register(Blog)
    admin.site.register(Author)
    admin.site.register(Entry)
    
    

    新建管理员用户

    python manage.py cteatesuperuser
    
    

    开启服务器,使用pycharm的启动按钮或python manage.py runserver

    此时,访问 http://127.0.0.1:8000/blog/http://127.0.0.1:8000/admin/即可验证

    相关文章

      网友评论

        本文标题:2019-06-13 django2.2 一般项目步骤(初步)

        本文链接:https://www.haomeiwen.com/subject/ilpefctx.html