项目创建
1. 虚拟环境
python -m venv my_env
cd my_env
activate/deactivate
pip install django
2. 项目和app创建
cd mypros
django-admin startproject Pro1
django-admin startapp app1
3. settings配置INSTALLED_APPS【app1"】TEMPLATES【 'DIRS': [os.path.join(BASE_DIR,"templates")]】LANGUAGE_CODE = 'zh-hans'TIME_ZONE = 'Asia/Shanghai'
MVT Demo
urls --> app.views --> templates/test.html
### urls.py
from app1.views import test1
urlpatterns = [...,path("/test1",test1)
]
### app1.views.py
def test1(request):return render(request,"app1/test1.html",context={"msg":"hello world"})
### templates/test1.html
# TEMPLATES【 'DIRS': [os.path.join(BASE_DIR,"templates")]】
# "app1/test1.html"
new >> Pro1/templates
new >> Pro1/templates/app1/test1.html
{{ msg }}
ORM
### install mysql dependency
pip install mysqlclient 【recommend】
pip install pymysql【app/__init__.py:import pymysqlpymysql.install_as_MySQLdb()
】
### settings.py
DATABASES = {'default': {'ENGINE': 'django.db.backends.mysql',"NAME":"test1","HOST":"localhost""PORT":3306,"USER":"root","PASSWORD":"root",}
}
### mysql
mysql -uroot -proot
show databases;
create database test1;
### orm
class Users(models.Model):# id 自动生成name = models.CharField(max_length=255,verbose_name="用户名")age = models.IntegerField(verbose_name="用户年龄")class Account(models.Model):KIND_CHOICE = ((1,"普通用户"),(2,"VIP用户"),)# id 自动生成balance = models.DecimalField(max_digits=10,decimal_places=2,verbose_name="账户余额")kind = models.IntegerField(choices=KIND_CHOICE,verbose_name="账户类型")user = models.ForeignKey(to="app1.Users",verbose_name="账户用户名",on_delete=models.CASCADE)
### migrate
python manage.py makemigrations
python manage.py migrate
Admin Manger
### simple register model(admin.py)
from django.contrib import admin
from .models import Users,Account
admin.site.register(Users)
admin.site.register(Account)
### create super user: admin manage-user(Terminal)
python manage.py createsuperuser### admin page show:verbose_name(models.py)
class Users(models.Model):class Meta:verbose_name = verbose_name_plural = "用户"passclass Account(models.Model):class Meta:verbose_name = verbose_name_plural = "用户账户"pass
### admin page show: list_display(admin.py)
# @admin.register(Users)
class UsersAdmin(admin.ModelAdmin):list_display = ("id","name","age")
@admin.register(Account)
class AccountAdmin(admin.ModelAdmin):list_display = ("id","user","balance","kind")# admin.site.register(Users)
# admin.site.register(Account)
admin.site.register(Users,UsersAdmin)
### admin page show: app verbose name(apps.py)
class App1Config(AppConfig):verbose_name = "我的应用1"pass
### admin page show:model object str name
class Users(models.Model):def __str__(self):return "%s"%(self.name)pass
class Account(models.Model):def __str__(self):return "%s账户"%(self.user.name)pass
### admin page show:records ordering(admin.py)
class UsersAdmin(admin.ModelAdmin):ordering = ["id"] # ordering = ["-id"]pass
### admin page show:fieldsets of add form(admin.py)
class AccountAdmin(admin.ModelAdmin):fieldsets = (("账户信息", {"description":"请输入用户信息","fields":("kind","balance")}),("所有者",{"description": "请输入用户所有者","fields":("user",)}))
### admin page show:search fields(admin.py)
search_fields = ["name"]
### admin page show:Tabular inline Edit(admin.py)
class AccountInline(admin.TabularInline):extra = 1model = Account
class UsersAdmin(admin.ModelAdmin):inlines = [AccountInline,]
### admin page show:custom css style (admin.py)
# settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
# admin.py
class UsersAdmin(admin.ModelAdmin):class Media:css = {"all": ("/static/css/admin/admin_user.css",),}pass
Template
{{ msg }}
{{ user.name }}
{% csrf_token %}
{% for user in users %}{% if user.age > 18 %}<p>adult</p>{% else %}<p>minor</p>{% endif %}
{% end for %}
{% for key,value in dict.items %}<p>{{ key }}:{{ value }}</p>
{% endfor %}
{{ data | default:"<p style='color:red'>还没有任何数据哦</p>" }}
{{ content | slice:":20" }}
{{ getDate | date:"Y/m/d" }}{% extends "base.html" %}{% block main %}
{% endblock %}
URL
### re_path:query_param、named-group
from django.urls import path,re_path
urlpatterns = [path("index",test,name="index"),re_path(r"^app1/(?P<page>[1-9]+)$",test1),
]
def test(request):# localhost:8000/index?name=joden&age=20print(request.GET.dict)print(request.GET.get("name"))def test1(request,page):# re_path page group => param: page print("page:",page)print(request.GET.dict())
### url name
re_path(r'app1/(?P<page>[1-9]+)$', test1, name="index"),
def test(request):print(reverse("index",kwargs={"page":2}))
### url namespace
from django.urls import include
path("app1",include("app1.urls"))
# app1/urls.py
app_name = "app1"
re_path(r'page/(?P<page>[1-9]+)$', test1, name="index"),
# views.py
reverse("app1:index",kwargs={"page":2})
CBV
CBV:Class Basic View
https://docs.djangoproject.com/zh-hans/4.1/ref/class-based-views/### View
from django.view import View
class TestView(View):def get(self,request,*args,**kwargs):return render(request,"app1/test1.html")def post(self,request,*args,**kwargs):passurlpatterns = [path("app",TestView.as_view()),
]### TemplateView
from django.views.generic.base import TemplateView
class TestTemplateView(TemplateView):tempate_name = "app1/test1.html"def get_context_data(self,**kwargs):super().get_context_data(self,**kwargs)context = {"users":Users.objects.all(),}return context
### ListView
from django.views.generic.list import ListView
class TestListView(ListView):template_name = "app1/test1.html"model = Userpaginate_by = 2 # 3 user/per pagedef get_context_data(self,**kwargs):context = super().get_context_data(self,**kwargs)print(self.get_paginator(self.object_list,self.paginate_by).num_pages)return context{% for user in object_list %}
{% endfor %}
Cookie and Session
### cookie
class TestListView(ListView):def get(self,request,*args,**kwargs):# get cookie(request)request.get_cookie("name")response = super(TestListView, self).get(*args,**kwargs)# set cookie(response)response.set_cookie("name","joden")return response
### session
class TestListView(ListView):def get(self,request,*args,**kwargs):# get sessionget_session_name = request.session.get("sname","")# set sessionrequest.session["sname"] = "value"return super(TestListView, self).get(*args,**kwargs)