如何在 Django 中使用 CBV 中的表单集?

How to work with the formset in CBV at the Django?

我有一个表格 ProductCreateForm。有必要在其中插入 SpeciallyPriceForm 形式。

我对 ProductCreateForm 有看法。但是里面的SpeciallyPriceForm我也不知道怎么处理

class ProductsCreate(CreateView):
    model = Product
    form_class = ProductCreateForm
    http_method_names = ['get', 'post']

    def get_form_kwargs(self):
        print('form')
        kwargs = super(ProductsCreate, self).get_form_kwargs()
        kwargs['request'] = self.request
        return kwargs

    def get(self, request, *args, **kwargs):
        self.object = None
        ...
        return self.render_to_response(self.get_context_data())

    def post(self, request, *args, **kwargs):
        self.object = None
        form = self.get_form()
        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

    def form_valid(self, form):
        product = form.save(commit=False)
        product.user = self.request.user
        product.save()
        if self.request.is_ajax():
            return JsonResponse({'success': True, 'location': location})
        else:
            return redirect(location)

    def form_invalid(self, form):
        ....

upd.

class ProductsCreate(CreateView):
    model = Product
    form_class = ProductCreateForm
    # template_name = 'products/product_form.html'
    http_method_names = ['get', 'post']

    def get_form_kwargs(self):
        kwargs = super(ProductsCreate, self).get_form_kwargs()
        kwargs['request'] = self.request
        return kwargs

    def get_context_data(self, *args, **kwargs):
        print('ok')
        ctx=super(ProductsCreate, self).get_context_data(*args, **kwargs)
        ctx['special_form'] = SpeciallyPriceForm()
        return ctx

    def get(self, request, *args, **kwargs):
        self.object = None
        if kwargs.get('slug'):
            category = Category.objects.filter(slug=kwargs.get('slug')).first()
            self.initial.update({'category': category})
        return self.render_to_response(self.get_context_data())


    def post(self, request, *args, **kwargs):
        self.object = None
        form = self.get_form()
        special_form = SpeciallyPriceForm(self.request.POST)
        if form.is_valid() and special_form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

    def form_valid(self, form):
        product = form.save(commit=False)

我需要模板作为

<form ... >
    {{ form }}       /*product_form
    {{ formset }}    /* specially_price_form
</form>

upd2

型号

class Product(models.Model):
    category = models.ForeignKey(
        Category, related_name='product',
        verbose_name=_('category'), on_delete=models.SET_NULL, null=True,
    )

表格

self.fields['category'] = ModelMultipleChoiceField(queryset=provider.category.all())

def clean(self):
        cleaned_data = super(ProductCreateForm, self).clean()
        cd_category = cleaned_data.get('category')

观看次数

form = self.get_form()   #Error

我相信 formset 确实是用不同的实例多次显示相同的表单。你在这里想要的是2种形式。添加 get_context data

def get_context_data(self, *args, **kwargs):
   ctx=super().get_context_data(*args, **kwargs)
   ctx['special_form'] = SpeciallyPriceForm()
   return ctx

def form_valid(self, form):
    special_form = SpeciallyPriceForm(self.request.POST)
    if special_form.is_valid():
    ...
    else: error code and return to screen