django的form实践

form可以完成的功能

  • 数据校验
  • 渲染

1,定义models

from django.db import models
from django.utils.html import format_html
# Create your models here.
class Publisher(models.Model):
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=50)
    city = models.CharField(max_length=60)
    state_province = models.CharField(max_length=30)
    country = models.CharField(max_length=50)
    website = models.URLField()
    p_lever = (
        ('top', u'顶级出版社'),
        ('one', u'一级出版社'),
        ('two', u'二级出版社'),
    )
    lever = models.CharField(choices=p_lever, max_length=32, default='one')
    def __str__(self):
      return self.name
    class Meta:
        verbose_name_plural = '出版社'

    def lever_color(self):
        format_td = ''
        if self.lever == 'top':
            format_td = format_html('<span style="padding:2px;background-color:yellowgreen;color:white">顶级出版社</span>')
        if self.lever == 'one':
            format_td = format_html('<span style="padding:2px;background-color:pink;color:white">一级出版社</span>')
        if self.lever == 'two':
            format_td = format_html('<span style="padding:2px;background-color:orange;color:white">二级出版社</span>')
        return format_td
    lever_color.short_description = 'lever'


class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()
    def __str__(self):
      return self.first_name

    class Meta:
        verbose_name_plural = '作者'

class Book(models.Model):
    name = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)    #关联Author表,在后台添加book时,会有author和publisher的选项。
    publisher = models.ForeignKey(Publisher,on_delete=models.CASCADE)
    publication_date = models.DateField()
    def __str__(self):
      return self.name

    class Meta:
        verbose_name_plural = '书籍'

2,从数据库拿数据填充到选框中

from django.shortcuts import render,HttpResponse
from django import forms
from mysite import models
from django.core.validators import RegexValidator
import re
from django.core.exceptions import ValidationError
# Create your views here.
class BookForm(forms.Form):

    name = forms.CharField(
        label="书名",
        max_length=100,
    )
    # 从数据库拿数据填充到多选框中
    authors = forms.ModelMultipleChoiceField(
        queryset=models.Author.objects.all(),
        widget=forms.widgets.CheckboxSelectMultiple(),
        label="作者")
    # 从数据库拿数据填充到单选框中
    publisher = forms.ModelChoiceField(
        models.Publisher.objects.all(),
        empty_label="------",
        label="出版社")
    publication_date = forms.DateField(label="出版日期",widget=forms.TextInput(attrs={'type': 'date'}))


def bookhandles(request):
    form_obj = BookForm()
    booklist = models.Book.objects.all()
    pub = models.Publisher.objects
    # print(booklist)
    if request.method == "POST":
        form_obj = BookForm(request.POST)  # 对提交的数据进行组件类实例化
        if form_obj.is_valid():  # 校验提交的数据对象(字段校验-->validators校验(RegexValidator模块或者自定义函数)-->局部钩子-->全局钩子)
            cdata = form_obj.cleaned_data
            print(cdata)
            print(cdata['authors'])
            # author_obj = models.Author.objects.filter(first_name='avichal').select_related()# 这个是queryset对象,love_list = Love.objects.filter(b__name='xx').values('g__nick')  # love_list里面全是字典
            author_obj = models.Author.objects.filter(first_name= cdata['authors'].first()).select_related()
            print(author_obj)
            cdata['publisher']=pub.filter(name = cdata['publisher'])[0] #处理外键插入
            book_obj = models.Book.objects.create(name = cdata['name'],publisher = cdata['publisher'],publication_date=cdata['publication_date'])
            book_obj.authors.set(author_obj)#处理多对多插入
        else:
            pass
            # print(form_obj)return render(request, 'book.html', {'form_obj': form_obj, "booklist":booklist})

前端页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>showbook</title>
</head>
<body>


<form action="" method="post">{% csrf_token%}
  {{ form_obj }}
    <input type="submit" value="提交">
</form>

<table>
    <thead>
    <tr>
        <th>
            书名
        </th>
        <th>
            出版社
        </th>
        <th>
            出版日期
        </th>
    </tr>
    </thead>
    <tbody>
    {% for book in booklist %}
    <tr>
        <td>{{ book.name }}</td>
        <td>{{ book.publisher }}</td>
        <td>{{ book.publication_date }}</td>
    </tr>
    {% endfor %}

    </tbody>
</table>

</body>
</html>
View Code

admin

from django.contrib import admin
from mysite import models
# Register your models here.
def make_top(modelAdmin,request,queryset):      #queryset是选中的对象的集合
    queryset.update(lever='top')
    make_top.short_description='顶级出版社'
def make_one(modelAdmin,request,queryset):
    queryset.update(lever='one')
    make_one.short_description='一级出版社'
def make_two(modelAdmin,request,queryset):
    queryset.update(lever='two')
    make_two.short_description='二级出版社'

class BookAdmin(admin.ModelAdmin):
    list_display = ('name','publisher','publication_date')
    search_fields = ('name','publisher__name')
    list_editable = ('publisher','publication_date')
    fields = ['name',('publisher','publication_date')]
class PublisherAdmin(admin.ModelAdmin):
    list_display = ('name','address','city','state_province','website','lever_color')
    actions = [make_top, make_one, make_two]

admin.site.register(models.Author)
admin.site.register(models.Publisher,PublisherAdmin)
admin.site.register(models.Book, BookAdmin)

效果

猜你喜欢

转载自www.cnblogs.com/anyShanbhag/p/13401433.html
今日推荐