feat(projects): 新增Django综合案例示例代码及素材

This commit is contained in:
100gle
2022-08-10 16:15:39 +08:00
parent b4c2257308
commit 3bf65b2755
65 changed files with 1496 additions and 0 deletions

View File

@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'quickstart.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

View File

@@ -0,0 +1,6 @@
from django.apps import AppConfig
class MyappConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'myapp'

View File

@@ -0,0 +1,3 @@
from django.db import models
# Create your models here.

View File

@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

View File

@@ -0,0 +1,61 @@
from django.http import HttpResponse
def poem(request):
content = """
<style>
figure {
display: block;
margin: auto;
width: 40%;
}
figure > figcaption {
text-align: center;
}
blockquote {
margin: 0;
}
blockquote p {
padding: 15px;
line-height: 1cm;
background: #eee;
border-radius: 5px;
}
</style>
<figure>
<blockquote>
<i>
<p>
Beautiful is better than ugly.<br />
Explicit is better than implicit.<br />
Simple is better than complex.<br />
Complex is better than complicated.<br />
Flat is better than nested.<br />
Sparse is better than dense.<br />
Readability counts.<br />
Special cases aren't special enough to break the rules.<br />
Although practicality beats purity.<br />
Errors should never pass silently.<br />
Unless explicitly silenced.<br />
In the face of ambiguity, refuse the temptation to guess.<br />
There should be one-- and preferably only one --obvious way to do
it.<br />
Although that way may not be obvious at first unless you're
Dutch.<br />
Now is better than never.<br />
Although never is often better than *right* now.<br />
If the implementation is hard to explain, it's a bad idea.<br />
If the implementation is easy to explain, it may be a good idea.<br />
Namespaces are one honking great idea -- let's do more of those!<br />
</p>
</i>
</blockquote>
<figcaption>
——Tim Peters, <cite><b>The Zen of Python</b></cite>
</figcaption>
</figure>
"""
return HttpResponse(content)

View File

@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

View File

@@ -0,0 +1,6 @@
from django.apps import AppConfig
class OrmConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'orm'

View File

@@ -0,0 +1,26 @@
# Generated by Django 4.0.4 on 2022-06-25 05:27
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(primary_key=True, serialize=False, verbose_name='用户ID')),
('name', models.CharField(max_length=10, verbose_name='用户名')),
('age', models.IntegerField(verbose_name='年龄')),
('gender', models.BooleanField(blank=True, choices=[(0, ''), (1, '')], default='', verbose_name='性别')),
('email', models.EmailField(max_length=50, verbose_name='邮箱')),
('telephone', models.CharField(blank=True, max_length=11, verbose_name='联系电话')),
('register_at', models.DateTimeField(auto_now_add=True, verbose_name='注册时间')),
],
),
]

View File

@@ -0,0 +1,35 @@
from django.db import models
class User(models.Model):
gender_choices = [
(0, ""),
(1, ""),
]
id = models.AutoField(
primary_key=True,
verbose_name="用户ID",
)
name = models.CharField(
max_length=10,
verbose_name="用户名",
)
age = models.IntegerField(verbose_name="年龄")
gender = models.BooleanField(
choices=gender_choices,
blank=True,
default="",
verbose_name="性别",
)
email = models.EmailField(max_length=50, verbose_name="邮箱")
telephone = models.CharField(
max_length=11,
blank=True,
verbose_name="联系电话",
)
register_at = models.DateTimeField(auto_now_add=True, verbose_name="注册时间")
def __repr__(self):
return f"User<id:{self.id}, name:{self.name}>"

View File

@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

View File

@@ -0,0 +1,7 @@
from django.urls import path
from .views import index
urlpatterns = [
path("", index, name="orm.index"),
]

View File

@@ -0,0 +1,5 @@
from django.http import HttpResponse
def index(request):
return HttpResponse("ORM page here.")

View File

@@ -0,0 +1,16 @@
"""
ASGI config for quickstart project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'quickstart.settings')
application = get_asgi_application()

View File

@@ -0,0 +1,125 @@
"""
Django settings for quickstart project.
Generated by 'django-admin startproject' using Django 4.0.4.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-)8usuw-fz#s1wq7u2_$u!g&=llu!%j5gl5)$a(avyh5h20_ssq"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
# internal apps
"orm",
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "quickstart.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [BASE_DIR.joinpath("templates")],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "quickstart.wsgi.application"
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = "zh-Hans"
TIME_ZONE = "Asia/Shanghai"
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = "static/"
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

View File

@@ -0,0 +1,26 @@
"""quickstart URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path
from myapp import views
urlpatterns = [
path("admin/", admin.site.urls),
path("poem/", views.poem, name="poem"),
path("view/", include("view.urls")),
path("tmpl/", include("tmpl.urls")),
path("orm/", include("orm.urls")),
]

View File

@@ -0,0 +1,16 @@
"""
WSGI config for quickstart project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'quickstart.settings')
application = get_wsgi_application()

View File

@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>The Zen of Python</title>
<style>
figure {
display: block;
margin: auto;
width: 40%;
}
figure > figcaption {
text-align: center;
}
blockquote {
margin: 0;
}
blockquote p {
padding: 15px;
line-height: 1cm;
background: #eee;
border-radius: 5px;
}
</style>
</head>
<body>
{% csrf_token %}
<figure>
<blockquote>
<p>
{% for line in lines %} <i>{{ line }}</i><br />
{% endfor %}
</p>
</blockquote>
<figcaption>
——{{ author }}, <cite><b>{{ source }}</b></cite>
</figcaption>
</figure>
</body>
</html>

View File

@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

View File

@@ -0,0 +1,6 @@
from django.apps import AppConfig
class TmplConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'tmpl'

View File

@@ -0,0 +1,3 @@
from django.db import models
# Create your models here.

View File

@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

View File

@@ -0,0 +1,7 @@
from django.urls import path
from .views import index
urlpatterns = [
path("", index, name="tmpl_index"),
]

View File

@@ -0,0 +1,36 @@
from django.shortcuts import render
def index(request):
poem = """\
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"""
lines = poem.strip().split("\n")
author = "Tim Peters"
source = "The Zen of Python"
context = dict(
lines=lines,
author=author,
source=source,
)
return render(request, "poem.html", context=context)

View File

@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

View File

@@ -0,0 +1,6 @@
from django.apps import AppConfig
class ViewConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'view'

View File

@@ -0,0 +1,3 @@
from django.db import models
# Create your models here.

View File

@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

View File

@@ -0,0 +1,8 @@
from django.urls import path
from .views import IndexView, index
urlpatterns = [
path("", index),
path("class/", IndexView.as_view()),
]

View File

@@ -0,0 +1,59 @@
from django.http import HttpResponse, HttpResponseNotAllowed
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def index(request):
"""index page"""
method = request.method
if method == "GET":
return HttpResponseNotAllowed(["POST"])
elif method == "POST":
return HttpResponse(f"You has got this page by POST method.")
@method_decorator(csrf_exempt, name="dispatch")
class IndexView(View):
template = """\
<p>You has got this page by {method} method, the following steps are: <br />
{content}
</p>
"""
def get(self, request):
"""index page"""
steps = [
"1. handle GET request",
"2. log request and other info",
"3. query something from database",
]
response = self.template.format(
method="GET",
content=r"<br />".join(steps),
)
return HttpResponse(response)
def post(self, request):
steps = [
"1. handle POST request",
"2. log request and other info",
"3. get form or parameters from request",
"4. parse form or parameters",
"5. query something from database",
"6. return response",
]
response = self.template.format(
method="POST",
content=r"<br />".join(steps),
)
return HttpResponse(response)