E
E
ErikHabr2020-07-13 19:41:52
Django
ErikHabr, 2020-07-13 19:41:52

How to link forms in django?

People please help! I've been struggling with this all week.
In general, I have two forms on the same page, one form should automatically substitute the name of the block in which we are in the select (it works), and the second should, depending on which block we are in the select, provide options for choosing categories of only this block, I hope I explained it clearly .

# views.py file # views.py file # views.py file # views.py file # views.py file # views.py file 
class AddTable(SuccessMessageMixin, CreateView):
    model = TableCategory
    form_class = TableCategoryForm
    second_form_class = TableItemsForm
    template_name = 'forms/table_add.html'
    success_url = '.'
    success_message = "Категория таблицы успешно добавленна"

    def get_initial(self):
        initial = super(AddTable, self).get_initial()
        initial['block'] = CreateBlock.objects.get(pk=self.kwargs['pk'])
        return initial

    def get_context_data(self, **kwargs):
        context = super(AddTable, self).get_context_data(**kwargs)
        context['tablecat'] = TableCategory.objects.filter(block=self.kwargs['pk'])
        context['tableitem'] = TableItems.objects.all()

        #if 'formcat' not in context:
        #    context['formcat'] = self.form_class()
        if 'form2' not in context:
            context['form2'] = self.second_form_class()
        return context
        
# forms.py file # forms.py file # forms.py file # forms.py file # forms.py file # forms.py file      
class TableCategoryForm(forms.ModelForm):
    class Meta:
        model = TableCategory
        fields = '__all__'
        #widgets = {'block': forms.HiddenInput}

class TableItemsForm(forms.ModelForm):
    class Meta:
        model = TableItems
        fields = '__all__'

# models.py file # models.py file # models.py file # models.py file # models.py file # models.py file
# tables models
class TableCategory(models.Model):
    """ table category  """
    block = models.ForeignKey(CreateBlock, on_delete=models.CASCADE, related_name='blocktablecat', default=0)
    category = models.CharField(max_length=50)

    def __str__(self):
        return self.category

    class Meta:
        verbose_name = 'Категория таблицы'
        verbose_name_plural = 'Категории таблицы'

class TableItems(models.Model):
    """ table items  """
    category = models.ForeignKey(TableCategory, related_name='tableitems', on_delete=models.PROTECT)
    name = models.CharField(max_length=50)
    price = models.SmallIntegerField(default=0)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = 'Содержимое таблицы'
        verbose_name_plural = 'Содержимое таблицы'


# urls.py file # urls.py file  # urls.py file  # urls.py file 
path('block/<int:pk>/add/table/', views.AddTable.as_view(), name='add_table'),

# html file # html file # html file # html file # html file
<form method="post">
   {% csrf_token %}
   {{ form|crispy }}
   <button type="submit" class="btn btn-primary btn-sm waves-effect waves-light">Добавить</button>
  </form>
 </div>
 <div class="col-md-7">
  <form method="post">
   {% csrf_token %}
{{ form2|crispy }}
   <button type="submit" class="btn btn-primary btn-sm waves-effect waves-light">Добавить</button>
  </form>
 </div>
</div>


<div class="box-content">
{% if tablecat %}
  {% for cat in tablecat %}
      <table class="table table-striped">
        <p class="table_head">{{ cat.category }}</p>
          {% for item in cat.tableitems.all %}
         <tr>
          <td>{{ item.name }}</td>
          <td>{{ item.price }} руб</td>
         </tr>
          {% endfor %}
      </table>
    {% endfor %}
{% else %}
  <p>Вы еще не создали объектов для таблицы. Заполните формы выше.<br/>
    Сначала создайте категорию для определенных объектов, затем добавьте сами объекты в созданную категорию и т.д.</p>
{% endif %}
</div>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Tikhonov, 2020-07-14
@ErikHabr

This is how it's done with autocomplete-light. You can either use the library, or peep the implementation in JS there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question