B
B
blackbb2016-10-31 14:13:52
Django
blackbb, 2016-10-31 14:13:52

How to apply inlineformset_factory correctly?

There are two models:

class Company(models.Model):
    user = models.ForeignKey(User, verbose_name=u'Пользователь')
    info = models.CharField(max_length=300, verbose_name=u'Информация о компании', blank=True)
class CompanyImage(models.Model):
    description = models.CharField(max_length=200, verbose_name=u'Описание', default='')
    file = models.FileField(upload_to='images/company',blank=True, verbose_name=u'Фотографии')
    order = models.ForeignKey(Company, verbose_name=u'Фото компании')

There is a form of company formation
class AddCompanyForm(forms.ModelForm):
    class Meta:
        model = Company
        fields = '__all__'
        exclude = ['user']

And the formset:
CompanyFormSet = inlineformset_factory(Company, CompanyImage, fields = '__all__')

In views.py:
class CompanyCreate(CreateView):
    model = Company
    template_name = 'add_company.html'
    form_class = AddCompanyForm
    success_url = '/orders'
   
    def get(self, request, *args, **kwargs):
        """
        Handles GET requests and instantiates blank versions of the form
        and its inline formsets.
        """
        self.object = None
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        company_form = CompanyFormSet()
        return self.render_to_response(
            self.get_context_data(form=form,
                                  company_form=company_form))

    def post(self, request, *args, **kwargs):
        """
        Handles POST requests, instantiating a form instance and its inline
        formsets with the passed POST variables and then checking them for
        validity.
        """
        self.object = None
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        company_form = CompanyFormSet(self.request.POST)
        if (form.is_valid() and company_form.is_valid()):
            return super(CompanyCreate, self).form_valid(form)
        else:
            return self.form_invalid(form, company_form)

    def form_valid(self, form, company_form):
        """
        Called if all forms are valid. Creates a Recipe instance along with
        associated Ingredients and Instructions and then redirects to a
        success page.
        """
        self.object = form.save()
        company_form.instance = self.object
        company_form.instance.user = self.request.user
        company_form.save()
        return HttpResponseRedirect(self.get_success_url())

    def form_invalid(self, form, company_form):
        """
        Called if a form is invalid. Re-renders the context data with the
        data-filled forms and errors.
        """
        return self.render_to_response(
            self.get_context_data(form=form,
                                  company_form=company_form))

I output it like this in the template:
{%extends 'base.html'%}
{%block content%}
    <h3>Добавление компании</h3>
    <form action="" method="post" enctype="multipart/form-data">
    {% csrf_token %}
{{ form.as_p }}
 <br>
            <fieldset>
                <legend></legend>
                {{ company_form.management_form }}
                {{ company_form.non_form_errors }}
                {% for form in company_form %}
                    {{ form.id }}
                    <div class="inline {{ company_form.prefix }}">
                        {{ form.file.errors }}
                        {{ form.file.label_tag }}
                        {{ form.file }}
                        {{ form.description.errors }}
                        {{ form.description.label_tag }}
                        {{ form.description }}

                    </div>
                {% endfor %}
            </fieldset>

 <button class="btn btn-primary" type="submit" name="submit">Добавить</button>
    </form>
{%endblock%}

The problem is that when the form is saved, only the main form is written to the database, but the formset is not. What could be the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
blackbb, 2016-11-01
@blackbb

Solved the problem. Need to add to return company_form

if (form.is_valid() and company_form.is_valid()):
            return self.form_valid(form, company_form)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question