TransWikia.com

Formset not showing in Django 3

Stack Overflow Asked by Ethan Roman on December 13, 2021

i am creating invoice and items using **formset inline ** , the problem is the forms is not showing in the templates

here is the models , forms views and template
can anyone help or direct me for a better way for creating an invoice with dynamic items where you can add or remove for item using query.formset.js plugin

class Invoice(models.Model):
invNo         = models.CharField(max_length=255,null=True)
supplier      = models.ForeignKey(Supplier,on_delete=models.CASCADE,null=True,blank=True)
note          = models.TextField(blank=True)

class Items(models.Model):
Invoice  = models.ForeignKey(Invoice,on_delete=models.CASCADE,null=True,blank=True,db_index=True)
item     = models.CharField(max_length=255,null=True)
price    = models.DecimalField(max_digits=5, decimal_places=2,default="0.00")
q        = models.PositiveIntegerField(verbose_name="Quantity")
location = models.CharField(max_length=255,null=True,blank=True)
reason   = models.TextField(max_length=255,null=True)

Forms

class ItemsForm(forms.ModelForm):

class Meta:
    model = Items
    exclude = ()

ItemsFormSet = inlineformset_factory(Invoice, Items, form=ItemsForm,fields=['item', 'price'], extra=1, can_delete=True)

self.helper.layout = Layout(
            Div(
                Field('invNo'),
                Field('supplier'),
                Fieldset('Add Item',
                    Formset('Items')),
                Field('note'),
                HTML("<br>"),
                ButtonHolder(Submit('submit', 'save')),
                )
            )

Views :

class InvoiceDetailView(DetailView):
model = Invoice
template_name = 'invoice_detail.html'

def get_context_data(self, **kwargs):
    context = super(InvoiceDetailView, self).get_context_data(**kwargs)
    return context

class InvoiceCreate(CreateView):
model = Invoice
template_name = 'addinv.html'
form_class = InvoiceForm
success_url = None

def get_context_data(self, **kwargs):
    data = super(InvoiceCreate, self).get_context_data(**kwargs)
    if self.request.POST:
        data['items'] = ItemsFormSet(self.request.POST)
    else:
        data['items'] = ItemsFormSet()
    return data

def form_valid(self, form):
    context = self.get_context_data()
    items = context['items']
    with transaction.atomic():
        form.instance.created_by = self.request.user
        self.object = form.save()
        if items.is_valid():
            items.instance = self.object
            items.save()
    return super(CollectionCreate, self).form_valid(form)

 def get_success_url(self):
     return reverse_lazy('mycollections:collection_detail', kwargs={'pk': self.object.pk})

Template :

{% extends 'core/base.html' %}
{% load static %}
 {% load crispy_forms_tags %} 


{% block css %}

{% endblock %}
{% block content %}
  <table>
    {{ formset.management_form|crispy }}

  {% for form in formset.forms %}
          <tr class="{% cycle 'row1' 'row2' %} formset_row-{{ formset.prefix }}">
              {% for field in form.visible_fields %}
              <td>
                  {# Include the hidden fields in the form #}
                  {% if forloop.first %}
                      {% for hidden in form.hidden_fields %}
                          {{ hidden }}
                      {% endfor %}
                  {% endif %}
                  {{ field.errors.as_ul }}
                  {{ field|as_crispy_field }}
              </td>
              {% endfor %}
          </tr>
  {% endfor %}

script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
  <script src="{% static 'js/jquery.formset.js' %}">
  </script>
  <script type="text/javascript">
      $('.formset_row-{{ formset.prefix }}').formset({
          addText: 'add another',
          deleteText: 'remove',
          prefix: '{{ formset.prefix }}',
      });
  </script>

 {% endblock%}

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP