Django does not print any errors to the console by default. Instead it provides very helpful error pages that are displayed for any errors that occur in your views. Please check what your DEBUG setting is set to. In development this should be True which will give you the nice error pages for 404 and 500 errors.
When a POST request is received at the Django server, the data in the request can be retrieved using the HTTPRequest. POST dictionary. All the data of the POST request body is stored in this dictionary. For example, you can use the following code snippet inside your view.py file.
_ in Django is a convention that is used for localizing texts. It is an alias for ugettext_lazy.
Use the MultiValueDict's get
method. This is also present on standard dicts and is a way to fetch a value while providing a default if it does not exist.
is_private = request.POST.get('is_private', False)
Generally,
my_var = dict.get(<key>, <default>)
Choose what is best for you:
is_private = request.POST.get('is_private', False);
If is_private
key is present in request.POST the is_private
variable will be equal to it, if not, then it will be equal to False.
if 'is_private' in request.POST:
is_private = request.POST['is_private']
else:
is_private = False
from django.utils.datastructures import MultiValueDictKeyError
try:
is_private = request.POST['is_private']
except MultiValueDictKeyError:
is_private = False
You get that because you're trying to get a key from a dictionary when it's not there. You need to test if it is in there first.
try:
is_private = 'is_private' in request.POST
or
is_private = 'is_private' in request.POST and request.POST['is_private']
depending on the values you're using.
Another thing to remember is that request.POST['keyword']
refers to the element identified by the specified html name
attribute keyword
.
So, if your form is:
<form action="/login/" method="POST">
<input type="text" name="keyword" placeholder="Search query">
<input type="number" name="results" placeholder="Number of results">
</form>
then, request.POST['keyword']
and request.POST['results']
will contain the value of the input elements keyword
and results
, respectively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With