519π
Just ran into this problem. I donβt know if itβs the same thing that hit your code, but for me the root cause was because I forgot to put name=
on the last argument of the url
(or path
in Django 2.0+) function call.
For instance, the following functions throw the error from the question:
url(r'^foo/(?P<bar>[A-Za-z]+)/$', views.FooBar.as_view(), 'foo')
path('foo/{slug:bar}/', views.FooBar, 'foo')
But these actually work:
url(r'^foo/(?P<bar>[A-Za-z]+)/$', views.FooBar.as_view(), name='foo')
path('foo/{slug:bar}/', views.FooBar, name='foo')
The reason why the traceback is unhelpful is because internally, Django wants to parse the given positional argument as the keyword argument kwargs
, and since a string is an iterable, an atypical code path begins to unfold. Always use name=
on your urls!
104π
I got this error when I was messing around with string and dictionary.
dict1 = {'taras': 'vaskiv', 'iruna': 'vaskiv'}
str1 = str(dict1)
dict(str1)
*** ValueError: dictionary update sequence element #0 has length 1; 2 is required
So what you actually got to do to get dict from string is:
dic2 = eval(str1)
dic2
{'taras': 'vaskiv', 'iruna': 'vaskiv'}
Or in matter of security we can use literal_eval
from ast import literal_eval
- [Django]-Alowing 'fuzzy' translations in django pages?
- [Django]-Django: Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found
- [Django]-DRF: custom ordering on related serializers
33π
Error in your question is raised when you try something like following:
>>> a_dictionary = {}
>>> a_dictionary.update([[1]])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required
Itβs hard to tell where is the cause in your code unless you show your code, full traceback.
- [Django]-Using django-admin on windows powershell
- [Django]-Django: manage.py does not print stack trace for errors
- [Django]-Django: Multiple forms possible when using FormView?
19π
I faced the above mentioned problem when I forgot to pass a keyword argument name to url() function.
Code with error
url(r"^testing/$", views.testing, "testing")
Code without error
url(r"^testing/$", views.testing, name="testing")
So finally I removed the above error in this way. It might be something different in your case. So check your url patterns in urls.py.
- [Django]-Using Cloudfront with Django S3Boto
- [Django]-How to change User representation in Django Admin when used as Foreign Key?
- [Django]-Cannot access django app through ip address while accessing it through localhost
17π
Here is how I encountered this error in Django and fixed it:
Code with error
urlpatterns = [path('home/', views.home, 'home'),]
Correction
urlpatterns = [path('home/', views.home, name='home'),]
- [Django]-Django: Using F arguments in datetime.timedelta inside a query
- [Django]-In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?
- [Django]-Warning: Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'
10π
Here is the reproduced error.
>>> d = {}
>>> d.update([(1,)])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required
>>>
>>> d
{}
>>>
>>> d.update([(1, 2)])
>>> d
{1: 2}
>>>
>>> d.update('hello_some_string')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required
>>>
If you give the sequence and any element length is 1 and required two then we will get this kind of error.
See the above code. First time I gave the sequence with tuple and itβs length 1, then we got the error and dictionary is not updated. second time I gave inside tuple with with two elements, dictionary got updated.
- [Django]-What's the purpose of Django setting βSECRET_KEYβ?
- [Django]-Group by Foreign Key and show related items β Django
- [Django]-Timestamp fields in django
10π
SolutionΒ»
Pass a keyword argument name with value as your view name e.g home
or home-view
etc. to url()
function.
Throws ErrorΒ»
url(r'^home$', 'common.views.view1', 'home'),
CorrectΒ»
url(r'^home$', 'common.views.view1', name='home'),
- [Django]-How can I see the raw SQL queries Django is running?
- [Django]-Django-allauth: Linking multiple social accounts to a single user
- [Django]-How to add superuser in Django from fixture
4π
I got the same issue and found that it was due to wrong parameters.
In views.py
, I used:
return render(request, 'demo.html',{'items', items})
But I found the issue: {'items', items}
. Changing to {'items': items}
resolved the issue.
- [Django]-Get the list of checkbox post in django views
- [Django]-How to upload a file in Django?
- [Django]-Does django with mongodb make migrations a thing of the past?
3π
Another scenario that causes this error:
dict('{"a":1}') # gives the error
One way to achieve what you want is to use eval
eval('{"a":1}') # gives {"a":1}
- [Django]-Django Cannot set values on a ManyToManyField which specifies an intermediary model. Use Manager instead
- [Django]-Django middleware difference between process_request and process_view
- [Django]-How to add new languages into Django? My language "Uyghur" or "Uighur" is not supported in Django
- [Django]-How do I get the class of a object within a Django template?
- [Django]-Using Cloudfront with Django S3Boto
- [Django]-RuntimeWarning: DateTimeField received a naive datetime
3π
I had the same problem and it turned out that missing βnameβ in the urls.py was the cause of problem.
- [Django]-Python Socket.IO client for sending broadcast messages to TornadIO2 server
- [Django]-How to mix queryset results?
- [Django]-Django order_by query set, ascending and descending
2π
In my case, my get_context_data
in one of my views was returning return render(self.request, 'es_connection_error.html', {'error':error});
in a try/catch block instead of returning context
- [Django]-Why does Django's render() function need the "request" argument?
- [Django]-No handlers could be found for logger
- [Django]-"<Message: title>" needs to have a value for field "id" before this many-to-many relationship can be used.
2π
The error should be with the params. Please verify that the params is a dictionary object. If it is just a list/tuple of arguments use only one * (*params
) instead of two * (**params
). This will explode the list/tuple into the proper amount of arguments.
Or, if the params is coming from some other part of code as a JSON file, please do json.loads(params)
, because the JSON objects sometimes behave as string and so you need to make it as a JSON using load from string (loads).
super(HStoreDictionary, self).__init__(value, **params)
Hope this helps!
- [Django]-Is there a way to filter a queryset in the django admin?
- [Django]-Django Installed Apps Location
- [Django]-What's the difference between CharField and TextField in Django?
2π
check in your dictionary whether if you have single or double Quotation mark in your key or value!
dict1 = {'hello': 'world', 'programmer's': 'have girlfriend'}
to resolve it you can simply convert your dictionary in to string and then use replace method!
- [Django]-How do I POST with jQuery/Ajax in Django?
- [Django]-Django Template Language: Using a for loop with else
- [Django]-Github issues api 401, why? (django)
2π
I faced this problem when I was trying to convert json string to dict.
Input: '{\r\n "resource_id": "id",\r\n "resource_type": "resource"\r\n}'
Using dict()
to convert the string to dict
gave me this error. The correct way would be to use json
module.
Example: json.loads(input_str)
- [Django]-Where is a good place to work on accounts/profile in Django with the Django registration app?
- [Django]-The QuerySet value for an exact lookup must be limited to one result using slicing. Filter error
- [Django]-How to change User representation in Django Admin when used as Foreign Key?
1π
I encountered this issue when trying to invoke the update method with a parameter of a wrong type.
The expected dict was:
{'foo': True}
The one that was passed was:
{'foo': "True"}
make sure you check all the parameters you pass are of the expected type.
- [Django]-Remove pk field from django serialized objects
- [Django]-Migrating Django fixtures?
- [Django]-How do I run tests against a Django data migration?
1π
I too had a similar type of problem . The solution is simple . just dont try to enter NULL or None value in values or u might have to use Something like thisdic.update([(key,value)])
- [Django]-How to get GET request values in Django?
- [Django]-How to query as GROUP BY in Django?
- [Django]-Django index page best/most common practice
1π
I hit this error calling:
dict(my_data)
I fixed this with:
import json
json.loads(my_data)
- [Django]-Choose test database?
- [Django]-Django 1.7 β App 'your_app_name' does not have migrations
- [Django]-How to pass django rest framework response to html?
0π
You are sending one parameter incorrectly; it should be a dictionary object
:
-
Wrong:
func(a=r)
-
Correct:
func(a={'x':y})
- [Django]-Nginx doesn't serve static
- [Django]-CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true
- [Django]-Django: Get list of model fields?
0π
This behavior will also occurs when using get_or_create
method in the following example below one will obviously get that error:
state,_ = Status.objects.get_or_create('Pending')
To resolve this you will add the the respective key and value.
i.e like this state,_ = Status.objects.get_or_create(name='Pending')
- [Django]-Django REST Framework: how to substitute null with empty string?
- [Django]-Error: could not determine PostgreSQL version from '10.3' β Django on Heroku
- [Django]-Django QuerySet order
0π
Please check your URL path I fixed this issue by changing the URL.
path(βreset_password_email/β, requestpasswordresetemail, "request-rest-email")
Instead of use
path(βreset_password_email/β, requestpasswordresetemail, name="request-rest-email")
- [Django]-What's the best solution for OpenID with Django?
- [Django]-Form with CheckboxSelectMultiple doesn't validate
- [Django]-Getting the SQL from a Django QuerySet
0π
I was getting this issue so this is how I solved it ( by doing an eval and strip )
aggr = {}
with open("output.txt", "r") as f:
for line in f.readlines():
for k, v in dict(eval(line.strip())).items():
aggr.setdefault(k, 0)
aggr[k] = aggr[k] + v
print(aggr)
print(aggr)
The data I was reading was a text file with a dictionary objects
{'unknown': 298, 'a4a815d631c805ccd10dd2f1548baa57': 9724, '22b5a0ff959ce0b4036716cc0c2df68b': 1341, 'd186fde596dffaab46260765c7fcba61': 2052}
{'unknown': 323, '49e5357782510659cf083356f7d2a1ab': 9826, 'a4a815d631c805ccd10dd2f1548baa57': 9812, 'b615930608b8dcd217de7904d4463efb': 2409}
- [Django]-How to implement FirebaseDB with a Django Web Application
- [Django]-Programmatically saving image to Django ImageField
- [Django]-Django Cannot set values on a ManyToManyField which specifies an intermediary model. Use Manager instead
0π
from ast import literal_eval
c = "{'taras': 'vaskiv', 'iruna': 'vaskiv'}"
c= dict(literal_eval(c))
- [Django]-Django set default form values
- [Django]-Django TypeError: get() got multiple values for keyword argument 'invoice_id'
- [Django]-How do I run tests for all my Django apps only?
0π
I got this error when I was messing around with string and dictionary.
dict1 = {'taras': 'vaskiv', 'iruna': 'vaskiv'}
str1 = str(dict1)
dict(str1)
or to be specific
query_result = req_db_session.query(app_config_model.APPCONFIG).with_entities(app_config_model.APPCONFIG.value).filter(app_config_model.APPCONFIG.name == 'test_me').first()
print(query_result, type(query_result))
print('--------------------------')
print(type(query_result))
# prints <class 'sqlalchemy.util._collections.result'>
print(dict(query_result))
# throws error
*** ValueError: dictionary update sequence element #0 has length 1; 2 is required
So what you actually worked was:
query_result = req_db_session.query(app_config_model.APPCONFIG).with_entities(app_config_model.APPCONFIG.value).filter(app_config_model.APPCONFIG.name == 'test_me').first()
print(query_result, type(query_result))
print('--------------------------')
print(type(query_result.value))
# prints <type 'unicode'>
print(json.loads(query_result.value))
# prints parsed dictionary
- [Django]-How to force application version on AWS Elastic Beanstalk
- [Django]-Is it bad to have my virtualenv directory inside my git repository?
- [Django]-Django Model() vs Model.objects.create()