The first argument of every Django view is the HttpRequest
object that is usually named request
. It contains metadata about the request. For example, current language code, current user, current cookies, and current session. By default, the forms that are used in the views accept the GET
or POST
parameters, files, initial data, and other parameters; however, not the HttpRequest
object. In some cases, it is useful to additionally pass HttpRequest
to the form, especially when you want to filter out the choices of form fields using the 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; we don't want anybody to write a message to themselves.