码迷,mamicode.com
首页 > 其他好文 > 详细

第77篇 formset的使用示例

时间:2018-11-25 20:42:49      阅读:303      评论:0      收藏:0      [点我收藏+]

标签:har   gem   mod   rom   queryset   modelform   .sh   cti   max   

1. views

from django.shortcuts import render
from django.forms import modelformset_factory
from app01.forms import Publisher
from app01.forms import PunlisherForm
# Create your views here.


def publisher(request):
    data = Publisher.objects.all()
    Formset = modelformset_factory(Publisher,PunlisherForm,extra=0)
    formset_obj = Formset(queryset=data)
    if request.method == ‘POST‘:
        # form_obj = Form(request.POST,instance=edit_obj)
        formset_obj = Formset(request.POST,queryset=data)
        if formset_obj.is_valid():
            formset_obj.save()
    return render(request,‘publisher.html‘,{‘formset_obj‘:formset_obj})

  2. html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>出版社列表</title>
</head>
<body>
<h1>出版社列表</h1>
<form action="" method="post">
{% csrf_token %}  防止跨站请求伪造
{{ formset_obj.management_form }}  告诉后端总共有哪些form 哪些发生了变化
    <table border="1">
        <thead>
        <tr>
            <th>#</th>
            <th>名称</th>
            <th>地址</th>
        </tr>
        </thead>
        <tbody>
        {% for form_obj in formset_obj %}
            <tr>
                <td>{{ forloop.counter }}</td>
                {{ form_obj.id }}
                <td> {{ form_obj.name }}</td>
                <td> {{ form_obj.addr }}</td>
            </tr>
        {% endfor %}
        </tbody>
    </table>
    <input type="submit" name="" id="">
</form>
</body>
</html>

  3. models

from django.db import models
# 出版社列表
class Publisher(models.Model):
    name = models.CharField(max_length=32)
    addr = models.CharField(max_length=128)

  4. forms

from django import forms
from app01.models import Publisher

class PunlisherForm(forms.ModelForm):

    class Meta:
        model = Publisher
        fields = ‘__all__‘

  

第77篇 formset的使用示例

标签:har   gem   mod   rom   queryset   modelform   .sh   cti   max   

原文地址:https://www.cnblogs.com/cavalier-chen/p/10016202.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!