Reputation: 43
Can someone check what i'm omitting here? The Validation error is not showing up even when it should. It's just returning successful when it should've showed a validation error. When I run my server and insert a title less than 5 charcters, it still returns successful instead of raising a Validating error.
views.py;
def form_view(request):
if request.method == 'POST':
form = ProductForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.save()
return HttpResponse("successful")
else:
return render(request, "product_create.html", {'form': form})
else:
form = ProductForm(None)
return render(request, 'product_create.html', {'form': form})
models.py;
from django.db import models
# Create your models here.
class Product(models.Model):
title = models.CharField(max_length=120)
description = models.CharField(blank=True, null=True, max_length=250)
price = models.FloatField()
forms.py;
from django import forms
from .views import Product
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = [
'title',
'description',
'price',
]
def cleaned_title(self):
title = self.cleaned_data.get('title')
if len(title) < 5:
raise forms.ValidationError("This is not a valid title")
return self.cleaned_data
template;
product_create.html:
{% block content %}
<form action="." method="post"> {% csrf_token %}
{{ form.as_p }}
<input type="submit" value="save">
</form>`enter code here`
{% endblock %}
Upvotes: 0
Views: 26