30岁初学者基础设施工程师 Django 超入门

第一天

pip install Django==3.0.4 
//バージョン指定はしなくてもいい

创建项目

django-admin startproject django_app
//django_appとゆうプロジェクト作成

服务器启动

cd django_app
python manage.py runserver
//ブラウザでhttp://localhost:8000
djang.png

第二天

python manage.py startapp hello
//helloとゆうフォルダが作成される

编辑 view.py 文件

from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello Django!!")

创建和编辑hello/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'), #indexとゆう名前を付与
]

编辑项目根目录下的urls.py文件。

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

urlpatterns = [
    path('admin/', admin.site.urls),
        path('hello/', include('hello.urls')), #helloアプリのurlsを全て読み込み
]
#http://localhost:8000/helloをブラウザで確認
djang.png

编辑hello/urls.py和hello/view.py文件来使用URL的查询参数。

from django.urls import path
from . import views

urlpatterns = [
    path('<int:id>/<nickname>/', views.index, name='index'),
    #基本文字列なのでintを指定
]
from django.shortcuts import render
from django.http import HttpResponse

def index(request, id, nickname):
    result = 'your id: ' + str(id) + ', name: "' \ #見かけの改行 次の行も同じになる
        + nickname + '". '
    return HttpResponse(result)
#http://localhost:8000/hello/id/nicknameをブラウザで確認
djang.png

第三天

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'hello', #これを足す
]

创建文件夹,创建 index.html 文件,修改 urls.py,修正 views.py 中的 index 函数。

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>hello</title>
</head>
<body>
    <h1>hello/index</h1>
    <p>This is sample page.</p>
</body>
</html>
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]
from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    return render(request, 'hello/index.html')

传递值给模板

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
</head>
<body>
    <h1>{{title}}</h1>
    <p>{{msg}}</p>
</body>
</html>
from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    params = {
        'title':'Hello/Index',
        'msg':'これは、サンプルぺーじです'
    }
    return render(request, 'hello/index.html', params)

翻増多页移动

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
</head>
<body>
    <h1>{{title}}</h1>
    <p>{{msg}}</p>
    <p><a href="{% url goto %}">{{goto}}</a></p>
</body>
</html>
from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    params = {
        'title':'Hello/Index',
        'msg':'これは、サンプルぺーじです',
        'goto':'next',
    }
    return render(request, 'hello/index.html', params)

def next(request):
    params = {
        'title':'Hello/Next',
        'msg':'これは、もう一つのぺーじです',
        'goto':'index',
    }
    return render(request, 'hello/index.html', params)
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('next', views.next, name='next'),
]

使用CSS,管理静态文件,创建static文件夹,以及使用bootstrap。

body{
    color:gray;
    font-size:16pt;
}

h1{
    color:red;
    opacity: 0.2;
    font-size: 60pt;
    margin-top: -20px;
    margin-bottom: 0px;
    text-align: right;
}

p{
    margin: 10px;
}

a{
    color: blue;
    text-decoration: none;
}
{% load static %}
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <link rel="stylesheet" type="text/css"
        href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossorigin="anonymous">
</head>
<body class="container">
    <h1 class="display-4 text-primary mb-4">{{title}}</h1>
    <p class="h5">{{msg}}</p>
    <p class="h6"><a href="{% url goto %}">{{goto}}</a></p>
</body>
</html>
djang.png

第四天

from django import forms

class HelloForm(forms.Form):
    name = forms.CharField(label='name',widget=forms.TextInput(attrs={'class':'form-control'}))
    mail = forms.CharField(label='mail',widget=forms.TextInput(attrs={'class':'form-control'}))
    age = forms.IntegerField(label='age',widget=forms.NumberInput(attrs={'class':'form-control'}))
#widgetでbootstrapのcssを引数で渡して、htmlでの編集をなくしている
from django.shortcuts import render
from django.http import HttpResponse
from .forms import HelloForm

def index(request):
    params = {
        'title':'Hello',
        'msg':'your data:',
        'form':HelloForm()
    }
    if(request.method == 'POST'):
        params['message'] = '名前:' + request.POST['name'] + \
            '<br>メール:' + request.POST['mail'] + \
            '<br>年齢:' + request.POST['age']
        params['form'] = HelloForm(request.POST)
    return render(request, 'hello/index.html', params)
#indexの中でGETの表示とPOSTの表示を分けている
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]
#indexだけで処理しているため
{% load static %}
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossorigin="anonymous">

</head>
<body class="container">
    <h1 class="display-4 text-primary">{{title}}</h1>
    <p class="h5 mt-4">{{message|safe}}</p>
    <form action="{% url 'index' %}" method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" class="btn btn-primary my-2" value="click">
    </form>
</body>
</html>
djang.png

第五天

from django.db import models

class Friend(models.Model):
    name = models.CharField(max_length=100)
    mail = models.EmailField(max_length=200)
    gender = models.BooleanField()
    age = models.IntegerField(default=0)
    birthday = models.DateField()

    def __str__(self):
        return '<Friend:id=' + str(self.id) + ', ' + self.name + '(' + str(self.age) +')>'

创建迁移文件 (Migrate file creation)

python manage.py makemigrations hello

执行迁移文件

python manage.py migrate

创建管理工具

python manage.py createsuperuser

在admin.py中添加Friend模型

from django.contrib import admin
from .models import Friend

admin.site.register(Friend)
#http://localhost:8000/adminにアクセス

模型的对象是通过manager类创建的,使用QuerySet从数据库中提取和编辑数据。

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]
from django.shortcuts import render
from django.http import HttpResponse
from .models import Friend
from django.db.models import QuerySet

def __new_str__(self):
    result = ''
    for item in self:
        result += '<tr>'
        for k in item:
            result += '<td>' + str(k) + '=' + str(item[k]) + '</td>'
        result += '</tr>'
    return result

QuerySet.__str__ = __new_str__

def index(request):
    data=Friend.objects.all().values('id','name','age')
    params = {
        'title':'Hello',
        'data':data,
    }
    return render(request, 'hello/index.html', params)
{% load static %}
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossorigin="anonymous">

</head>
<body class="container">
    <h1 class="display-4 text-primary">{{title}}</h1>
    <table class="table">
        {{data|safe}}
    </table>
</body>
</html>
djang.png

第六天

在urls.py中添加跳转目标

from django.urls import path
from . import views
from .views import FriendList
from .views import FriendDetail


urlpatterns = [
    path('', views.index, name='index'),
    path('create', views.create, name='create'),
    path('edit/<int:num>', views.edit, name='edit'),
    path('delete/<int:num>', views.delete, name='delete'),
    path('list', FriendList.as_view()), #☆
    path('detail/<int:pk>', FriendDetail.as_view()), #☆
]

在forms.py中添加一个类。

from django import forms
from.models import Friend

class HelloForm(forms.Form):
    name = forms.CharField(label='Name', \
        widget=forms.TextInput(attrs={'class':'form-control'}))
    mail = forms.EmailField(label='Email', \
        widget=forms.EmailInput(attrs={'class':'form-control'}))
    gender = forms.BooleanField(label='Gender', required=False, \
        widget=forms.CheckboxInput(attrs={'class':'form-check'}))
    age = forms.IntegerField(label='Age', \
        widget=forms.NumberInput(attrs={'class':'form-control'}))
    birthday = forms.DateField(label='Birth', \
        widget=forms.DateInput(attrs={'class':'form-control'}))

class FriendForm(forms.ModelForm):
    class Meta:
        model = Friend
        fields = ['name','mail','gender','age','birthday']

创建一个create函数

from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from .models import Friend
#from .forms import HelloForm
from .forms import FriendForm


def index(request):
    data = Friend.objects.all()
    params = {
        'title': 'Hello',
        'data': data,
    }
    return render(request, 'hello/index.html', params)

# create model
def create(request):
    if (request.method == 'POST'):
        obj = Friend()
        friend = FriendForm(request.POST, instance=obj)
        friend.save()
        return redirect(to='/hello')
    params = {
        'title': 'Hello',
        'form': FriendForm(),
    }
    return render(request, 'hello/create.html', params)

创建一个create.html页面

{% load static %}
<!doctype html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <link rel="stylesheet" 
    href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
    crossorigin="anonymous">
</head>
<body class="container">
    <h1 class="display-4 text-primary">
        {{title}}</h1>
    <form action="{% url 'create' %}" 
        method="post">
    {% csrf_token %}
        <table class="table">
        {{ form.as_table }}
            <tr><th><td>
                <input type="submit" value="click"
                    class="btn btn-primary mt-2">
            </td></th></tr>
        </table>
    </form>
</body>
</html>
#http://localhost:8000/hello/createにアクセス
djang.png

创建edit函数

from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from .models import Friend
#from .forms import HelloForm
from .forms import FriendForm


def index(request):
    data = Friend.objects.all()
    params = {
        'title': 'Hello',
        'data': data,
    }
    return render(request, 'hello/index.html', params)

# create model
def create(request):
    if (request.method == 'POST'):
        obj = Friend()
        friend = FriendForm(request.POST, instance=obj)
        friend.save()
        return redirect(to='/hello')
    params = {
        'title': 'Hello',
        'form': FriendForm(),
    }
    return render(request, 'hello/create.html', params)

def edit(request, num):
    obj = Friend.objects.get(id=num)
    if (request.method == 'POST'):
        friend = FriendForm(request.POST, instance=obj)
        friend.save()
        return redirect(to='/hello')
    params = {
        'title': 'Hello',
        'id':num,
        'form': FriendForm(instance=obj),
    }
    return render(request, 'hello/edit.html', params)

修改index.html

{% load static %}
<!doctype html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <link rel="stylesheet" 
    href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
    crossorigin="anonymous">
</head>
<body class="container">
    <h1 class="display-4 text-primary">
        {{title}}</h1>
    <table class="table">
        <tr>
            <th>data</th>
        </tr>
    {% for item in data %}
        <tr>
            <td>{{item}}</td>
            <td><a href="{% url 'edit' item.id %}">Edit</a></td>
        <tr>
    {% endfor %}
    </table>
</body>
</html>

创建edit.html

{% load static %}
<!doctype html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <link rel="stylesheet" 
    href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
    crossorigin="anonymous">
</head>
<body class="container">
    <h1 class="display-4 text-primary">
        {{title}}</h1>
    <form action="{% url 'edit' id %}" 
        method="post">
    {% csrf_token %}
        <table class="table">
        {{ form.as_table }}
            <tr><th><td>
                <input type="submit" value="click"
                    class="btn btn-primary mt-2">
            </td></th></tr>
        </table>
    </form>
</body>
</html>
#http://localhost:8000/hello/からeditをクリック
djang.png

创建一个delete函数

from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from .models import Friend
#from .forms import HelloForm
from .forms import FriendForm


def index(request):
    data = Friend.objects.all()
    params = {
        'title': 'Hello',
        'data': data,
    }
    return render(request, 'hello/index.html', params)

# create model
def create(request):
    if (request.method == 'POST'):
        obj = Friend()
        friend = FriendForm(request.POST, instance=obj)
        friend.save()
        return redirect(to='/hello')
    params = {
        'title': 'Hello',
        'form': FriendForm(),
    }
    return render(request, 'hello/create.html', params)

def edit(request, num):
    obj = Friend.objects.get(id=num)
    if (request.method == 'POST'):
        friend = FriendForm(request.POST, instance=obj)
        friend.save()
        return redirect(to='/hello')
    params = {
        'title': 'Hello',
        'id':num,
        'form': FriendForm(instance=obj),
    }
    return render(request, 'hello/edit.html', params)

def delete(request, num):
    friend = Friend.objects.get(id=num)
    if (request.method == 'POST'):
        friend.delete()
        return redirect(to='/hello')
    params = {
        'title': 'Hello',
        'id':num,
        'obj': friend,
    }
    return render(request, 'hello/delete.html', params)

修改 index.html。

{% load static %}
<!doctype html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <link rel="stylesheet" 
    href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
    crossorigin="anonymous">
</head>
<body class="container">
    <h1 class="display-4 text-primary">
        {{title}}</h1>
    <table class="table">
        <tr>
            <th>data</th>
        </tr>
    {% for item in data %}
        <tr>
            <td>{{item}}</td>
            <td><a href="{% url 'edit' item.id %}">Edit</a></td>
            <td><a href="{% url 'delete' item.id %}">Delete</a></td>
        <tr>
    {% endfor %}
    </table>
</body>
</html>

创建一个edit.html

{% load static %}
<!doctype html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <link rel="stylesheet" 
    href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
    crossorigin="anonymous">
</head>
<body class="container">
    <h1 class="display-4 text-primary">
        {{title}}</h1>
    <p>※以下のレコードを削除します。</p>
    <table class="table">
        <tr><th>ID</th><td>{{obj.id}}</td></tr>
        <tr><th>Name</th><td>{{obj.name}}</td></tr>
        <tr><th>Gender</th><td>
        {% if obj.gender == False %}male{% endif %}
        {% if obj.gender == True %}female{% endif %}</td></tr>
        <tr><th>Email</th><td>{{obj.mail}}</td></tr>
        <tr><th>Age</th><td>{{obj.age}}</td></tr>
        <tr><th>Birth</th><td>{{obj.birthday}}</td></tr>
        <form action="{% url 'delete' id %}" method="post">
        {% csrf_token %}
        <tr><th></th><td>
            <input type="submit" value="click"
                class="btn btn-primary">
        </td></tr>
        </form>
    </table>
</body>
</html>
#http://localhost:8000/hello/からdeleteをクリック
djang.png

在views.py中添加import和类以创建通用视图。

from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from .models import Friend
#from .forms import HelloForm
from .forms import FriendForm
from django.views.generic import ListView
from django.views.generic import DetailView

class FriendList(ListView):
    model = Friend

class FriendDetail(DetailView):
    model = Friend


def index(request):
    data = Friend.objects.all()
    params = {
        'title': 'Hello',
        'data': data,
    }
    return render(request, 'hello/index.html', params)

# create model
def create(request):
    if (request.method == 'POST'):
        obj = Friend()
        friend = FriendForm(request.POST, instance=obj)
        friend.save()
        return redirect(to='/hello')
    params = {
        'title': 'Hello',
        'form': FriendForm(),
    }
    return render(request, 'hello/create.html', params)

def edit(request, num):
    obj = Friend.objects.get(id=num)
    if (request.method == 'POST'):
        friend = FriendForm(request.POST, instance=obj)
        friend.save()
        return redirect(to='/hello')
    params = {
        'title': 'Hello',
        'id':num,
        'form': FriendForm(instance=obj),
    }
    return render(request, 'hello/edit.html', params)

def delete(request, num):
    friend = Friend.objects.get(id=num)
    if (request.method == 'POST'):
        friend.delete()
        return redirect(to='/hello')
    params = {
        'title': 'Hello',
        'id':num,
        'obj': friend,
    }
    return render(request, 'hello/delete.html', params)

创建friend_list.html

{% load static %}
<!doctype html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <link rel="stylesheet" 
    href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
    crossorigin="anonymous">
</head>
<body class="container">
    <h1 class="display-4 text-primary">
        Friends List</h1>
    <table class="table">
        <tr>
            <th>id</th>
            <th>name</th>
            <th></th>
        </tr>
    {% for item in object_list %}
        <tr>
            <th>{{item.id}}</th>
            <td>{{item.name}}</td>
            <td><a href="/hello/detail/{{item.id}}">detail</a></td>
        <tr>
    {% endfor %}
    </table>
</body>

</html>
#http://localhost:8000/hello/listにアクセス
djang1.png

创建friend_detail.html

{% load static %}
<!doctype html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <link rel="stylesheet" 
    href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
    crossorigin="anonymous">
</head>
<body class="container">
    <h1 class="display-4 text-primary">
        Friends List</h1>
    <table class="table">
        <tr>
            <th>id</th>
            <th>{{object.id}}</th>
        </tr>
        <tr>
            <th>name</th>
            <td>{{object.name}}</td>
        </tr>
        <tr>
            <th>mail</th>
            <td>{{object.mail}}</td>
        </tr>
        <tr>
            <th>gender</th>
            <td>{{object.gender}}</td>
        </tr>
        <tr>
            <th>age</th>
            <td>{{object.age}}</td>
        </tr>
    </table>
</body>
</html>
#http://localhost:8000/hello/listのdetailをクリック
djang2.png

第七天

在urls.py文件中添加跳转目标

from django.urls import path
from . import views
from .views import FriendList
from .views import FriendDetail


urlpatterns = [
    path('', views.index, name='index'),
    path('create', views.create, name='create'),
    path('edit/<int:num>', views.edit, name='edit'),
    path('delete/<int:num>', views.delete, name='delete'),
    path('list', FriendList.as_view()), #☆
    path('detail/<int:pk>', FriendDetail.as_view()), #☆
    path('find', views.find, name='find'), #☆
]

创建find.html

{% load static %}
<!doctype html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <link rel="stylesheet" 
    href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
    crossorigin="anonymous">
</head>
<body class="container">
    <h1 class="display-4 text-primary">
        {{title}}</h1>
    <p>{{message|safe}}</p>
    <form action="{% url 'find' %}" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <tr><th></th><td>
        <input type="submit" value="click"
            class="btn btn-primary mt-2"></td></tr>
    </form>
    <hr>
    <table class="table">
        <tr>
            <th>id</th>
            <th>name</th>
            <th>mail</th>
        </tr>
    {% for item in data %}
        <tr>
            <th>{{item.id}}</th>
            <td>{{item.name}}({{item.age}})</td>
            <td>{{item.mail}}</td>
        <tr>
    {% endfor %}
    </table>
</body>
</html>

创建一个find函数,通过姓名和地址进行搜索。

from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from .models import Friend
#from .forms import HelloForm
from .forms import FriendForm
from django.views.generic import ListView
from django.views.generic import DetailView
from .forms import FindForm #この文を追記
from django.db.models import Q

class FriendList(ListView):
    model = Friend

class FriendDetail(DetailView):
    model = Friend


def index(request):
    data = Friend.objects.all()
    params = {
        'title': 'Hello',
        'data': data,
    }
    return render(request, 'hello/index.html', params)

# create model
def create(request):
    if (request.method == 'POST'):
        obj = Friend()
        friend = FriendForm(request.POST, instance=obj)
        friend.save()
        return redirect(to='/hello')
    params = {
        'title': 'Hello',
        'form': FriendForm(),
    }
    return render(request, 'hello/create.html', params)

def edit(request, num):
    obj = Friend.objects.get(id=num)
    if (request.method == 'POST'):
        friend = FriendForm(request.POST, instance=obj)
        friend.save()
        return redirect(to='/hello')
    params = {
        'title': 'Hello',
        'id':num,
        'form': FriendForm(instance=obj),
    }
    return render(request, 'hello/edit.html', params)

def delete(request, num):
    friend = Friend.objects.get(id=num)
    if (request.method == 'POST'):
        friend.delete()
        return redirect(to='/hello')
    params = {
        'title': 'Hello',
        'id':num,
        'obj': friend,
    }
    return render(request, 'hello/delete.html', params)

def find(request):
    if (request.method == 'POST'):
        msg = 'search result:'
        form = FindForm(request.POST)
        find = request.POST['find']
        data = Friend.objects.filter(Q(name__contains=find)|Q(mail__contains=find))
    else:
        msg = 'search words...'
        form = FindForm()
        data =Friend.objects.all()
    params = {
        'title': 'Hello',
        'message': msg,
        'form':form,
        'data':data,
    }
    return render(request, 'hello/find.html', params)
#http://localhost:8000/hello/findにアクセス
djang3.png
广告
将在 10 秒后关闭
bannerAds