子inline_formset Django

时间:2019-07-12 00:42:35

标签: javascript python html django

我正在创建一个网站,以输入不同产品地点(餐厅,超市,药店)的不同产品的价格

用户可以输入多个产品位置一个产品位置可以具有多个产品一个产品位置(例如餐馆)可以具有多个菜单

所以我有三种模型:1.第一种是“ ProductPlace”,它具有网站用户模型(“ User”)作为foreignKey

第二个是具有“ ProductPlace”模型作为外键的“ P​​roduct” 第三是“菜单”(如餐厅菜单),它也具有“ ProductPlace”模型作为外键 我在“ forms.py”文件中创建了与这三个模型关联的表单集。

#forms.py

from django import forms
from .models import *
from django.forms.models import inlineformset_factory, modelformset_factory
from django.contrib.auth import get_user_model

User = get_user_model()

class ProductPlaceForm(forms.ModelForm):
    name = forms.CharField(label='Nom', 
                            widget=forms.TextInput(attrs={
                            'class': 'form-control',
                            'placeholder': 'Nom du point de vente'
                            }))
    num_road = forms.IntegerField(label='Numero',
                                    widget=forms.NumberInput(
                                    attrs={'class': 'form-control',
                                    'placeholder': 'Numero de la rue'}))
    name_road = forms.CharField(label='Nom de la rue', 
                                widget=forms.TextInput(attrs={
                                'class': 'form-control',
                                'placeholder': 'Nom de la Rue'
                                }))
    postal_code = forms.IntegerField(label='Code Postal',
                                    widget=forms.NumberInput(
                                    attrs={'class': 'form-control',
                                    'placeholder': 'Code Postal'}))
    city =  forms.CharField(label='Ville', 
                             widget=forms.TextInput(attrs={
                                'class': 'form-control',
                                'placeholder': 'Ville'
                                }))
    country =  forms.CharField(label='Pays', 
                                widget=forms.TextInput(attrs={
                                'class': 'form-control',
                                'placeholder': 'Pays'
                                }))

    class Meta:
        model = ProductPlace
        fields=['name', 'num_road', 'name_road', 'postal_code', 'city', 'country']

ProductPlaceFormSet = inlineformset_factory(User, ProductPlace, form=ProductPlaceForm, fields=['name', 'num_road', 'name_road',
                             'postal_code', 'city', 'country'], extra=1)


class ProductForm(forms.ModelForm):
    name = forms.CharField(label='Nom du produit', 
                            widget=forms.TextInput(attrs={
                            'class': 'form-control',
                            'placeholder': 'Nom du point de vente'
                            }))
    price = forms.IntegerField(label='Prix du produit',
                                    widget=forms.NumberInput(
                                    attrs={'class': 'form-control',
                                    'placeholder': 'Prix du produit'}))
    class Meta:
        model = Product
        fields=['name', 'price']

ProductFormSet = inlineformset_factory(
    ProductPlace, Product, form=ProductForm, fields=['name', 'price'], 
    extra=1, can_delete=True
)       


class MenuForm(forms.ModelForm):
    name = forms.CharField(label='Nom du menu', 
                            widget=forms.TextInput(attrs={
                            'class': 'form-control',
                            'placeholder': 'Nom du menu'
                            }))
    price = forms.IntegerField(label='Prix du menu',
                                    widget=forms.NumberInput(
                                    attrs={'class': 'form-control',
                                    'placeholder': 'Prix du menu'}))
    class Meta:
        model = Menu
        fields=['name', 'price']


MenuFormSet = inlineformset_factory(
    ProductPlace, Menu, form=MenuForm, fields=['name', 'price'], 
    extra=1, can_delete=True
)       


#views.py 

def create_product_place(request):
    template_name = 'product_place/place.html'
    heading_message = 'Ajouter des points de vente'
    if request.method == 'GET':
        formset = ProductPlaceFormSet()
        product_formset = ProductFormSet()
        menu_formset = MenuFormSet()
        print(product_formset)
    elif request.method == 'POST':
        formset = ProductPlaceFormSet(request.POST)
        product_formset = ProductFormSet(request.POST)
        menu_formset = MenuFormSet(request.POST)
        if formset.is_valid() and product_formset.is_valid()\
             and menu_formset.is_valid():
            for form in formset:
                #extract infos from each form and save
                name = form.cleaned_data.get('name')
                num_road = form.cleaned_data.get('num_road')
                name_road = form.cleaned_data.get('name_road')
                postal_code = form.cleaned_data.get('postal_code')
                city = form.cleaned_data.get('city')
                country = form.cleaned_data.get('country')
                for product_form in product_formset:
                    product_name = product_form.cleaned_data.get('name')
                    product_price = product_form.cleaned_data.get('price')

                for menu_form in menu_formset:
                    menu_name = menu_form.cleaned_data.get('name')
                    menu_price = menu_form.cleaned_data.get('price')

                #save place instance
                if name and num_road and name_road and postal_code and city\
                    and country:
                    if product_name and product_price and menu_name and menu_price:
                        ProductPlace(name=name, num_road=num_road, name_road=name_road,
                                    postal_code=postal_code,
                                    city=city, country=country, acquired_by=request.user).save()

                        product_place = ProductPlace.objects.get(name=name)
                        Product(name=product_name, price=product_price, place=product_place).save()

                        Menu(name=menu_name, price=menu_price, place=product_place).save()

                return redirect('index')
    return render(request, template_name, {
        'formset': formset,
        'product_formset': product_formset,
        'menu_formset': menu_formset,
        'heading': heading_message,
    })

#place.html

{% extends "src/base.html" %}
{% block body_block %}
{% load static %}

<link rel="stylesheet" type="text/css" href="{% static 'product_place/place-input-style.css' %}">

<div class="place">
<form class="place_form" method="POST" action="">
  {% csrf_token %}
  <div id="items-form-container" class="input-group">
  {{ formset.management_form }}
  <h1>Ajouter un point de vente</h1>
   {% for  item_form in formset %}
        <div id="item-{{ forloop.counter0 }}">
            {{ item_form.id }}
            {{ item_form.as_p }}
        </div>
    {% endfor %}

    {{ product_formset.management_form }}
    <h1>Ajouter des produits</h1>
    <div class='.product'>
      {% for  item_form in product_formset %}
          <div id="item-{{ forloop.counter0 }}">
              {{ item_form.id }}
              {{ item_form.as_p }}
          </div>
      {% endfor %}
    </div>
    <input type="button" value="+ Ajouter un nouveau produit" id="add_product">

    {{ menu_formset.management_form }}
    <div class='.menu'>
    <h1>Ajouter des menus</h1>
      {% for  item_form in menu_formset %}
          <div id="item-{{ forloop.counter0 }}">
              {{ item_form.id }}
              {{ item_form.as_p }}
          </div>
      {% endfor %}
    </div>
    <input type="button" value="+ Ajouter un nouveau menu" id="add_menu">
 </div>
  <div class="input-group-append">
    <input type="button" value="+ Ajouter un nouveau point de vente" id="add_more">
  </div>

  <div class="row spacer">
    <div class="add-item">
      <button type="submit" class="btn btn-block btn-primary">Créer</button>
    </div>

<div id="empty_form" style="display:none">
    <br> </br>
    <table class='no_error'>
        <h1>Ajouter un point de vente</h1>
        {{ formset.empty_form }}
    </table>

    <table class='no_error1'>
        <h1>Ajouter des produits</h1>
        {{ product_formset.empty_form }}
    </table>
    <input type="button" value="+ Ajouter un nouveau produit" id="add_product">


    <table class='no_error1'>
        <h1>Ajouter des menus</h1>
        {{ menu_formset.empty_form }}
    </table>
    <input type="button" value="+ Ajouter un nouveau menu" id="add_menu">

</div>

  </div>
  </form>
  </div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'dynamic_formsets/jquery.formset.js' %}"></script>
<script type='text/javascript'>
      $('#add_more').click(function() {
      var form_idx = $('#id_product_places-TOTAL_FORMS').val();
      alert(form_idx)
      $('#items-form-container').append($('#empty_form').html().replace(/__prefix__/g, form_idx));
      $('#id_product_places-TOTAL_FORMS').val(parseInt(form_idx) + 1);
      });

      $('#add_product').click(function() {
      var form_idx = $('#id_products-TOTAL_FORMS').val();
      alert(form_idx)
      $('.product').append($('#empty_form').html().replace(/__prefix__/g, form_idx));
      $('#id_products-TOTAL_FORMS').val(parseInt(form_idx) + 1);
      });

      $('#add_menu').click(function() {
      var form_idx = $('#id_menus-TOTAL_FORMS').val();
      $('.menu').append($('#empty_form').html().replace(/__prefix__/g, form_idx));
      $('#id_menus-TOTAL_FORMS').val(parseInt(form_idx) + 1);
      });
</script>

  {% comment %} <script type="text/javascript">
  $('.place_form').formset({
            addText: 'add family member',
            deleteText: 'remove',
            prefix: '{{ formset.prefix }}'
          });
</script> {% endcomment %}
{% endblock %}


我想动态添加产品和菜单,但我不能。我只能添加新的产品位置,但不能添加产品或特定产品位置的菜单。

0 个答案:

没有答案