Reputation: 565
Good morning, when I try to send the form, I get the error, and when I send it, it generates that my view does not return any httpresponse object.
this is the view
class ProductView(View):
template_name = 'products/product.html'
model = Product
form_class = ProductForm
def get_queryset(self):
return self.model.objects.filter(state=True)
def get_context_data(self, **kwargs):
context = {}
context['product'] = self.get_queryset()
context['list_product'] = self.form_class
return context
def get(self, request, *args, **kwargs):
return render(request, self.template_name, self.get_context_data())
def post(self, request, *args, **kwargs):
list_product = self.form_class(request.POST)
if list_product.is_valid():
list_product.save()
return redirect('products:product')
and this is the form
class ProductForm(forms.ModelForm):
name_product = forms.CharField(
max_length=25,
widget=forms.TextInput(
attrs={
'class': 'form-control',
'id': 'name_product',
}
)
)
def clean_name_product(self):
name_product = self.cleaned_data.get('name_product')
if Product.objects.filter(name_product=name_product).exists():
raise forms.ValidationError('El nombre del producto ya existe')
return name_product
class Meta:
model = Product
fields = (
'name_product', 'description', 'price', 'category', 'state', 'image'
)
labels = {
'name_product': 'Nombre del Producto',
'description': 'Descripcion',
'price': 'Precio',
'category': 'Categoria',
'state': 'Estado',
'image': 'Imagen del Producto',
}
widgets = {
'name_product': forms.TextInput(
attrs={
'class': 'form-control',
'id': 'name_product',
}
),
'description': forms.TextInput(
attrs={
'class': 'form-control',
'id': 'description',
}
),
'price': forms.NumberInput(
attrs={
'class': 'form-control',
'id': 'price',
}
),
'category': forms.SelectMultiple(
attrs={
'class': 'custom-select',
'id': 'category',
}
),
'state': forms.CheckboxInput(),
}
when I give send it generates the error.The view products.views.ProductView didn't return an HttpResponse object. It returned None instead.
At the beginning I thought that the error is due to the error lifting in the form, change the code without the validation and it generates the same error
Upvotes: 1
Views: 68
Reputation: 476493
In case the form.is_valid()
fails, you do not return anything in the post
method, hence the error. That being said, this is basically just a CreateView
[Django-doc], so it might be better to use that to reduce the amount of "boilerplate" code:
from django.views.generic.edit import CreateView
class ProductView(CreateView):
template_name = 'products/product.html'
model = Product
form_class = ProductForm
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context.update(
product=Product.objects.filter(state=True),
list_product=context['form']
)
return context
Upvotes: 2