user_change_password() got an unexpected keyword argument 'extra_context' - django

Django 3.0.7
When I try to change password in admin site, I get
TypeError at /admin/auth/user/1/password/
user_change_password() got an unexpected keyword argument 'extra_context'
Namely I pressed "this form" link:
More details
Environment:
Request Method: GET
Request URL: http://localhost:8000/admin/auth/user/1/password/
Django Version: 3.0.7
Python Version: 3.8.0
Installed Applications:
['admin_aux',
'images.apps.ImagesConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'posts',
'sidebars',
'general',
'categories',
'marketing',
'home',
'authors',
'taggit',
'cachalot',
'django_cleanup.apps.CleanupConfig',
'widgets',
'code_samples',
'hyper_links',
'polls',
'applications',
'videos',
'quotations',
'languages',
'people',
'arbitrary_htmls.apps.ArbitraryHtmlsConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 231, in inner
return view(request, *args, **kwargs)
File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/views/decorators/debug.py", line 76, in sensitive_post_parameters_wrapper
return view(request, *args, **kwargs)
Exception Type: TypeError at /admin/auth/user/1/password/
Exception Value: user_change_password() got an unexpected keyword argument 'extra_context'
How can I localize this problem?

What's happening...
I have no idea tbh. It is worth noting a few things though, that the url, should call a method in the User Auth ModelAdmin at django/contrib/auth/admin called user_change_password. It has the following signature:
def user_change_password(self, request, id, form_url=""):
which is why the error is being raised, because somehow extra_context is being passed to it.
There is also a way for you to change the logged on users password, which does accept a extra_context kwarg. My best guess is that one of the apps has overwritten the standard auth ModelAdmin and done it not quite right. Certainly everything works fine with a fresh django 3.0.7 project.
How can I localize this problem?
I would remove all of your additional apps. Hopefully this will fix the problem. If it doesn't then this becomes more interesting. But if it does, I would add them back in one by one until it breaks, and then you'll figure out which additional app is breaking things.
maybe you even can help me cope with it.
There's a few things I can think of that you could do if you just want to change the password. You can change user details via the shell:
python manage.py shell
Then the following will enable you to change a password:
from auth.models import User
user = User.objects.get(id=1) # Or whatever user you want
user.set_password('my_new_password')
user.save()
This should do the trick. Even easier still, there is a management command that does it (but for this you will need to know the current password). You can simply run:
manage.py changepassword *username*

I had this issue (though in Django 2.2). It started after I took the advice from another Stack Overflow post on adding extra_context to every admin page. This seems harmless, but breaks the "change password" form. In the end I deleted the 'extra_context' changes to urls.py and added the extra_context ONLY to the admin forms I needed using the ModelAdmin add_view and change_view methods.
# New Layer Form
def add_view(self, request, form_url='', extra_context={}):
extra_context['CATALOG_TECHNOLOGY'] = settings.CATALOG_TECHNOLOGY
return super(LayerAdmin, self).add_view(request, form_url, extra_context)
# Edit Layer Form
def change_view(self, request, object_id, extra_context={}):
extra_context['CATALOG_TECHNOLOGY'] = settings.CATALOG_TECHNOLOGY
return super(LayerAdmin, self).change_view(request, object_id, extra_context=extra_context)
Here are the commits for full context:
Breaking Commit
urls.py
Fixing Commits
urls.py
admin.py

Related

How to fix social_core.exceptions.AuthMissingParameter error

I am trying to implement a google login onto my project. I already had a relatively working login scheme when I tried to use social_core's oauth with google to log in with a google account. It keeps throwing a social_core.exceptions.AuthMissingParameter error, meaning that somehow, the state isn't being passed at all.
I have been following the walkthrough done here https://fosstack.com/how-to-add-google-authentication-in-django/ as a baseline for how to implement this. When I run the code from this tutorial (besides some basic syntax and version errors), everything runs like a charm. However, when I try to implement it on my project, an error I cannot resolve occurs.
The url.py file I have, I have only imported some files and added the line
path('auth/', include('social_django.urls', namespace='social')),
Other, than that, most of my test code is similar to the blog: like this in my common file.
AUTHENTICATION_BACKENDS = (
'social_core.backends.open_id.OpenIdAuth', # for Google authentication
'social_core.backends.google.GoogleOpenId', # for Google authentication
'social_core.backends.google.GoogleOAuth2', # for Google authentication
'django.contrib.auth.backends.ModelBackend',
)
How the current situation is, is that I can click login, it takes me to a login page where I type in my google account, and then it throws the following exception:
Environment:
Request Method: GET
Request URL: http://localhost:3000/auth/complete/google-oauth2/
Django Version: 2.1.7
Python Version: 3.6.5
Installed Applications:
[##Some personal files###
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'markdownx',
'social_django',
'livereload']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Users\Daniel\.virtualenvs\project-djMFGD5K\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\Daniel\.virtualenvs\project-djMFGD5K\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "C:\Users\Daniel\.virtualenvs\project-djMFGD5K\lib\site-packages\django\core\handlers\base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Daniel\.virtualenvs\project-djMFGD5K\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File "C:\Users\Daniel\.virtualenvs\project-djMFGD5K\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "C:\Users\Daniel\.virtualenvs\project-djMFGD5K\lib\site-packages\social_django\utils.py" in wrapper
49. return func(request, backend, *args, **kwargs)
File "C:\Users\Daniel\.virtualenvs\project-djMFGD5K\lib\site-packages\social_django\views.py" in complete
33. *args, **kwargs)
File "C:\Users\Daniel\.virtualenvs\project-djMFGD5K\lib\site-packages\social_core\actions.py" in do_complete
43. user = backend.complete(user=user, *args, **kwargs)
File "C:\Users\Daniel\.virtualenvs\project-djMFGD5K\lib\site-packages\social_core\backends\base.py" in complete
40. return self.auth_complete(*args, **kwargs)
File "C:\Users\Daniel\.virtualenvs\project-djMFGD5K\lib\site-packages\social_core\utils.py" in wrapper
259. return func(*args, **kwargs)
File "C:\Users\Daniel\.virtualenvs\project-djMFGD5K\lib\site-packages\social_core\backends\oauth.py" in auth_complete
388. state = self.validate_state()
File "C:\Users\Daniel\.virtualenvs\project-djMFGD5K\lib\site-packages\social_core\backends\oauth.py" in validate_state
88. raise AuthMissingParameter(self, 'state')
Exception Type: AuthMissingParameter at /auth/complete/google-oauth2/
Exception Value: Missing needed parameter state
Where I have edited out some of the more personal information, but those files aren't being used currently. I am pretty sure I have my keys done correctly, because the parameters are correct when I print them in the terminal after I run the server, and for the fact that google manages to send me the redirect at all.
Edit: Pretty sure the keys are correct, since when I remove them or type them incorrectly, I get a server not found error rather than a missing parameter error.

MultiValueDictKeyError when deleting related inline records in another tab

I'll try to be as concise as possible.
Background
I have a model Person which has a ForeignKey to model Document. Each Person can only have one Document but, as you may already know, each Document can be linked to many Persons.
In the Document's Admin form I have the Persons associated to the Document displayed inline. I can edit, add or delete the Persons right there.
Problem
Following these steps I get the error:
I open the Admin edit form for a Document. Let's call it Document
A. This Document has two Persons associated, let's call them John
Doe and Jane Doe. You can see them there (inline) in the form and
the fields are editable, but I don't touch them.
I open another tab and go straight to the Persons list and delete
Jane Doe.
I get back to the first tab (the Document's edit form) and click on
"Save and continue editing".
The form is sent and I get a generic error at the top (something
like) "Please, fix the following errors". But the form shows no
errors (next to the fields) to correct and, obviously, the record
for Jane Doe isn't displayed.
I click again on "Save and continue editing" and when the form is
sent I get the error "MultiValueDictKeyError: "u'person_set-1-id'"".
Ideal solution
I'd like to be able to display a custom error in the middle stage (when the first error appears, after the first save), saying something like "A person associated with this Document was deleted while you were editing it". Also, preventing the final error is highly desirable.
Error dump
MultiValueDictKeyError at /admin/persons/document/1145/
"u'person_set-1-id'"
Request Method: POST
Request URL: http://localhost:8000/admin/persons/document/1145/
Django Version: 1.7.7
Exception Type: MultiValueDictKeyError
Exception Value:
"u'person_set-1-id'"
Exception Location: /__PATH__/local/lib/python2.7/site-packages/django/utils/datastructures.py in __getitem__, line 319
Python Executable: /__PATH__/bin/python
Python Version: 2.7.15
Python Path:
['/__PATH__/test/test/apps',
'/__PATH__/test',
'/__PATH__/lib/python2.7',
'/__PATH__/lib/python2.7/plat-x86_64-linux-gnu',
'/__PATH__/lib/python2.7/lib-tk',
'/__PATH__/lib/python2.7/lib-old',
'/__PATH__/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/__PATH__/local/lib/python2.7/site-packages',
'/__PATH__/src/django-smart-selects',
'/__PATH__/lib/python2.7/site-packages',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/test']
Server time: Mar, 29 Ene 2019 11:52:18 -0300
Environment:
Request Method: POST
Request URL: http://localhost:8000/admin/persons/document/1145/
Django Version: 1.7.7
Python Version: 2.7.15
Installed Applications:
('salmonella',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'crispy_forms',
'test.apps.persons',
'captcha',
'django_countries',
'django_extensions',
'import_export',
'django_object_actions',
'widget_tweaks',
'smart_selects',
'daterange_filter',
'compressor',
'auditlog')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'auditlog.middleware.AuditlogMiddleware')
Traceback:
File "/__PATH__/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper
583. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
105. response = view_func(request, *args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
52. response = view_func(request, *args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
206. return view(request, *args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in change_view
1456. return self.changeform_view(request, object_id, form_url, extra_context)
File "/__PATH__/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
29. return bound_func(*args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
105. response = view_func(request, *args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
25. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/__PATH__/local/lib/python2.7/site-packages/django/db/transaction.py" in inner
394. return func(*args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in changeform_view
1403. if all_valid(formsets) and form_validated:
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/formsets.py" in all_valid
438. if not formset.is_valid():
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/formsets.py" in is_valid
303. self.errors
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/formsets.py" in errors
277. self.full_clean()
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/formsets.py" in full_clean
325. form = self.forms[i]
File "/__PATH__/local/lib/python2.7/site-packages/django/utils/functional.py" in __get__
55. res = instance.__dict__[self.func.__name__] = self.func(instance)
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/formsets.py" in forms
141. forms = [self._construct_form(i) for i in xrange(self.total_form_count())]
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/models.py" in _construct_form
868. form = super(BaseInlineFormSet, self)._construct_form(i, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/models.py" in _construct_form
581. pk = self.data[pk_key]
File "/__PATH__/local/lib/python2.7/site-packages/django/utils/datastructures.py" in __getitem__
319. raise MultiValueDictKeyError(repr(key))
Exception Type: MultiValueDictKeyError at /admin/persons/document/1145/
Exception Value: "u'person_set-1-id'"
UPDATE
I'm adding the definitions for models Person and Document.
class Document(models.Model):
creation_date = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=300, null=True, blank=True)
class Person(models.Model):
first_name = models.CharField(max_length=300)
last_name = models.CharField(max_length=300)
email = models.EmailField(max_length=300)
document = models.ForeignKey(Document)
UPDATE 2
One important thing I noticed is that, in the first error page (after the first submission of Document A form) the hidden inputs like person_set-TOTAL_FORMS and person_set-INITIAL_FORMS are set to 2 while they should be set to 1 (the actual number of persons). Obviously this happens because the submitted data doesn't reflect the actual database state.

"<Association: >" needs to have a value for field "association" before this many-to-many relationship can be used: django error

I have seen a bit of similar threads here in SO but cant seem to solve it. Here is my model:
class Association(models.Model):
'''
For members declared as groups
'''
member=models.ManyToManyField(User,related_name='association_user')
name=models.CharField(max_length=50)
def __str__(self):
return self.name
class Meta:
ordering=('name',)
The many-to-many relationship ended up creating, i think, a table under the hood with the following definitions:
association_id
user_id
I don't know if it is refering to the that field association nor how to add values to that table from my views.
my forms.py
class NewAssocationForm(forms.ModelForm):
'''
this is used to create a new form
'''
class Meta:
model=Association
fields=['name',]
labels=['Assocation Name'),]
and my views.py:
#login_required
def make_new(request):
'''
Register a new association or corporate
'''
if request.method=='POST':
form=NewAssocationForm(request.POST or None)
if form.is_valid():
new_association=form.save(commit=False)
new_association.member=request.user
new_association.save()
#add a message then redirect
return HttpResponseRedirect('/corporates/done/)
else:
form=NewAssocationForm(request.POST or None)
else:
form=NewAssocationForm(request.POST or None)
return render(request, "association_new.html", locals())
I don't have a field named association in my model at all. I doubt it is constraint erorr cos i can insert records to the table from the shell without any issues.
Here is my traceback.
Environment:
Request Method: POST
Request URL: http://localhost:9000/corporates/new/
Django Version: 1.10
Python Version: 3.4.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'widget_tweaks',
'welcome',
'members',
'corporates']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "D:\pyworks\agrigo\env\lib\site-packages\django\core\handlers\exception.py" in inner
39. response = get_response(request)
File "D:\pyworks\agrigo\env\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "D:\pyworks\agrigo\env\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\pyworks\agrigo\env\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "D:\pyworks\agrigo\env\agrigo\corporates\views.py" in make_new
78. new_association.member=request.user
File "D:\pyworks\agrigo\env\lib\site-packages\django\db\models\fields\related_descriptors.py" in __set__
499. manager = self.__get__(instance)
File "D:\pyworks\agrigo\env\lib\site-packages\django\db\models\fields\related_descriptors.py" in __get__
476. return self.related_manager_cls(instance)
File "D:\pyworks\agrigo\env\lib\site-packages\django\db\models\fields\related_descriptors.py" in __init__
783. (instance, self.source_field_name))
Exception Type: ValueError at /corporates/new/
Exception Value: "<Association: North Side>" needs to have a value for field "association" before this many-to-many relationship can be used.
Thanks for anyone who went through the long post. Apparently, I shouldn't specify user. So, deleting the line:
new_association.member=request.user
solved the issue. Makes sense; dumb me.

Django 1.9: 'AnonymousUser' object is not iterable

I was working on a Django 1.9 project, and suddenly this error popped up when I attempted to view my site's home page as a logged-out user.
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.9.7
Python Version: 2.7.10
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.sites',
'django.contrib.staticfiles',
'captcha',
'debug_toolbar',
'django_extensions',
'djstripe',
'crm',
'launch',
'rentals',
'widget_tweaks']
Installed Middleware:
[u'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
174. response = self.process_exception_by_middleware(e, request)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
172. response = response.render()
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/template/response.py" in render
160. self.content = self.rendered_content
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/template/response.py" in rendered_content
137. content = template.render(context, self._request)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/template/backends/django.py" in render
95. return self.template.render(context)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/template/base.py" in render
204. with context.bind_template(self):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py" in __enter__
17. return self.gen.next()
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/debug_toolbar/panels/templates/panel.py" in _request_context_bind_template
79. context = processor(self.request)
File "/Users/me/projects/rentalguru/src/rentals/processors.py" in allCategories
4. expense_categories = ExpenseCategory.objects.filter(user=request.user)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
122. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/query.py" in filter
790. return self._filter_or_exclude(False, *args, **kwargs)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/query.py" in _filter_or_exclude
808. clone.query.add_q(Q(*args, **kwargs))
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/sql/query.py" in add_q
1243. clause, _ = self._add_q(q_object, self.used_aliases)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/sql/query.py" in _add_q
1269. allow_joins=allow_joins, split_subq=split_subq,
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/sql/query.py" in build_filter
1174. self.check_related_objects(field, value, opts)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/sql/query.py" in check_related_objects
1073. for v in value:
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/utils/functional.py" in inner
205. return func(self._wrapped, *args)
Exception Type: TypeError at /
Exception Value: 'AnonymousUser' object is not iterable
I'm not sure what would be causing this, and there's only one Google search result (for this site) for this error. I searched the code for the is_authenticated() method and didn't find anything, so I'm unsure where to turn. Working through the stack trace didn't show any useful (for me) information.
Here is my view:
class HomePageView(TemplateView):
template_name = 'home.html'
No login decorators or wrapped functions that I can tell.
Let me know if I need to post anything else.
EDIT: Asked for the model, here is the offending context processor instead:
def allCategories(request):
expense_categories = ExpenseCategory.objects.filter(user=request.user)
tags = {'categories': expense_categories}
return tags
I just stumbled myself upon this error. Thankfully the answer was provided in the comments:
As you said you tried to view home page with logged out user and this ExpenseCategory.objects.filter(user=request.user) filtering of Anonymous user (because you are logged out now) seems to be the culprit. Either you should allow only a authenticated user to this view or handle the case where your user is Anonymous
As for myself, I had a view, where I was filtering on a model based on the current user, which apparantly fails, when the user is the AnonymousUser.
I fixed this by adding a check:
if request.user.is_active:
expense_categories = ExpenseCategory.objects.filter(user=request.user)
Note that some people seem to prefer to check request.user.is_authenticated instead.
If you are dealing with a view that shall be accessed by logged in users only, you can also use the #login_required decorator.
For reference:
https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User.is_active
https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User.is_authenticated
https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.decorators.login_required

Django REST framework IntegerField max_length issue

I am getting an "__init__() got an unexpected keyword argument 'max_length'" error for my model field of IntegerField with max_length. The stack trace is as follows:
Environment:
Request Method: GET
Request URL: http://localhost:8000/api/jmc/foundation/
Django Version: 1.7.1
Python Version: 2.7.8
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'dajaxice',
'dajax',
'rest_framework',
'core',
'analytics',
'api')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py" in wrapped_view
57. return view_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py" in dispatch
406. response = self.handle_exception(exc)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py" in dispatch
403. response = handler(request, *args, **kwargs)
File "/home/dev/Documents/Program Codes/Python/Django/Hera/api/views.py" in get
17. return Response(serializer.data)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py" in data
547. ret = super(ListSerializer, self).data
File "/usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py" in data
174. self._data = self.to_representation(self.instance)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py" in to_representation
500. self.child.to_representation(item) for item in iterable
File "/usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py" in to_representation
382. fields = [field for field in self.fields.values() if not field.write_only]
File "/usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py" in fields
245. for key, value in self.get_fields().items():
File "/usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py" in get_fields
911. ret[field_name] = field_cls(**kwargs)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/fields.py" in __init__
597. super(IntegerField, self).__init__(**kwargs)
Exception Type: TypeError at /api/jmc/foundation/
Exception Value: __init__() got an unexpected keyword argument 'max_length'
You might want to use the MaxValueValidator with IntegerField instead of max_length.
from django.db import models
from django.core.validators import MaxValueValidator
class MyModel(models.Model):
number = models.IntegerField(validators=[MaxValueValidator(100)])
Looks like IntegerField in Django doesn't have an max_length option. The reason we don't get any error is because Django suppresses it and 'Django REST framework' doesn't. Just removing the max_length option will make it work again.
Contrary to popular belief and common sense, Django does support the max_length argument on the IntegerField as well as any other field. The error you are seeing here is a known issue with Django REST Framework that does not currently have a fix.
The easiest way to fix this in your serializers (until a fix is done in DRF) is to redefine the field on the serializer without the max_length argument.
class MySerializer(serializers.ModelSerializer):
int_field = serializers.IntegerField()