1👍
✅
Redirecting to the same page will solve the problem
if form.is_valid():
instance = form.save(commit=False)
book = form.cleaned_data.get("book")
author = form.cleaned_data.get("author")
price = form.cleaned_data.get("price")
cat = form.cleaned_data.get("cat")
image = form.cleaned_data.get("image")
instance.book = book
instance.author = author
instance.price = price
instance.cat = cat
instance.image = image
instance.save()
messages.add_message(request, messages.INFO,'Product Added')
return redirect("add_prod")
0👍
define action
parameter in form tag and no need of javascript to clear form fields
<form method="POST" action='your url or simply place dot(.) to redirect current url' enctype="multipart/form-data" name="myform" id="myform" onSubmit="clearField();">
{% csrf_token %}
<table>
{{form.as_table}}
</table>
<input type="submit" value="Add"/>
<input type="reset" value="Cancel"/>
<input type="hidden" name="next" value="{{next}}">
</form>
- {Javascript} How to return Json when calling POST xmlHttpRequest
- User created in migration does not exist
0👍
When the page is loaded, you don’t need to render the empty form, as described in else part.
def add_prod(request):
if request.method == 'POST':
form = ProdForm(request.POST or None, request.FILES or None)
my_products = Add_prod.objects.all()
context = {
"form":form,
"products":my_products
}
if form.is_valid():
instance = form.save(commit=False)
instance.book = form.cleaned_data.get("book")
instance.author = form.cleaned_data.get("author")
instance.price = form.cleaned_data.get("price")
instance.cat = form.cleaned_data.get("cat")
instance.image = form.cleaned_data.get("image")
instance.save()
form = ProdForm()
messages.add_message(request, messages.INFO,'Product Added')
else:
form = ProdForm()
return render(request,"add-prod.html",context)
- Assign field from related model as default in another model
- How to use TextInput widget with ModelChoiceField in Django forms?
- Django static import on template
- Django how to get password after registration form is submitted?
- How to understand how exception handling is working?
Source:stackexchange.com