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
 

二、form组件

三、modelform

猜你喜欢

转载自www.cnblogs.com/alice-bj/p/9183509.html