Reputation: 6606
I'm currently learning django from the 'How to tango with django' site and i'm unable to understand the chapter dealing with forms. Appreciate it if someone would help me out.
http://www.tangowithdjango.com/book17/chapters/forms.html
the first step is to create a forms page which maps to models.py. I seem to understand this part. I also understand that we create a view to process the data acquired from these forms. I'm not able to understand the below code in the views page.
from rango.forms import CategoryForm
def add_category(request):
# A HTTP POST?
if request.method == 'POST':
form = CategoryForm(request.POST)
else:
# If the request was not a POST, display the form to enter details.
form = CategoryForm()
How do the urlmapper know that a request method is POST or GET before the user actually enters any data in the form? On a similar note, when would a form have a get method?
form = CategoryForm(request.POST)
- would someone explain this to me? CategoryForm looks to be a class which is already inheriting from another class
what does the request.POST argument convey ?
Upvotes: 0
Views: 104
Reputation: 851
1) The urlmapper does by default not care about GET or POST request method. It will route any request to the given view-function.
Normally, your form html-code will look like this:
<form method="post" action="some_url">
...
</form>
So, when you submit the form, the data will be send to some_url with the specified method, in this case post.
You may want to read something about when to use GET or POST, normally forms are transferred using POST.
2) form = CategoryForm(request.POST)
will bind the values provided in the request's POST-dictionary to the form. You may say, it prepopulates this. This way, further working with the form (like validating it by calling form.is_valid()
) will be made possible.
Perhaps you should investigate further on Django forms and modelforms by reading some official documentation.
Upvotes: 1
Reputation: 599610
Why do you think the URL mapper knows if it's a post it a get? It doesn't, and it doesn't care.
The thing you are missing is that this view has two responsibilities: showing the initial form (on GET) and processing the submitted form (on POST).
Your second question shows an unfamiliarity with basic Python syntax. request.POST
is the parameter to the initialisation of the form instance.
Upvotes: 0