@ilyaa01
Новичёк не судите строго

Django inlineformset_factory forms Error The view shop.views.view didn't return an HttpResponse object. It returned None instead?

Я сделал inlineformset хочу чтоб при нажатии кнопки добовлялась inline строка
Оно выводит ошибку:
"The view shop.views.view didn't return an HttpResponse object. It returned None instead"
> forms

class ProductForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for _, value in self.fields.items():
            value.widget.attrs['placeholder'] = value.label
    class Meta:
        model = Product
        widgets = {
            'description': SummernoteWidget(),
        }
        fields = ["inID", "category", "subcategory", "name", "brend", "slug", "parent", "description", "price", "stock", "available"]

class ProductImageForm(forms.ModelForm):
    class Meta:
        model = ProductImage
        fields = ['image', 'mdoel']
    def __init__(self, *args, **kwargs):
        super(ProductImageForm, self).__init__(*args, **kwargs)
        for _, value in self.fields.items():
            value.widget.attrs['placeholder'] = value.label
ProductImageFormSet = forms.inlineformset_factory(Product, ProductImage, form=ProductImageForm, extra=8, max_num=25)


class ProductCharacteristicsForm(forms.ModelForm):
    class Meta:
        model = ProductCharacteristics
        fields = ['name', 'description', 'mdoel']
    def __init__(self, *args, **kwargs):
        super(ProductCharacteristicsForm, self).__init__(*args, **kwargs)
        for _, value in self.fields.items():
            value.widget.attrs['placeholder'] = value.label
ProductCharacteristicsFormSet = forms.inlineformset_factory(Product, ProductCharacteristics, form=ProductCharacteristicsForm, extra=1, max_num=35)


> views

class AddProduct(View):
    def get(self, request):
        form = ProductForm()
        image = ProductImageFormSet()
        char = ProductCharacteristicsFormSet()
        cart = request.session.get('cart', {})
        data = {
            'title': "Додати продукт",
            'form': form,
            'images': image,
            'chars': char,
            'cart': cart,
            'total_price': get_total_price(cart),
            'total_quantity': get_total_quantity(cart),
        }
        return render(request, 'shop/add_product.html', data)
    def post(self, request):
        form = ProductForm(request.POST)
        image = ProductImageFormSet(request.POST, request.FILES)
        char = ProductCharacteristicsFormSet(request.POST, request.FILES)
        if form.is_valid() and image.is_valid() and char.is_valid():
            product = form.save()
            image.instance = product
            image.save()
            char.instance = product
            char.save()
            return redirect('index')


> html

<section>
	<form method="post" enctype="multipart/form-data">
		{% csrf_token %}
		<div class="images_cont">
			<h2>Inline Form</h2>
			<fieldset class="images" id="images">
				{{ images.management_form }}
				{% for image in images %}
					{{ image.image }}
				{% endfor %}
			</fieldset>
			<button class="add_line" type="button">Add image</button>
		</div>
		<div class="chars_cont">
			<h2>Inline Form</h2>
			<fieldset class="chars" id="chars">
				{{ chars.management_form }}
				{% for char in chars %}
					{{ char.name }}
					{{ char.description }}
					<button type="button">Remove</button>
				{% endfor %}
			</fieldset>
			<button class="add_line" type="button">Add char</button>
		</div>
	</form>
</section>

<script>
	$(document).ready(function() {
		$('.images_cont .add_line').click(function() {
			var formset = $("#images")
			var n = formset.children("input[type='file']").length
			formset.append(`<input type="file" name="productimage_set-${n}-image" accept="image/*" placeholder="Додати фото" id="id_productimage_set-${n}-image">`);
			$("#id_productimage_set-TOTAL_FORMS").val(n + 1)
		});
		$('.chars_cont .add_line').click(function() {
			var formset = $("#chars")
			var n = (formset.children("input[type='text']").length / 2)
			console.log(n)
			var code = `<input type="text" name="productcharacteristics_set-${n}-name" maxlength="200" placeholder="Назва" id="id_productcharacteristics_set-${n}-name">
			<input type="text" name="productcharacteristics_set${n}-description" maxlength="2000" placeholder="Опис" id="id_productcharacteristics_set-${n}-description">
			<button type="button">Remove</button>`
			formset.append(code);
			$("#id_productcharacteristics_set-TOTAL_FORMS").val(n + 1)
		});
	});
</script>

  • Вопрос задан
  • 65 просмотров
Решения вопроса 1
@ilyaa01 Автор вопроса
Новичёк не судите строго
Сам нашёл ответ
Django Inline Formset Factory with Examples
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

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

Войти через центр авторизации
Похожие вопросы