一、创建项目目录
1.1 预备环境
需要有python, django, 而且版本要匹配。
1.2、创建项目总文件夹
django-admin startproject <project_name>
1.3 创建app目录
进入到项目录,然后执行命令
python manage.py startapp <app_name>
二、创建项目文件
2.1 编写models模型代码
这里我们定义两个字段:name和age
from django.db import models
class showInfo(models.Model):
name = models.CharField(max_length=20)
addr = models.CharField(max_length=40)
def __str__(self):
return self.name
2.2 编写views视图代码
from django.views import generic
from .models import showInfo
class IndexView(generic.ListView):
template_name = ‘learn/index.html‘
context_object_name = ‘showw‘
def get_queryset(self):
return showInfo.objects.filter()
2.3 编写urls.py路由配置
from django.urls import path
from . import views
app_name = ‘learn‘
urlpatterns = [
path(‘‘, views.IndexView.as_view(), name=‘index‘),
]
2.5 编写admin.py将应用注册到管理台
from django.contrib import admin
from .models import showInfo
admin.site.register(showInfo)
2.6 编写learn/templates/learn/index.html视图模版
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static ‘learn/index.css‘ %}">
<h1>这里是learn.index</h1>
{% if showw %}
<ul>
{% for item in showw %}
<li>{{ item.name }}</li>
{% endfor %}
</ul>
{% else %}
<p>没有结果</p>
{% endif %}
2.7 编写learn/static/learn/index.css样式表文件
h1 {
color: greenyellow;
}
h1:hover {
color: red;
}
2.8 在mysite的INSTALLED_APPS中将应用注册
INSTALLED_APPS = [
‘learn.apps.LearnConfig‘,
‘django.contrib.admin‘,
‘django.contrib.auth‘,
‘django.contrib.contenttypes‘,
‘django.contrib.sessions‘,
‘django.contrib.messages‘,
‘django.contrib.staticfiles‘,
]
2.9 编写mysite/urls.py主路由配置
urlpatterns = [
path(‘learn/‘, include(‘learn.urls‘)),
path(‘admin/‘, admin.site.urls),
]