2👍
Thanks to Daniel Roseman and Anuj Gupta I think I finally re-worked on my code on got it working in a standard way so it will generate the html form and validate errors.
So for anyone else who is trying to work django forms here is the code I worked on.
My model.py is was almost the same one i posted on the question but i removed
class ProductForm(ModelForm):
class Meta:
model = Product
I created a new form.py here is the code-
from django import forms
from models import Category
class ProductForm(forms.Form):
# Put all my Categories into a select option
category = forms.ModelChoiceField(queryset=Category.objects.all())
product = forms.CharField()
quantity = forms.IntegerField()
price = forms.FloatField()
My views.py changed had a lot of changes –
def add_product(request):
success = False
if request.method == "POST":
product_form = ProductForm(request.POST)
if product_form.is_valid():
success = True
category = Category.objects.get(name=product_form.cleaned_data['category'])
product = product_form.cleaned_data['product']
quantity = product_form.cleaned_data['quantity']
price = product_form.cleaned_data['price']
new_product = Product(category = category, product = product, quantity = quantity, price = price )
new_product.save()
new_product_form = ProductForm()
ctx2 = {'success':success, 'product_form':new_product_form}
return render_to_response('product/add_product.html', ctx2 , context_instance=RequestContext(request))
else:
product_form = ProductForm()
ctx = {'product_form':product_form}
return render_to_response('product/add_product.html', ctx , context_instance=RequestContext(request))
Finally in my html page i used {{ product_form.as_p }}
so it created the forms dynamically
{% if success %}
<h3> product added successfully </h3>
{% endif %}
<form method="post" action=".">
{% csrf_token %}
{{ product_form.as_p }}
<input type="submit" value="Add New product" id="create">
<input type="reset" value="reset" id="reset">
</form>
This may not be the perfect solution, but for a starter like me this sounds good, and at times you just get lost while reading the docs lol, hope it helps some one.
Cheers
3👍
You should read the documentation. If the form is not valid, it will have a whole set of errors associated with it, which will tell you exactly why. But you just throw that away, and redirect to /product
. The docs show exactly how to redisplay the form with the errors.
Also you should not write HTML form field tags directly in your template: use the form object from the view – {{ form.product }}
, etc – as these will be repopulated with the appropriate values on redisplay.
- [Django]-Django rest-framework singleton ViewSet
- [Django]-Is it possible to show progress bar of django celery task?
- [Django]-My custom heroku python buildpack downloads requirements on every push
- [Django]-How can I disable some options in the Select widget of a mptt's TreeForeignKey field in some model admin?
- [Django]-Docker-compose ERROR [internal] booting buildkit, http: invalid Host header while deploy Django
1👍
Try:
<form method="post" action="add_product/">
{% csrf_token %}
{{ form.as_p }}
</form>
in your template, instead of hand-coding the form’s input tags. This shortcut will generate the form html for you, as well as print validation errors.
Make sure you return the form
object to the template when:
- There is no request.POST (form has not been submitted)
- form.is_valid() fails (form has validation errors)
Of course, this is only to get you started. You really should read the docs
- [Django]-Python-ModuleNotFoundError: No module named 'django.db.migrations.migration'
- [Django]-What's the best way to display accurate current time and date in Django?
- [Django]-How to get rid of spacing in SimpleDocTemplate(). Python. ReportLab