如何在一个CreateView中创建多个表单集?

时间:2018-07-04 20:23:56

标签: python django python-3.x

我有两个模型:

class Recipe(Model):

    title = CharField(blank=True, max_length=255)
    slug = SlugField()

    user = ForeignKey(get_user_model(), on_delete=CASCADE)

    categories = TaggableManager()

    class Meta:
        ordering = ['id']

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title, allow_unicode=True)
        return super(Recipe, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse("recipes:detail", kwargs={"pk": self.pk})


class RecipeStep(Model):

    recipe = ForeignKey(Recipe, on_delete=CASCADE, related_name="steps")

    ingredients = ManyToManyField(Ingredient)

    title = CharField(blank=True, max_length=255)
    slug = SlugField()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title, allow_unicode=True)
        return super(RecipeStep, self).save(*args, **kwargs)

我需要这样做,以便在创建食谱model时可以创建RecipeStep model

为此,我做了2个ModelForminlineformset

class RecipeForm(forms.ModelForm):

    class Meta:
        model = Recipe
        fields = ['title']


class RecipeStepForm(forms.ModelForm):

    class Meta:
        model = RecipeStep
        fields = ['title']

RecipeInlineForm = inlineformset_factory(
    Recipe,
    RecipeStep,
    form=RecipeStepForm,
    extra=1,
    can_delete=False,
    can_order=False
)

我使用CreateView创建新食谱:

class RecipeCreateView(LoginRequiredMixin, CreateView):

    model = Recipe
    form_class = RecipeForm

    def form_valid(self, form):
        form.instance.user = self.request.user
        context = self.get_context_data()
        inlines = context['inlines']
        if inlines.is_valid() and form.is_valid():
            self.object = form.save()
            for inline in inlines:
                inline.instance.recipe = self.object
                inline.save()
            return super(RecipeCreateView, self).form_valid(form)
        else:
            return self.render_to_response(self.get_context_data(form=form))

    def form_invalid(self, form):
        return self.render_to_response(self.get_context_data(form=form))

    def get_context_data(self, **kwargs):
        context = super(RecipeCreateView, self).get_context_data(**kwargs)
        if self.request.POST:
            context['form'] = RecipeForm(self.request.POST)
            context['inlines'] = RecipeInlineForm(self.request.POST)
        else:
            context['form'] = RecipeForm()
            context['inlines'] = RecipeInlineForm()
        return context

一切正常。我什至为Bootstrap 4创建了一个jQuery脚本,该脚本可让您在创建配方时添加无限数量的新RecipeStep。

而且,我还有2个models

class RecipePhoto(Model):

    recipe = ForeignKey(Recipe, on_delete=CASCADE)
    image = ImageField(
        upload_to=get_recipe_image_filename,
        verbose_name="images"
    )


class RecipeStepPhoto(Model):

    recipe_step = ForeignKey(RecipeStep, on_delete=CASCADE)
    image = ImageField(
        upload_to=get_recipe_step_image_filename,
        verbose_name="images"
    )

如何使这些models也是formset

0 个答案:

没有答案