1. 程式人生 > >Django - ModelForm

Django - ModelForm

.post submit ews del rfi button tom bsp make

一、原生form

https://www.cnblogs.com/yuanchenqi/articles/7614921.html

案例:

技術分享圖片

步驟:

1.models.py ...
makemigrations
migrate
技術分享圖片
from django.db import models

# Create your models here.

class Book(models.Model):
    title = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=8,decimal_places=2)  #
999999.99 date = models.DateField() publish = models.ForeignKey("Publish",on_delete=models.CASCADE) authors = models.ManyToManyField("Author") def __str__(self): return self.title class Publish(models.Model): name = models.CharField(max_length=32) def __str__
(self): return self.name class Author(models.Model): name = models.CharField(max_length=32) def __str__(self): return self.name
models.py

2.admin.py
技術分享圖片
from django.contrib import admin

# Register your models here.

from .models import *

admin.site.register(Book)
admin.site.register(Publish)
admin.site.register(Author)
admin.py

3.createsuperuser
yuan yuan1234

4.註意點:

1.addbook:(getlist)
...
publish_id = request.POST.get(‘publish_id‘)
auhtor_pk_list = request.POST.getlist(‘auhtor_pk_list‘) # [‘1‘, ‘2‘]
book_obj = Book.objects.create(title=title,price=price,date=date,publish_id=publish_id)
book_obj.authors.add(*auhtor_pk_list)

2.editbook:(set)
...
<p>價格 <input type="text" name="price" value="{{ edit_book.price }}"></p>
{% if author in edit_book.authors.all %}
<option selected value="{{ author.pk }}">{{ author.name }}</option>
{% else %}
<option value="{{ author.pk }}">{{ author.name }}</option>
{% endif %}

...
ret = Book.objects.filter(pk=edit_book_id).update(title=title, price=price, date=date, publish_id=publish_id)
print(‘ret---‘, ret) # 1

book_obj = Book.objects.filter(pk=edit_book_id).first()
print(‘book_obj---‘, book_obj) # 對象

book_obj.authors.set(auhtor_pk_list)

5.code
技術分享圖片
from django.contrib import admin
from django.urls import path,re_path

from app01 import views

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

    path(books/, views.books),
    path(book/add/, views.addbook),
    re_path(book/edit/(\d+), views.editbook),

]
urls.py 技術分享圖片
from django.shortcuts import render,HttpResponse,redirect

# Create your views here.

from .models import *

def books(request):
    book_list = Book.objects.all()

    return render(request,books.html,locals())

def addbook(request):
    if request.method == POST:
        title = request.POST.get(title)
        price = request.POST.get(price)
        date = request.POST.get(date)
        publish_id = request.POST.get(publish_id)
        auhtor_pk_list = request.POST.getlist(auhtor_pk_list)  # [‘1‘, ‘2‘]

        print(auhtor_pk_list)

        book_obj = Book.objects.create(title=title,price=price,date=date,publish_id=publish_id)
        book_obj.authors.add(*auhtor_pk_list)

        return redirect(/books/)

    publish_list = Publish.objects.all()
    author_list= Author.objects.all()

    return render(request,add.html,locals())


def editbook(request, edit_book_id):
    if request.method == POST:
        title = request.POST.get(title)
        price = request.POST.get(price)
        date = request.POST.get(date)
        publish_id = request.POST.get(publish_id)
        auhtor_pk_list = request.POST.getlist(auhtor_pk_list)  # [‘1‘, ‘2‘]

        print(auhtor_pk_list)

        ret = Book.objects.filter(pk=edit_book_id).update(title=title, price=price, date=date, publish_id=publish_id)
        print(ret---, ret)  # 1

        book_obj = Book.objects.filter(pk=edit_book_id).first()
        print(book_obj---, book_obj)  # 對象

        book_obj.authors.set(auhtor_pk_list)

        return redirect(/books/)

    edit_book = Book.objects.filter(pk=edit_book_id).first()
    publish_list = Publish.objects.all()
    author_list = Author.objects.all()

    return render(request, edit.html, locals())
views.py 技術分享圖片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>books</title>
</head>
<body>

<a href="/book/add/"><button>添加書籍</button></a>
<hr>

<table border="1">
    {% for book in book_list %}
        <tr>
            <td>{{ book.title }}</td>
            <td>{{ book.price }}</td>
            <td>{{ book.date|date:‘Y-m-d‘ }}</td>
            <td>{{ book.publish.name}}</td>
            <td>
                {% for author in book.authors.all %}
                {{ author.name }}
                {% endfor %}

            </td>
            <td><a href="/book/edit/{{ book.pk }}">編輯</a></td>


        </tr>
    {% endfor %}

</table>


</body>
</html>
books.html 技術分享圖片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h3>添加頁面</h3>

<form action="" method="post">
    {% csrf_token %}
    <p>書籍名稱 <input type="text" name="title"></p>
    <p>價格 <input type="text" name="price"></p>
    <p>日期 <input type="date" name="date"></p>
    <p>出版社
        <select name="publish_id" id="">
            {% for publish in publish_list %}
                <option value="{{ publish.pk }}">{{ publish.name }}</option>
            {% endfor %}
        </select>
    </p>
    <p>作者
        <select name="auhtor_pk_list" id="" multiple>
            {% for author in author_list %}
                <option value="{{ author.pk }}">{{ author.name }}</option>
            {% endfor %}
        </select>
    </p>
    <input type="submit">
</form>

</body>
</html>
add.html 技術分享圖片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h3>編輯頁面</h3>

<form action="" method="post">
    {% csrf_token %}
    <p>書籍名稱 <input type="text" name="title" value="{{ edit_book.title}}"></p>
    <p>價格 <input type="text" name="price" value="{{ edit_book.price }}"></p>
    <p>日期 <input type="date" name="date" value="{{ edit_book.date|date:‘Y-m-d‘ }}"></p>
    <p>出版社
        <select name="publish_id" id="">
            {% for publish in publish_list %}

                {% if edit_book.publish == publish %}
                    <option selected value="{{ publish.pk }}">{{ publish.name }}</option>
                {% else %}
                    <option value="{{ publish.pk }}">{{ publish.name }}</option>
                {% endif %}

            {% endfor %}
        </select>
    </p>
    <p>作者
        <select name="auhtor_pk_list" id="" multiple>
            {% for author in author_list %}

                {% if author in edit_book.authors.all %}
                    <option selected value="{{ author.pk }}">{{ author.name }}</option>
                {% else %}
                    <option value="{{ author.pk }}">{{ author.name }}</option>
                {% endif %}

            {% endfor %}
        </select>
    </p>
    <input type="submit">
</form>

</body>
</html>
edit.html

二、form組件

三、modelform

Django - ModelForm