dictionary update sequence element #0 has length 0; 2 is required - python

I was working on my project and everthing worked fine. I tried to open the server in another browser and this error appeared. I stopped the project and start it agian and it stop working on my main browser aswell. I dont have any idea what this cause it.
Internal Server Error: /account/login/
Traceback (most recent call last):
File "A:\repos\topanime\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "A:\repos\topanime\venv\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response
response = response.render()
File "A:\repos\topanime\venv\lib\site-packages\django\template\response.py", line 105, in render
self.content = self.rendered_content
File "A:\repos\topanime\venv\lib\site-packages\django\template\response.py", line 83, in rendered_content
return template.render(context, self._request)
File "A:\repos\topanime\venv\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
File "A:\repos\topanime\venv\lib\site-packages\django\template\base.py", line 168, in render
with context.bind_template(self):
File "C:\Python\Python391\lib\contextlib.py", line 117, in __enter__
return next(self.gen)
File "A:\repos\topanime\venv\lib\site-packages\django\template\context.py", line 244, in bind_template
updates.update(processor(self.request))
ValueError: dictionary update sequence element #0 has length 0; 2 is required
[18/Mar/2021 18:52:01] "GET /account/login/ HTTP/1.1" 500 86400
If there is any other information that you need tell me.

The problem was that I had a view in context_processors that required login #login_required. So I couldnt load any page because i wasnt logged in

If you use #login_required in context_processors:
The way I solved it was by replacing it with an if statment inside the context_processor.
def myCP(self, *args, **kwargs):
kontext = {}
if self.user.is_authenticated:
# The user is logged in
kontext['loggedIn'] = True
else:
# The user is logged out
kontext['loggedIn'] = False
return kontext

Related

Access cleaned data from django admin for pdf processing

As a newbie, I am currently trying to add a print button to every existing django admin view of a project.
The goal is to make it not depend on a single model I could resolve manually for printing but every existing model which contains foreign keys to other models an so on.
For simplicity I thought it would be the best to just get the cleaned_data of the form and process it for the pdf.
I alread added the print button, the path url and so on and it will create a pdf file for me.
What I am not able to do is to access the forms cleaned_data from my BaseAdmins (extends the ModelAdmin) class like this:
form = BaseForm(request.POST)
if form.is_valid():
data = form.cleaned_data
It will just give me random kinds of errors, like object has no attribute 'is_bound'
So I think that I am generally wrong with the context where I am trying to get the cleaned_data from the form. Every tutorial I found is just showing how to get the data but not fully resolved if it contains foreign keys and not in which context.
Could you please clear up for me where it would make sense to pass any kind of form data maybe as session data or post body to a print view where I can process it.
Thank you very much for reading, hope I was able to describe my problem, feel free to ask.
Edit
This is the BaseForm I changed variable names for internal reasons:
class BaseForm(ModelForm):
def clean_custom(self):
another_model = self.cleaned_data.get('AnotherModel')
custom_models = self.cleaned_data.get('CustomModel')
custom_models_allowed = CustomModel.objects.filter(AnotherModel=another_model)
custom_models_was_list = True
if not custom_models:
return
if not isinstance(custom_models, Iterable):
custom_models_was_list = False
custom_models = [custom_models]
for custom_model in custom_models:
if another_model and custom_model not in custom_models_allowed:
custom_models_allowed = [custom_model.titel for custom_model in custom_models_allowed]
custom_models_allowed = ', '.join(custom_models_allowed)
raise ValidationError(
f'{custom_model} is not part of {another_model}. For selection: {custom_models_allowed}'
)
if custom_models_was_list:
return custom_models
else:
return custom_models[0]
I'm trying to add cleaned_data in my BaseAdmin class where I have access to request and get the following trace:
AttributeError
AttributeError: type object 'CustomForm' has no attribute 'is_bound'
Traceback (most recent call last)
File ".../.env/lib/python3.9/site-packages/django/contrib/staticfiles/handlers.py", line 65, in __call__
return self.application(environ, start_response)
File ".../.env/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 141, in __call__
response = self.get_response(request)
File ".../.env/lib/python3.9/site-packages/django/core/handlers/base.py", line 75, in get_response
response = self._middleware_chain(request)
File ".../.env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 36, in inner
response = response_for_exception(request, exc)
File ".../.env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception
response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
File ".../.env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 125, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File ".../.env/lib/python3.9/site-packages/django_extensions/management/technical_response.py", line 40, in null_technical_500_response
raise exc_value.with_traceback(tb)
File ".../.env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File ".../.env/lib/python3.9/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File ".../.env/lib/python3.9/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File ".../.env/lib/python3.9/site-packages/django/contrib/admin/options.py", line 606, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File ".../.env/lib/python3.9/site-packages/django/utils/decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File ".../.env/lib/python3.9/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File ".../.env/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 223, in inner
return view(request, *args, **kwargs)
File ".../admin/base_admin.py", line 203, in change_view
if self.form.is_valid(self.form):
File ".../.env/lib/python3.9/site-packages/django/forms/forms.py", line 185, in is_valid
return self.is_bound and not self.errors
AttributeError: type object 'CustomForm' has no attribute 'is_bound'
This is not a standard question format, you are supposed to give us the code for the piece of code where the error occurs, (i.e. the base_admin.py file) but what you have provided is just 3 lines of it.
But so far I can see you are not checking whether the request is of the type of post or not. Pay attention to the if condition at the beginning of the method
def edit(request):
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = PurposeForm(request.POST)
# check whether it's valid:
if form.is_valid():
for key, value in form.cleaned_data.items():
# etc

How to pass json to render_to_response

I am trying to pass a json file through render_to_response to the front end. The front end is not a django template, its coded in JS, HTML etc. I am getting some weird error. Can anybody help me with that. I am attaching the code and the traceback.
return render_to_response('ModelView.html', json.dumps(newDict))
Traceback (most recent call last):
File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
response = get_response(request)
File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\PythonWorkspace\ScApp\ScApp2\views.py", line 78, in ScorecardApp20
return render_to_response('ModelView.html', json.dumps(newDict))
File "C:\Users\kxc89\AppData\Local\Programs\Python\Python37\lib\site-packages\django\shortcuts.py", line 27, in render_to_response
content = loader.render_to_string(template_name, context, using=using)
File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\backends\django.py", line 59, in render
context = make_context(context, request, autoescape=self.backend.engine.autoescape)
File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\context.py", line 274, in make_context
raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__)
TypeError: context must be a dict rather than str.
Don’t use render_to_response, it’s obsolete. Use render instead.
return render(request, 'ModelView.html', {'new_dict': json.dumps(newDict)})
The third argument has to be a dictionary, so you can either add the json string to the dictionary as I have done above, or perhaps you don’t want to use json.dumps() at all and just use newDict.
Use the code below
import json
data = open('/static/JsonFile.json').read() #opens the json file and saves the raw contents
JsonData = json.dumps(data) #converts to a json structure
context = {'obj': JsonData}
return render(request, 'templates', context)
Hope it should work !

django allauth social authentication retrieved email matches an existing user's email?

This is my first post in Stack exchange, I am Python and Django Noob trying to develop an application. The application uses django-registration for user registration and then I started plugging in 'social' authentication. I chose allauth as it has the ability to perform authentication among'st other things.
I have hit the same problem that was presented in this thread: django allauth facebook redirects to signup when retrieved email matches an existing user's email?
user login/signup failing if the user with same email address already exists in the database(due to registration with local registration path). I tried the solution provided in the above post and have issues. Looking for some help and advise here.
I have exactly the same code as above in my socialadapter.py under the following path
myproject/allauth/socialaccount/socialadapter.py
I have the following in my settings
LOGIN_URL = '/'
#LOGIN_REDIRECT_URL = '/'
LOGIN_REDIRECT_URL = "/users/{id}/mytags"
SOCIALACCOUNT_QUERY_EMAIL = True
ACCOUNT_AUTHENTICATION_METHOD='username_email'
SOCIALACCOUNT_EMAIL_REQUIRED = False
#create and use specific adapter to handle the issue reported here
# https://github.com/pennersr/django-allauth/issues/418
ACCOUNT_ADAPTER = "myproject.allauth.socialaccount.MyLoginAccountAdapter"
SOCIALACCOUNT_ADAPTER = 'myproject.allauth.socialaccount.MySocialAccountAdapter'
On starting the runserver and accessing the facebook/login , I see the following issue
[17/Jul/2014 11:49:43] "GET /myproject/accounts2/facebook/login/ HTTP/1.1" 500 59
---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 58805) Traceback (most recent call last): File "C:\Python27\Lib\SocketServer.py", line 593, in process_request_thread
self.finish_request(request, client_address) File "C:\Python27\Lib\SocketServer.py", line 334, in finish_request
self.RequestHandlerClass(request, client_address, self) File "C:\Python27\lib\site-packages\django\core\servers\basehttp.py", line 139, in __init__
super(WSGIRequestHandler, self).__init__(*args, **kwargs) File "C:\Python27\Lib\SocketServer.py", line 651, in __init__
self.finish() File "C:\Python27\Lib\SocketServer.py", line 710, in finish
self.wfile.close() File "C:\Python27\Lib\socket.py", line 279, in close
self.flush() File "C:\Python27\Lib\socket.py", line 303, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size]) error: [Errno 10053] An established connection was aborted by the software in your host machine
---------------------------------------- ERROR:django.request:Internal Server Error: /myproject/accounts2/facebook/login/callback/ Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 109, in get_response
response = callback(request, *callback_args, **callback_kwargs) File "myproject\allauth\socialaccount\providers\oauth2\views.py", line 51, in view
return self.dispatch(request, *args, **kwargs) File "myproject\allauth\socialaccount\providers\oauth2\views.py", line 98, in dispatch
response=access_token) File "myproject\allauth\socialaccount\providers\facebook\views.py", line 43, in complete_login
return fb_complete_login(request, app, access_token) File "myproject\allauth\socialaccount\providers\facebook\views.py", line 31, in fb_complete_login
.sociallogin_from_response(request, extra_data) File "myproject\allauth\socialaccount\providers\base.py", line 44, in sociallogin_from_response
adapter = get_adapter() File "myproject\allauth\socialaccount\adapter.py", line 150, in get_adapter
return import_attribute(app_settings.ADAPTER)() File "myproject\allauth\utils.py", line 97, in import_attribute
ret = getattr(importlib.import_module(pkg), attr) AttributeError: 'module' object has no attribute 'MySocialAccountAdapter' [17/Jul/2014 11:49:46] "GET /myproject/accounts2/facebook/login/callback/?code=AQBShGWTHnGVvlo-fOVW7xjF9RUJo-k7P23zISHC70p aAR5uWYpnI46gpHFUCC5Rz-SviDyTITVRAUkZ-DhkZaHyBT2n5UBhhSwkACgCKTTgPrFLAZFBQs05AEZ67xfk-wRlF47DSjT26bbDdUmc1ptfFxP3W4qS5Y6b5Yrj iLTI3RMScOEM0EKUQjNySyj4XSAVk6wj4HcAbCVxiVv5QaH63ayxyt5Y5jQ0AOH3zsCngPaqFNJArXseMS6wfqSc8yDwcwWZKo1nGhcNtA9Gy_bqZNiTZSjPJguhT lBwbmDAJ9SUNI8AS3yzC-AKDtD2_bo&state=441rn77wUuLH HTTP/1.1" 500 147978
Initially the socialadapter.py would not even compile,all others did compile even after deleting the .pyc
I referred to this thread: pycompile for python3.2
and force compile but I still see the issue
Any suggestions on what I might be doing wrong here is greatly appreciated.
thank you for your valuable time.
-km
EDIT:
Environment
Python 2.7.5
allauth: 0.17
Ok I figured out the issue , I had the settings entry for my adapter missing a the full path to the class. Now I am able to login using Facebook.
However I have another issue, I am trying to enable Linked in login for the same app and have the following entries in the settings
SOCIALACCOUNT_PROVIDERS = \
{'linkedin':{'SCOPE': [ 'r_emailaddress',
'r_fullprofile',
'r_emailaddress',
'r_contactinfo',
'r_network'],
'PROFILE_FIELDS':
[
'id',
'first-name',
'last-name',
'email-address',
'picture-url',
'public-profile-url',
'skills',
'headline',
'industry',
'num-connections',
'positions',
'interests',
'languages',
'certifications',
'educations',
'courses',
'three-current-positions',
'three-past-positions',
'recommendations-received',
'honors-awards'
]
},
'facebook': {'SCOPE': ['email', 'user_about_me', 'user_birthday',
'user_education_history','user_work_history',
'user_hometown',
'user_location',
'user_religion_politics','user_subscriptions',
'read_stream',
'read_insights',
'read_friendlists',
'user_likes',
'user_interests',
'user_groups'
],
'AUTH_PARAMS': {},
'METHOD': 'oauth2'
},
}
Now When I use the login page, I get the following error
[17/Jul/2014 22:26:28] "GET /myproject/accounts2/linkedin/login/?process=connect HTTP/1.1" 302 0
ERROR:django.request:Internal Server Error: /myproject/accounts2/linkedin/login/callback/
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 109, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "myproject\allauth\socialaccount\providers\oauth\views.py", line 35, in view
return self.dispatch(request, *args, **kwargs)
File "myproject\allauth\socialaccount\providers\oauth\views.py", line 90, in dispatch
return complete_social_login(request, login)
File "myproject\allauth\socialaccount\helpers.py", line 113, in complete_social_login
sociallogin=sociallogin)
File "C:\Python27\lib\site-packages\django\dispatch\dispatcher.py", line 172, in send
response = receiver(signal=self, sender=sender, **named)
File "myproject\allauth\socialaccount\socialadapter.py", line 50, in link_to_local_user
email_address = sociallogin.account.extra_data['email']
KeyError: 'email'
[17/Jul/2014 22:26:50] "GET /myproject/accounts2/linkedin/login/callback/?oauth_token=77--d223fb8b-168f-4260-b93c-1a6e5ff2
e1e1&oauth_verifier=52724 HTTP/1.1" 500 139897
I am not sure how to fix this because the SCOPE for LinkedIn has : 'email-address', how can I fix this issue as the Email Fields in LinkedIn Documentation also says email-address
LinkedIn fields
Any suggestions are appreciated.
I am sorry I do not know how to put a bounty on the question and I do not have enough to place for the question also.
TIA
-km

Why do I get "AttributeError: 'unicode' object has no attribute 'user' " on some specify url only?

I'm using the #login_required decorator in my project since day one and it's working fine, but for some reason, I'm starting to get "
AttributeError: 'unicode' object has no attribute 'user' " on some specific urls (and those worked in the past).
Example : I am the website, logged, and then I click on link and I'm getting this error that usually is linked to the fact that there is no SessionMiddleware installed. But in my case, there is one since I am logged on the site and the page I am on also had a #login_required.
Any idea?
The url is definied as : (r'^accept/(?P<token>[a-zA-Z0-9_-]+)?$', 'accept'),
and the method as : #login_required
def accept(request,token): ...
The Traceback:
Traceback (most recent call last):
File "/Users/macbook/virtualenv/proj/lib/python2.6/site-packages/django/core/servers/basehttp.py", line 674, in __call__
return self.application(environ, start_response)
File "/Users/macbook/virtualenv/proj/lib/python2.6/site-packages/django/core/handlers/wsgi.py", line 241, in __call__
response = self.get_response(request)
File "/Users/macbook/virtualenv/proj/lib/python2.6/site-packages/django/core/handlers/base.py", line 141, in get_response
return self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "/Users/macbook/virtualenv/proj/lib/python2.6/site-packages/django/core/handlers/base.py", line 165, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "/Users/macbook/virtualenv/proj/lib/python2.6/site-packages/django/core/handlers/base.py", line 100, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/Users/macbook/virtualenv/proj/lib/python2.6/site-packages/django/contrib/auth/decorators.py", line 25, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/Users/macbook/dev/pycharm-projects/proj/match/views.py", line 33, in accept
return __process(token,callback)
File "/Users/macbook/virtualenv/proj/lib/python2.6/site-packages/django/contrib/auth/decorators.py", line 24, in _wrapped_view
if test_func(request.user):
AttributeError: 'unicode' object has no attribute 'user'`
The decorator was on a private method that doesn't have the request as a parameter. I removed that decorator (left there because of a refactoring and lack of test [bad me]).
Problem solved.
This can also happen if you call a decorated method from another method without providing a request parameter.

TemplateSyntaxError: 'settings_tags' is not a valid tag library

i got this error when i try to run this test case: WHICH IS written in tests.py of my django application:
def test_accounts_register( self ):
self.url = 'http://royalflag.com.pk/accounts/register/'
self.c = Client()
self.values = {
'email': 'bilal#gmail.com',
'first_name': 'bilal',
'last_name': 'bash',
'password1': 'bilal',
'password2': 'bilal',
}
self.response = self.c.post( self.url, self.values )
my django version is 1.2.1 and python 2.6 and satchmo version is 0.9.2-pre hg-unknown
the complete error log is:
.E....
======================================================================
ERROR: test_accounts_register (administration.tests.AccountsRegisterTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\pytho\satchmo\administration\tests.py", line 53, in test_accounts_reg
ister
self.response = self.c.get( self.url )
File "C:\django\django\test\client.py", line 290, in get
response = self.request(**r)
File "C:\django\django\test\client.py", line 230, in request
response = self.handler(environ)
File "C:\django\django\test\client.py", line 74, in __call__
response = self.get_response(request)
File "C:\django\django\core\handlers\base.py", line 141, in get_response
return self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "C:\django\django\core\handlers\base.py", line 180, in handle_uncaught_ex
ception
return callback(request, **param_dict)
File "C:\django\django\views\defaults.py", line 23, in server_error
t = loader.get_template(template_name) # You need to create a 500.html templ
ate.
File "C:\django\django\template\loader.py", line 157, in get_template
template, origin = find_template(template_name)
File "C:\django\django\template\loader.py", line 134, in find_template
source, display_name = loader(name, dirs)
File "C:\django\django\template\loader.py", line 42, in __call__
return self.load_template(template_name, template_dirs)
File "C:\django\django\template\loader.py", line 48, in load_template
template = get_template_from_string(source, origin, template_name)
File "C:\django\django\template\loader.py", line 168, in get_template_from_str
ing
return Template(source, origin, name)
File "C:\django\django\template\__init__.py", line 158, in __init__
self.nodelist = compile_string(template_string, origin)
File "C:\django\django\template\__init__.py", line 186, in compile_string
return parser.parse()
File "C:\django\django\template\__init__.py", line 282, in parse
compiled_result = compile_func(self, token)
File "C:\django\django\template\defaulttags.py", line 921, in load
(taglib, e))
TemplateSyntaxError: 'settings_tags' is not a valid tag library: Template librar
y settings_tags not found, tried django.templatetags.settings_tags,satchmo_store
.shop.templatetags.settings_tags,django.contrib.admin.templatetags.settings_tags
,django.contrib.comments.templatetags.settings_tags,django.contrib.humanize.temp
latetags.settings_tags,livesettings.templatetags.settings_tags,sorl.thumbnail.te
mplatetags.settings_tags,satchmo_store.contact.templatetags.settings_tags,tax.te
mplatetags.settings_tags,pagination.templatetags.settings_tags,product.templatet
ags.settings_tags,payment.templatetags.settings_tags,payment.modules.giftcertifi
cate.templatetags.settings_tags,satchmo_utils.templatetags.settings_tags,app_plu
gins.templatetags.settings_tags,tinymce.templatetags.settings_tags
----------------------------------------------------------------------
Ran 6 tests in 47.468s
FAILED (errors=1)
Destroying test database 'default'...
It seems to me you probably have a code like {% load settings_tags %} somewhere in your template. Django looks for templatetags/settings_tags.py file in your installed apps' directories. This is the result of not finding a file like this. Maybe the app, which contains it is not in your INSTALLED_APPS or maybe it's a typo. You should be getting the same error when you put this url in your browser.
Sometimes this happens when you forgot to put an __ init __.py in the package.
Like #AJJ said, you may have to restart the server to get the new tags loaded
This is a common issue for this package. When you get it from pypi, it does not contains the template tag: settings_tag.py and that will cause the error 'settings_tags' is not a valid tag library: Template library settings_tags not found.
The current solution is to install it from the github zip.

Categories

Resources