• Django(复习篇)


    项目创建
    1. 1. 虚拟环境
    2. python -m venv my_env
    3. cd my_env
    4. activate/deactivate
    5. pip install django
    6. 2. 项目和app创建
    7. cd mypros
    8. django-admin startproject Pro1
    9. django-admin startapp app1
    10. 3. settings配置
    11. INSTALLED_APPS【app1"】
    12. TEMPLATES【 'DIRS': [os.path.join(BASE_DIR,"templates")]】
    13. LANGUAGE_CODE = 'zh-hans'
    14. TIME_ZONE = 'Asia/Shanghai'
    MVT Demo
    1. urls --> app.views --> templates/test.html
    2. ### urls.py
    3. from app1.views import test1
    4. urlpatterns = [
    5. ...,
    6. path("/test1",test1)
    7. ]
    8. ### app1.views.py
    9. def test1(request):
    10.    return render(request,"app1/test1.html",context={"msg":"hello world"})
    11. ### templates/test1.html
    12. # TEMPLATES【 'DIRS': [os.path.join(BASE_DIR,"templates")]】
    13. # "app1/test1.html"
    14. new >> Pro1/templates
    15. new >> Pro1/templates/app1/test1.html
    16. {{ msg }}

    ORM
    1. ### install mysql dependency
    2. pip install mysqlclient 【recommend】
    3. pip install pymysql【
    4. app/__init__.py:
    5.    import pymysql
    6.    pymysql.install_as_MySQLdb()
    7. ### settings.py
    8. DATABASES = {
    9.    'default': {
    10.        'ENGINE': 'django.db.backends.mysql',
    11.        "NAME":"test1",
    12.        "HOST":"localhost"
    13.        "PORT":3306,
    14.        "USER":"root",
    15.        "PASSWORD":"root",
    16.   }
    17. }
    18. ### mysql
    19. mysql -uroot -proot
    20. show databases;
    21. create database test1;
    22. ### orm
    23. class Users(models.Model):
    24.    # id 自动生成
    25.    name = models.CharField(max_length=255,verbose_name="用户名")
    26.    age = models.IntegerField(verbose_name="用户年龄")
    27. class Account(models.Model):
    28.    KIND_CHOICE = (
    29.       (1,"普通用户"),
    30.       (2,"VIP用户"),
    31.   )
    32.    # id 自动生成
    33.    balance = models.DecimalField(max_digits=10,decimal_places=2,verbose_name="账户余额")
    34.    kind = models.IntegerField(choices=KIND_CHOICE,verbose_name="账户类型")
    35.    user = models.ForeignKey(to="app1.Users",verbose_name="账户用户名",on_delete=models.CASCADE)
    36. ### migrate
    37. python manage.py makemigrations
    38. python manage.py migrate

    Admin Manger
    1. ### simple register model(admin.py)
    2. from django.contrib import admin
    3. from .models import Users,Account
    4. admin.site.register(Users)
    5. admin.site.register(Account)
    6. ### create super user: admin manage-user(Terminal)
    7. python manage.py createsuperuser
    8. ### admin page show:verbose_name(models.py)
    9. class Users(models.Model):
    10.    class Meta:
    11.        verbose_name = verbose_name_plural = "用户"
    12.    pass
    13.    
    14. class Account(models.Model):
    15.    class Meta:
    16.        verbose_name = verbose_name_plural = "用户账户"
    17.    pass
     
    
    1. ### admin page show: list_display(admin.py)
    2. # @admin.register(Users)
    3. class UsersAdmin(admin.ModelAdmin):
    4.    list_display = ("id","name","age")
    5. @admin.register(Account)
    6. class AccountAdmin(admin.ModelAdmin):
    7.    list_display = ("id","user","balance","kind")
    8.    
    9. # admin.site.register(Users)
    10. # admin.site.register(Account)
    11. admin.site.register(Users,UsersAdmin)

    1. ### admin page show: app verbose name(apps.py)
    2. class App1Config(AppConfig):
    3. verbose_name = "我的应用1"
    4. pass

     

    1. ### admin page show:model object str name
    2. class Users(models.Model):
    3.    def __str__(self):
    4.        return "%s"%(self.name)
    5.    pass
    6. class Account(models.Model):
    7.    def __str__(self):
    8.        return "%s账户"%(self.user.name)
    9.    pass

    1. ### admin page show:records ordering(admin.py)
    2. class UsersAdmin(admin.ModelAdmin):
    3.    ordering = ["id"] # ordering = ["-id"]
    4.    pass

    1. ### admin page show:fieldsets of add form(admin.py)
    2. class AccountAdmin(admin.ModelAdmin):
    3.    fieldsets = (
    4.       ("账户信息", {
    5.            "description":"请输入用户信息",
    6.            "fields":("kind","balance")
    7.       }),
    8.       ("所有者",{
    9.            "description": "请输入用户所有者",
    10.            "fields":("user",)
    11.       })
    12.   )

     

    1. ### admin page show:search fields(admin.py)
    2. search_fields = ["name"]
     
    
    1. ### admin page show:Tabular inline Edit(admin.py)
    2. class AccountInline(admin.TabularInline):
    3.    extra = 1
    4.    model = Account
    5. class UsersAdmin(admin.ModelAdmin):
    6.    inlines = [AccountInline,]
     
    
    1. ### admin page show:custom css style (admin.py)
    2. # settings.py
    3. STATIC_URL = '/static/'
    4. STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
    5. # admin.py
    6. class UsersAdmin(admin.ModelAdmin):
    7.    class Media:
    8.        css = {
    9.            "all": ("/static/css/admin/admin_user.css",),
    10.       }
    11.    pass

    Template
    1. {{ msg }}
    2. {{ user.name }}
    3. {% csrf_token %}
    4. {% for user in users %}
    5.    {% if user.age > 18 %}
    6.        

      adult

    7.    {% else %}
    8.        

      minor

    9.    {% endif %}
    10. {% end for %}
    11. {% for key,value in dict.items %}
    12. {{ key }}:{{ value }}

    13. {% endfor %}
    14. {{ data | default:"

      还没有任何数据哦

      "
      }}
    15. {{ content | slice:":20" }}
    16. {{ getDate | date:"Y/m/d" }}
    17. {% extends "base.html" %}
    18. {% block main %}
    19. {% endblock %}
    URL
    1. ### re_path:query_param、named-group
    2. from django.urls import path,re_path
    3. urlpatterns = [
    4.    path("index",test,name="index"),
    5. re_path(r"^app1/(?P[1-9]+)$",test1),
    6. ]
    7. def test(request):
    8.    # localhost:8000/index?name=joden&age=20
    9.    print(request.GET.dict)
    10.    print(request.GET.get("name"))
    11.    
    12. def test1(request,page):
    13.    # re_path page group => param: page  
    14.    print("page:",page)
    15.    print(request.GET.dict())
    16.    
    17. ### url name
    18. re_path(r'app1/(?P[1-9]+)$', test1, name="index"),
    19. def test(request):
    20.    print(reverse("index",kwargs={"page":2}))
    21.    
    22. ### url namespace
    23. from django.urls import include
    24. path("app1",include("app1.urls"))
    25. # app1/urls.py
    26. app_name = "app1"
    27. re_path(r'page/(?P[1-9]+)$', test1, name="index"),
    28. # views.py
    29. reverse("app1:index",kwargs={"page":2})
    CBV
    1. CBV:Class Basic View
    2. https://docs.djangoproject.com/zh-hans/4.1/ref/class-based-views/
    3.    
    4. ### View
    5. from django.view import View
    6. class TestView(View):
    7.    def get(self,request,*args,**kwargs):
    8.        return render(request,"app1/test1.html")
    9.    def post(self,request,*args,**kwargs):
    10.        pass
    11.    
    12. urlpatterns = [
    13. path("app",TestView.as_view()),
    14. ]
    15.    
    16.    
    17. ### TemplateView
    18. from django.views.generic.base import TemplateView
    19. class TestTemplateView(TemplateView):
    20.    tempate_name = "app1/test1.html"
    21.    def get_context_data(self,**kwargs):
    22.        super().get_context_data(self,**kwargs)
    23.        context = {
    24.            "users":Users.objects.all(),
    25.       }
    26.        return context
    27. ### ListView
    28. from django.views.generic.list import ListView
    29. class TestListView(ListView):
    30.    template_name = "app1/test1.html"
    31.    model = User
    32.    paginate_by = 2 # 3 user/per page
    33.    def get_context_data(self,**kwargs):
    34.        context = super().get_context_data(self,**kwargs)
    35.        print(self.get_paginator(self.object_list,self.paginate_by).num_pages)
    36.        return context
    37.    
    38. {% for user in object_list %}
    39. {% endfor %}

    Cookie and Session
    1. ### cookie
    2. class TestListView(ListView):
    3. def get(self,request,*args,**kwargs):
    4.        # get cookie(request)
    5.        request.get_cookie("name")
    6.        response = super(TestListView, self).get(*args,**kwargs)
    7.        # set cookie(response)
    8.        response.set_cookie("name","joden")
    9.        return response
    10.    
    11.    
    12. ### session
    13. class TestListView(ListView):
    14. def get(self,request,*args,**kwargs):
    15.        # get session
    16.        get_session_name = request.session.get("sname","")
    17.        # set session
    18.        request.session["sname"] = "value"
    19.        return super(TestListView, self).get(*args,**kwargs)

  • 相关阅读:
    Shell test 命令
    【第二章 数据的表示和运算】d1
    计算机毕业设计ssm校园生活互助平台06qe4系统+程序+源码+lw+远程部署
    优雅的实现符合开闭原则的流水日志抽取demo
    gRpc入门
    洛谷 P1349 广义斐波那契数列(矩阵快速幂, 水题)
    D. Cow and Fields(最短路+思维)
    图的最小生成树算法(图解+代码)| 学不会来看我系列
    MySQL Oracle区别
    解释CSS伪类和伪元素的区别,并举例说明。
  • 原文地址:https://blog.csdn.net/m0_60633107/article/details/134366208