Reputation: 397
The question is that my form is dynamical. Every time there may be different number of fields depending on data in DB. I am able to render this form manually (by passing attributes and types to template as context). But how can I handle the action of pressing submit button in django?
Upvotes: 0
Views: 2398
Reputation: 11943
Assuming you already have a function into your views.py to render the template, you just basically have to verify if there have been any data posted :
def contact(request): # let's say it's a contact form
if request.method == 'POST': # If the form has been submitted...
print(request.POST)
# do your things with the posted data
else: # form not posted : show the form.
return render(...)
Also please note that you have to manually add {% csrf_token %}
anywhere between your <form>
and </form>
inside your template, which basically add a hidden field to secure your site against Cross Site Request Forgery attacks.
And if you do it like that, just don't put any action
attribute in your form, so that it posts to the same url.
Upvotes: 2