Django 教程:武士日本选手名单

这是地区图书馆网站的 Django 教程第一部分的应用篇。

让我们显示一下日本足球代表队的球员名单。
我们将显示如下画面。

member01.png
member02.png
member03.png
member04.png
member05.png

1) 创建项目和应用

django-admin startproject member_shozoku
cd member_shozoku
python manage.py startapp namelist

2)应用程序的注册


import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


SECRET_KEY = 'p=df)0_ow)(j@h+)g5s!ceqnht$qtcr2+9$t1k*#5w5fgz8kn1'

DEBUG = True

ALLOWED_HOSTS = []

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'namelist.apps.NamelistConfig',
]

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 = 'member_syozoku.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR,'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 = 'member_syozoku.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

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',
    },
]

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_URL = '/static/'

3) 设置 URL


from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
]

from django.urls import include
from django.urls import path

urlpatterns += [
    path('namelist/', include('namelist.urls')),
]

from django.views.generic import RedirectView
urlpatterns += [
    path('', RedirectView.as_view(url='/namelist/', permanent=True)),
]

# Use static() to add url mapping to serve static files during development (only)
from django.conf import settings
from django.conf.urls.static import static

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('members/', views.MemberListView.as_view(), name='members'),
    path('member/<int:pk>', views.MemberDetailView.as_view(), name='member-detail'),
    path('syozokus/', views.SyozokuListView.as_view(), name='syozokus'),
    path('syozoku/<int:pk>', views.SyozokuDetailView.as_view(), name='syozoku-detail'),
]

#
urlpatterns += [  
    path('member/create/', views.MemberCreate.as_view(), name='member_create'),
    path('member/<int:pk>/update/', views.MemberUpdate.as_view(), name='member_update'),
    path('member/<int:pk>/delete/', views.MemberDelete.as_view(), name='member_delete'),
]
#

创建名单/views.py文件

from django.shortcuts import render

# Create your views here.

from namelist.models import Member, Syozoku

def index(request):
    """View function for home page of site."""

    # Generate counts of some of the main objects
    num_members = Member.objects.all().count()
#    num_instances = MemberInstance.objects.all().count()


    # The 'all()' is implied by default.    
    num_syozokus = Syozoku.objects.count()

    context = {
        'num_members': num_members,
#        'num_instances': num_instances,
        'num_syozokus': num_syozokus,
    }

    # Render the HTML template index.html with the data in the context variable
    return render(request, 'namelist/index.html', context=context)

from django.views import generic

class MemberListView(generic.ListView):
    model = Member

class MemberDetailView(generic.DetailView):
    model = Member

class SyozokuListView(generic.ListView):
    model = Syozoku

class SyozokuDetailView(generic.DetailView):
    model = Syozoku

from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from namelist.models import Member

class MemberCreate(CreateView):
    model = Member
    fields = '__all__'

class MemberUpdate(UpdateView):
    model = Member
    fields = '__all__'

class MemberDelete(DeleteView):
    model = Member
    success_url = reverse_lazy('members')

5) 创建 namelist/models.py

from django.db import models
from django.urls import reverse

class Member(models.Model):
    name = models.CharField(max_length=30)
    year_of_birth = models.IntegerField(null=True)

    syozoku = models.ForeignKey('Syozoku', on_delete=models.SET_NULL, null=True)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('member-detail', args=[str(self.id)])

class Syozoku(models.Model):
    name = models.CharField(max_length=30)
    home = models.CharField(max_length=30)

    class Meta:
        ordering = ['name']

    def get_absolute_url(self):
        return reverse('syozoku-detail', args=[str(self.id)])

    def __str__(self):
        return f'{self.name}'

6) 移民

python manage.py makemigrations
python manage.py migrate

7) 制作模板

mkdir namelist/templates
mkdir namelist/templates/namelist
<!DOCTYPE html>
<html lang="ja">
<head>
  {% block title %}<title>メンバー 所属</title>{% endblock %}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
  {% load static %}
</head>
<body>
{% block sidebar %}
    <ul class="sidebar-nav">
    <li><a href="{% url 'index' %}">ホーム</a></li>
    <li><a href="{% url 'members' %}">全メンバー</a></li>
    <li><a href="{% url 'syozokus' %}">全所属</a></li>
    </ul>
{% endblock %}
{% block content %}
{% endblock %}
    2019年3月23日<p />
</body>
</html>
{% extends "namelist/base_generic.html" %}

{% block content %}
  <h1>メンバー 所属</h1>
  <ul>
    <li><strong>メンバー:</strong> {{ num_members }}</li>
    <li><strong>所属:</strong> {{ num_syozokus }}</li>
  </ul>
{% endblock %}
{% extends "namelist/base_generic.html" %}

{% block content %}
  <h1>メンバー リスト</h1>
  {% if member_list %}
  <ol>
    {% for member in member_list %}
      <li>
        <a href="{{ member.get_absolute_url }}">{{ member.name }}</a>
        (<a href="{% url 'syozoku-detail' member.syozoku.pk %}">{{ member.syozoku }}</a>)
      </li>
    {% endfor %}
  </ol>
  {% else %}
    <p>There are no members registered.</p>
  {% endif %}

<a href="/namelist/member/create/">新規</a><p />
{% endblock %}
{% extends "namelist/base_generic.html" %}

{% block content %}
  <h1>所属 リスト</h1>
  {% if syozoku_list %}
  <ol>
    {% for syozoku in syozoku_list %}
      <li>
        <a href="{{ syozoku.get_absolute_url }}">{{ syozoku.name }}</a>
      </li>
    {% endfor %}
  </ol>
  {% else %}
    <p>There are no syozokus registered.</p>
  {% endif %}       
{% endblock %}
{% extends "namelist/base_generic.html" %}

{% block content %}
  <h1>名前: {{ member.name }}</h1>
    生年 {{member.year_of_birth}} <p />
  <p><strong>所属:</strong> <a href="{% url 'syozoku-detail' member.syozoku.pk %}">{{ member.syozoku }}</a></p>

  <div style="margin-left:20px;margin-top:20px">

a href= {{member.pk}}/update>更新</a><p />
<a href= {{member.pk}}/delete>削除</a><p />
<a href= "/namelist/members">一覧</a><p />


{% endblock %}
{% extends "namelist/base_generic.html" %}

{% block content %}
  <h1>名前: {{ syozoku.name }}</h1>
  ホーム: {{ syozoku.home }}<p />

{% endblock %}

创建超级用户以便插入数据。

python manage.py createsuperuser

9) 编辑 namelist/admin.py

from django.contrib import admin

# Register your models here.

from namelist.models import Member, Syozoku

admin.site.register(Member)
admin.site.register(Syozoku)

10) 启动开发服务器,访问 http://127.0.0.1:8000/admin,并输入数据。

11) 登出管理员账号,访问http://127.0.0.1:8000。

广告
将在 10 秒后关闭
bannerAds