Passing HttpRequest to a form

The first argument of every Django view is the HttpRequest object, which by convention is named request. It contains metadata about the request sent from a browser or other client, including such items as the current language code, user data, cookies, and session. By default, forms that are used by views accept the GET or POST data, files, initial data, and other parameters; however, they do not inherently have access to the HttpRequest object. In some cases, it is useful additionally to pass HttpRequest to the form, especially when you want to filter out the choices of form fields based on other request data, or handle saving something such as the current user or IP in the form.

In this recipe, we will see an example of a form where a person can choose a user and write a message to them. We will pass the HttpRequest object to the form in order to exclude the current user from the recipient choices, as we don't want anybody to write a message to themselves.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.251.169