E
E
ErikHabr2020-07-18 10:49:49
Django
ErikHabr, 2020-07-18 10:49:49

When submitting the second form, the required field of the first form is highlighted. How to fix?

Hello. I have two forms on the same page, but when submitting the second form, a required field is requested from the first form! Why? how to fix it?

views

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 'formitem' not in context:
            context['formitem'] = self.second_form_class()
        return context


forms
class TableCategoryForm(forms.ModelForm):
    class Meta:
        model = TableCategory
        fields = '__all__'
        #widgets = {'block': forms.HiddenInput}


class TableItemsForm(forms.ModelForm):
    #Category = forms.ModelChoiceField(queryset=TableCategory.objects.all())
    #block = CreateBlock.objects.all()
    class Meta:
        model = TableItems
        fields = '__all__'
        widgets = {
            'category': autocomplete.ModelSelect2(url='category-autocomplete',
                                                  forward=['block']
                                                  )
        }


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.CASCADE)
    name = models.CharField(max_length=50)
    price = models.SmallIntegerField(default=0)

    def __str__(self):
        return self.name

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

html
<div class="box-content">
 <div class="col-md-6">
  <form method="post">
   {% csrf_token %}
   {{ form|crispy }}
   <button type="submit" name="btncat" class="btn btn-primary btn-sm waves-effect waves-light">Добавить категорию</button>
  </form>
 </div>
 <div class="col-md-6">
  <form method="post">
   {% csrf_token %}
   {{ formitem|crispy }}
   {{ formitem.media }}
   <button type="submit" name="btnitem" class="btn btn-primary btn-sm waves-effect waves-light">Добавить объект</button>
  </form>
 </div>
</div>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
alfss, 2020-07-18
@alfss

Do not use for 2 forms 1 view

D
Dmitry, 2020-07-19
@pyHammer

ErikHabr please here is a ready solution, https://gist.github.com/jamesbrobb/748c47f46b9bd224b07f

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question