【问题标题】:django-dynamic-formset creating two add/remove links per formsetdjango-dynamic-formset 为每个表单集创建两个添加/删除链接
【发布时间】:2012-09-07 00:39:38
【问题描述】:

由于某种原因,我的 django-dynamic-formset 实现有点滑稽。

它正在为我的模板中的每个动态表单集创建两个添加/删除链接。

我一直在摆弄试图弄清楚这一点,它得到了我最好的。

here 是我所说的错误的屏幕截图

如果您想自己触发错误,我也可以提供登录信息 这是我的模板:

<head>
    <script type="text/javascript" src="{{ STATIC_URL }}jquery.formset.js"></script>
    <script type="text/javascript">
       $(function() {
           $('#ingredients tbody tr').formset({
               prefix: '{{ ingredients_formset.prefix }}',
               formCssClass: 'dynamic-ingredients'
           });
            $('#steps tbody tr').formset({
               prefix: '{{ steps_formset.prefix }}',
               formCssClass: 'dynamic-steps'
           });
       })
   </script>
</head>
<body>
<form action="{% url cookbook.views.createrecipe %}" method="POST" id="ingredients">
    {% csrf_token %}
<table>
    <tbody>
        <tr>
            <label>
                Ingredients:
            </label>
        </tr>

        <tr>
            <td>
                <input type="text" cols="40" rows="10" />
            </td>
        </tr>
    </tbody>
</table>
</form>
<form action="{% url cookbook.views.createrecipe %}" method="POST" id="steps">
    {% csrf_token %}
<table>
    <tbody>
        <label>
            Steps:
        </label>
        <tr>
            <td>
                <input type="text"  cols="40" rows="10" />
            </td>
        </tr>
    </tbody>
</table>
</form>
</body>

这是forms.py

class RecipeForm(forms.ModelForm):
    reset_recipe = forms.CharField(widget=forms.HiddenInput(), required = False)
    class Meta:
        model = Recipe
        widgets = {'original_cookbook':forms.HiddenInput(),
                    'pub_date':forms.HiddenInput(),
                    'author':forms.HiddenInput()}

        fields =("name", "picture","ingredients","steps","prep_time","type",'reset_recipe')

class CookbookForm(forms.ModelForm):
    class Meta:
        model = Cookbook


class StepsForm(forms.Form):
    Step = forms.CharField()

StepsFormSet = formset_factory(RecipeForm, StepsForm, can_order=True, can_delete=True, extra = 0)

class IngredientsForm(forms.Form):
    Ingredient = forms.CharField()

IngredientsFormSet = formset_factory(RecipeForm, IngredientsForm, can_order=True, can_delete=True, extra = 0)

和视图:

def createrecipe(request):
    RecipeForm = RecipeForm(request.POST)
    IngredientsFormSet = formset_factory(IngredientsForm)
    StepsFormSet = formset_factory(StepsForm)
    if request.method == 'POST':
        form = RecipeForm(request.POST)
        ingredients_formset = IngredientsFormSet(request.POST, request.FILES, prefix='ifs')
        steps_formset = StepsFormSet(request.POST, request.FILES, prefix='sfs')
        if form.is_valid() and ingredients_formset.is_valid() and steps_formset.is_valid():
            print "form is valid"
            new_recipe = form.save(commit=False)
            new_recipe.original_cookbook = request.user.cookbooks.all()[0]
            new_recipe.author = request.user.cookbooks.all()[0].name
            new_recipe.steps = steps_formset
            new_recipe.ingredients = ingredients_formset
            new_recipe.save()
            cookbooks = request.user.cookbooks.all()
            cookbook = cookbooks[0]
            cookbook.recipes.add(new_recipe)
            form.save_m2m()             
            t = loader.get_template('cookbook/create_form.html')
            c = RequestContext(request, {
            'form': new_recipe,
            })

            data = {
            'replace': True,
            'form': t.render(c),
            'success': True,
            }

            json = simplejson.dumps(data)
            return HttpResponse(json, mimetype='text/plain')
        else:
            print "form is invalid"
            form = RecipeForm(request.POST)
            ingredients_formset = IngredientsFormSet(request.POST, request.FILES, prefix='ifs')
            steps_formset = StepsFormSet(request.POST, request.FILES, prefix='sfs')
            t = loader.get_template('cookbook/create_form.html')
            c = RequestContext(request, {
                'form':form,
            })

            data ={
                'form': t.render(c),
                'success': False,
            }

            json = simplejson.dumps(data)
            return HttpResponse(json, mimetype='text/plain')    

【问题讨论】:

    标签: jquery django dynamic dynamic-forms formset


    【解决方案1】:

    您可以使用ELO80KA 提供的惊人的django-dynamic-formset jQuery 插件

    我现在正在一个项目中使用它,让我告诉你我现在是怎么做的,让我们看看标记:

    <div id="id_p_i_c_formset_div">
    {% for form in p_i_c_formset.forms %}
        <div class="p_i_c_child_formset row-fluid">
            {{ form.id }}
            <h2>year</h2>
            {{ form.year }}
            <h2>product_category</h2>
            {{ form.product_category }}
            <h2>insurance_company</h2>
            {{ form.insurance_company }}
            <h2>value</h2>
            {{ form.value|attr:"placeholder:insurance_claims" }}
            <h2>result</h2>
            {{ form.result }}
        </div>
    {% endfor %}
    {{ p_i_c_formset.management_form }}
    </div>
    

    然后,在 javascript 中,您需要执行正确的选择器(表单集的字段所在的位置),这是插件将获取代码以使用正确的 id 和名称克隆它的地方,不要忘记粘贴它是表单集的“前缀”:

    $(function(){
        $('form#my-personal-info #id_p_i_c_formset_div .p_i_c_child_formset').formset({
            prefix: '{{ p_i_c_formset.prefix }}'
        });
    });
    

    插件会自动创建删除和添加按钮。

    【讨论】:

      猜你喜欢
      • 2017-06-13
      • 2018-10-19
      • 2014-03-24
      • 1970-01-01
      • 2021-10-10
      • 2014-05-31
      • 1970-01-01
      • 2015-10-29
      • 1970-01-01
      相关资源
      最近更新 更多