@blackbb

Как правильно применять inlineformset_factory?

Имеется две модели:
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'Фото компании')

Есть форма создания компании
class AddCompanyForm(forms.ModelForm):
    class Meta:
        model = Company
        fields = '__all__'
        exclude = ['user']

И формсет:
CompanyFormSet = inlineformset_factory(Company, CompanyImage, fields = '__all__')

В 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))

В шаблоне вывожу так:
{%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%}

Проблема в том, что при сохранении формы в базу записывается только основная форма, а формсет нет. В чем может быть проблема?
  • Вопрос задан
  • 3071 просмотр
Решения вопроса 1
@blackbb Автор вопроса
Проблему решил. Нужно добавить в return company_form
if (form.is_valid() and company_form.is_valid()):
            return self.form_valid(form, company_form)
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы