Django - ModelForm

Posted alice-bj

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django - ModelForm相关的知识,希望对你有一定的参考价值。

一、原生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的主要内容,如果未能解决你的问题,请参考以下文章

Django之ModelForm

Django modelForm 中的文件上传

更改在Django中使用ModelForm创建的表单元素的宽度

[django]modelform实现的多文件上传

Django使用普通表单Form以及modelForm操作数据库方式总结

Django 2.0 ModelForm dateField 不显示为小部件