374👍
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>)
107👍
Choose what is best for you:
1
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.
2
if 'is_private' in request.POST:
is_private = request.POST['is_private']
else:
is_private = False
3
from django.utils.datastructures import MultiValueDictKeyError
try:
is_private = request.POST['is_private']
except MultiValueDictKeyError:
is_private = False
- [Django]-No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model
- [Django]-How can I get MINIO access and secret key?
- [Django]-Multiple annotate Sum terms yields inflated answer
14👍
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.
- [Django]-Django index page best/most common practice
- [Django]-How to get getting base_url in django template
- [Django]-Change a form value before validation in Django form
8👍
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.
- [Django]-Django 2.0 – Not a valid view function or pattern name (Customizing Auth views)
- [Django]-How can I keep test data after Django tests complete?
- [Django]-How to use MySQLdb with Python and Django in OSX 10.6?
5👍
Why didn’t you try to define is_private
in your models as default=False
?
class Foo(models.Models):
is_private = models.BooleanField(default=False)
- [Django]-Django, Models & Forms: replace "This field is required" message
- [Django]-What is related_name used for?
- [Django]-How to go from django image field to PIL image and back?
5👍
For me, this error occurred in my django project because of the following:
-
I inserted a new hyperlink in my home.html present in templates folder of my project as below:
<input type="button" value="About" onclick="location.href='{% url 'about' %}'">
-
In views.py, I had the following definitions of count and about:
def count(request):
fulltext = request.GET['fulltext']
wordlist = fulltext.split()
worddict = {}
for word in wordlist:
if word in worddict:
worddict[word] += 1
else:
worddict[word] = 1
worddict = sorted(worddict.items(), key = operator.itemgetter(1),reverse=True)
return render(request,'count.html', 'fulltext':fulltext,'count':len(wordlist),'worddict'::worddict})
def about(request):
return render(request,"about.html")
- In urls.py, I had the following url patterns:
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.homepage,name="home"),
path('eggs',views.eggs),
path('count/',views.count,name="count"),
path('about/',views.count,name="about"),
]
As can be seen in no. 3 above,in the last url pattern, I was incorrectly calling views.count whereas I needed to call views.about.
This line fulltext = request.GET['fulltext']
in count function (which was mistakenly called because of wrong entry in urlpatterns) of views.py threw the multivaluedictkeyerror exception.
Then I changed the last url pattern in urls.py to the correct one i.e. path('about/',views.about,name="about")
, and everything worked fine.
Apparently, in general a newbie programmer in django can make the mistake I made of wrongly calling another view function for a url, which might be expecting different set of parameters or passing different set of objects in its render call, rather than the intended behavior.
Hope this helps some newbie programmer to django.
- [Django]-Using django-rest-interface
- [Django]-Django: Record with max element
- [Django]-Multiple annotate Sum terms yields inflated answer
4👍
First check if the request object have the ‘is_private’ key parameter.
Most of the case’s this MultiValueDictKeyError occurred for missing
key in the dictionary-like request object. Because dictionary is an
unordered key, value pair “associative memories” or “associative
arrays”In another word. request.GET or request.POST is a dictionary-like
object containing all request parameters. This is specific to Django.The method get() returns a value for the given key if key is in the
dictionary. If key is not available then returns default value None.
You can handle this error by putting :
is_private = request.POST.get('is_private', False);
- [Django]-Django TypeError: get() got multiple values for keyword argument 'invoice_id'
- [Django]-Django Rest Framework Conditional Field on Serializer
- [Django]-Celery : Execute task after a specific time gap
1👍
1: use if request.POST in your function.
2: check html form method is equal .
def function_name(request):
if request.POST:
is_private = request.POST['is_private']
- [Django]-Using the reserved word "class" as field name in Django and Django REST Framework
- [Django]-Django – "Incorrect type. Expected pk value, received str" error
- [Django]-What's the difference between select_related and prefetch_related in Django ORM?
0👍
I got ‘MultiValueDictKeyError’ error while using ajax with Django. Just because of not putting ‘#’ while selecting an element. Like this.
data:{ name : $('id_name').val(),},
then I put the ‘#’ with the id and the problem is solved.
data:{ name : $('#id_name').val(),},
- [Django]-Why is factory_boy superior to using the ORM directly in tests?
- [Django]-Are sessions needed for python-social-auth
- [Django]-What is the use of PYTHONUNBUFFERED in docker file?
0👍
This will insert NULL value if the name is not present in the request
name = request.data.get('name')
- [Django]-Django simple_tag and setting context variables
- [Django]-Django: Error: You don't have permission to access that port
- [Django]-Django – Annotate multiple fields from a Subquery