Django - 'User' object has no attribute 'session_set' - python

I want to add a Sessions tabs to my Django project:
navbar.html
<li>Sessions</li>
But i keep getting the following error:
'User' object has no attribute 'session_set''User' object has no attribute 'session_set'
Exception Location: C:\Users\User\lib\site-packages\django\utils\functional.py in inner, line 214
I don't know where this error comes from, i did not find any other reference online, can anyone help me?
Here is the login view that i'm using: https://github.com/Bouke/django-two-factor-auth/blob/master/two_factor/views/core.py
Full traceback
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/account/sessions/
Django Version: 2.1.7
Python Version: 3.7.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main.apps.MainConfig',
'tinymce',
'captcha',
'django.contrib.sites',
'django_otp',
'django_otp.plugins.otp_static',
'django_otp.plugins.otp_totp',
'two_factor']
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',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django_otp.middleware.OTPMiddleware']
Traceback:
File "C:\Users\User\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\User\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "C:\Users\User\lib\site-packages\django\core\handlers\base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\User\lib\site-packages\django\views\generic\base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "C:\Users\User\lib\site-packages\django\utils\decorators.py" in _wrapper
45. return bound_method(*args, **kwargs)
File "C:\Users\User\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
21. return view_func(request, *args, **kwargs)
File "C:\Users\User\lib\site-packages\user_sessions\views.py" in dispatch
22. **kwargs)
File "C:\Users\User\lib\site-packages\django\views\generic\base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "C:\Users\User\lib\site-packages\django\views\generic\list.py" in get
142. self.object_list = self.get_queryset()
File "C:\Users\User\lib\site-packages\user_sessions\views.py" in get_queryset
14. return self.request.user.session_set\
File "C:\Users\User\lib\site-packages\django\utils\functional.py" in inner
214. return func(self._wrapped, *args)
File "C:\Users\User\lib\site-packages\django\utils\functional.py" in inner
214. return func(self._wrapped, *args)
Exception Type: AttributeError at /account/sessions/
Exception Value: 'User' object has no attribute 'session_set'

You need to replace django.contrib.sessions in your INSTALLED_APPS with user_sessions if you want to use django-user-sessions. This will setup its models correctly.
Furthermore make sure you have also followed all other installation instructions.

Related

Django Allauth TypeError at /accounts/confirm-email/

I'm using django-allauth for my django authentication and
while confirming the email i get
TypeError at /accounts/confirmemail/MQ:1mk57U:HtWDA8B5NClWhK2L6nDxJgwlNRGItW_4FyhDqcbcfow/ and it's complaining about argument of type 'bool' is not iterable
as I searched answers were in the cause of using django-rest-allauth and here I'm not using any rest api and facing this issue.
some configs on my settings.py file
# all auth config
AUTHENTICATION_BACKENDS = [
# Needed to login by username in Django admin, regardless of `allauth`
"django.contrib.auth.backends.ModelBackend",
# `allauth` specific authentication methods, such as login by e-mail
"allauth.account.auth_backends.AuthenticationBackend",
]
SITE_ID = 1
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
ACCOUNT_AUTHENTICATION_METHOD = "username_email"
ACCOUNT_LOGIN_ON_PASSWORD_RESET = True
Update: The full error tracback looks
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/accounts/confirm-email/MQ:1mk57U:HtWDA8B5NClWhK2L6nDxJgwlNRGItW_4FyhDqcbcfow/
Django Version: 3.2.9
Python Version: 3.9.7
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.twitter',
'allauth.socialaccount.providers.telegram',
'allauth.socialaccount.providers.instagram',
'django_extensions',
'avatar',
'django_cleanup.apps.CleanupConfig',
'user']
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/ali/.local/lib/python3.9/site-packages/django/shortcuts.py", line 130, in resolve_url
return reverse(to, args=args, kwargs=kwargs)
File "/home/ali/.local/lib/python3.9/site-packages/django/urls/base.py", line 86, in reverse
return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
File "/home/ali/.local/lib/python3.9/site-packages/django/urls/resolvers.py", line 694, in _reverse_with_prefix
raise NoReverseMatch(msg)
During handling of the above exception (Reverse for 'True' not found. 'True' is not a valid view function or pattern name.), another exception occurred:
File "/home/ali/.local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/ali/.local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ali/.local/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/home/ali/.local/lib/python3.9/site-packages/django/views/generic/base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "/home/ali/.local/lib/python3.9/site-packages/allauth/account/views.py", line 295, in get
return self.post(*args, **kwargs)
File "/home/ali/.local/lib/python3.9/site-packages/allauth/account/views.py", line 334, in post
return redirect(redirect_url)
File "/home/ali/.local/lib/python3.9/site-packages/django/shortcuts.py", line 41, in redirect
return redirect_class(resolve_url(to, *args, **kwargs))
File "/home/ali/.local/lib/python3.9/site-packages/django/shortcuts.py", line 136, in resolve_url
if '/' not in to and '.' not in to:
Exception Type: TypeError at /accounts/confirm-email/MQ:1mk57U:HtWDA8B5NClWhK2L6nDxJgwlNRGItW_4FyhDqcbcfow/
Exception Value: argument of type 'bool' is not iterable
The proplem come from after email confirmation done the reverse url is not valid so you need to go to your setting and check setting for that you must give it valid url to be redircted after confirmation
So I hope to revise the urls

ValueError with Django form initial

I'm building a reservation app with Django and I want to allow users to use one reservation as template for another. My idea is that I add ?prefill=<reservation_id> to url and then prefill empty form with data from reservation in prefill id.
My CreateView looks like this:
class ReservationCreateView(LoginRequiredMixin, CreateUpdateMixin, CreateView):
model = Reservation
form_class = ReservationForm
success_url = '/'
def get_context_data(self, **kwargs):
ctx = super(ReservationCreateView, self).get_context_data()
r = Reservation.objects.filter(pk=self.request.GET.get('prefill'))
ctx['form'] = ReservationForm(initial=r.values(), request=self.request)
return ctx
This gives me: dictionary update sequence element #0 has length 30; 2 is required
Error stack:
Environment:
Request Method: GET
Request URL: http://localhost:8000/r/create/?prefill=56cc36bd-c766-4e45-8a1b-cdde3cd87dc4
Django Version: 1.10.3
Python Version: 2.7.10
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'tags',
'profiles',
'reservations',
'drivers',
'import_export',
'src',
'crispy_forms',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
'anymail',
'wf',
'storages',
'djangoformsetjs']
Installed Middleware:
['corsheaders.middleware.CorsMiddleware',
'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',
'htmlmin.middleware.HtmlMinifyMiddleware',
'htmlmin.middleware.MarkRequestMiddleware']
Traceback:
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/contrib/auth/mixins.py" in dispatch
56. return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/reservations/mixins.py" in get
68. route_formset=route_formset))
File "/Users/jhotujec/Documents/projects/optilimo/reservations/views.py" in get_context_data
108. ctx['form'] = ReservationForm(initial=r.values(), request=self.request)
File "/Users/jhotujec/Documents/projects/optilimo/reservations/forms.py" in __init__
30. super(ReservationForm, self).__init__(*args, **kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/forms/models.py" in __init__
285. object_data.update(initial)
Exception Type: ValueError at /r/create/
Exception Value: dictionary update sequence element #0 has length 30; 2 is required
filter() always returns a queryset, and values() is then basically a list of dicts, whereas the form is expecting a single dict.
You could fix this by using r.values()[0] instead, but this is really the wrong approach. This is a model form; you should populate it by passing an actual model instance as the instance argument.
The problem is initial=r.values() where r is a QuerySet. values returns a list of dicts, initial expects a dict. You could get the Reservation instance and use the instance parameter of the form constructor instead:
# first() will return None if the QS is empty
r = Reservation.objects.get(pk=self.request.GET.get('prefill')).first()
ctx['form'] = ReservationForm(instance=r, request=self.request)

In DRF(django-rest-framework), AttributeError 'str' object has no attribute '~~' How to solve it?

I'm using DRF and be front of AttributeError 'str' object has no attribute '~~'.
my error page and code
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/blog/
Django Version: 1.9.7
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'blog',
'account',
'taggit',
'friendship',
'rest_framework']
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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
466. response = self.handle_exception(exc)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
463. response = handler(request, *args, **kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/decorators.py" in handler
52. return func(*args, **kwargs)
File "/home/keepair/djangogirls/blog/views.py" in post_list
37. return Response(serializer.data)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in data
700. ret = super(ListSerializer, self).data
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in data
239. self._data = self.to_representation(self.instance)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in to_representation
618. self.child.to_representation(item) for item in iterable
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in <listcomp>
618. self.child.to_representation(item) for item in iterable
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in to_representation
463. attribute = field.get_attribute(instance)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/relations.py" in get_attribute
157. return get_attribute(instance, self.source_attrs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/fields.py" in get_attribute
83. instance = getattr(instance, attr)
Exception Type: AttributeError at /blog/
Exception Value: 'str' object has no attribute 'author'
I wonder how to make serializers.py codes.
I already studied : http://www.django-rest-framework.org/api-guide/relations/
But I don't understand what I should do. Where should I put serializers.py?
And how to make my serializers code? Or maybe models.ForienKey is unavailable on using DRF?
blog/views.py
#api_view(['GET'])
def post_list(request, format=None):
"""
List all snippets, or create a new snippet.
"""
if request.method == 'GET':
lat = request.POST.get('user_lat', '13')
lon = request.POST.get('user_lon', '15')
userpoint = GEOSGeometry('POINT(' + lat + ' ' + lon + ')', srid=4326)
i=1
while i:
list_i = Post.objects.filter(point__distance_lte = (userpoint, D(km=i)))
list_total = str(',' + ' list_i')
post_list = list(chain(list_total))
if len(post_list) >= 0 :
break
serializer = PostSerializer(post_list, many=True)
return Response(serializer.data)
This has nothing to do with your serializer, or where you put it. The error traceback is telling you that the error happens in the view.
So, in your post_list view, you build up a list (also called post_list) which is populated by a list of strings. Then you try and put it through the PostSerializer, which of course is expecting a queryset of Posts.
I'm not sure what the point of the list is; seems like you should be passing the Posts directly to the serializer.

Django admin/ ViewDoesNotExist

I checked the other questions on here like this one, but couldn't get an accurate answer that would solve my problem. When i run the dev server with python manage.py runserver I get the following `
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/
Django Version: 1.6.4
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'firstapp')
Installed Middleware:
('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 "/Library/Python/2.7/site-packages/Django-1.6.4-py2.7.egg/django/core/handlers/base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/Django-1.6.4-py2.7.egg/django/contrib/admin/sites.py" in wrapper
215. return self.admin_view(view, cacheable)(*args, **kwargs)
File "/Library/Python/2.7/site-packages/Django-1.6.4-py2.7.egg/django/utils/decorators.py" in _wrapped_view
99. response = view_func(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/Django-1.6.4-py2.7.egg/django/views/decorators/cache.py" in _wrapped_view_func
52. response = view_func(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/Django-1.6.4-py2.7.egg/django/contrib/admin/sites.py" in inner
194. current_app=self.name):
File "/Library/Python/2.7/site-packages/Django-1.6.4-py2.7.egg/django/core/urlresolvers.py" in reverse
503. app_list = resolver.app_dict[ns]
File "/Library/Python/2.7/site-packages/Django-1.6.4-py2.7.egg/django/core/urlresolvers.py" in app_dict
329. self._populate()
File "/Library/Python/2.7/site-packages/Django-1.6.4-py2.7.egg/django/core/urlresolvers.py" in _populate
303. lookups.appendlist(pattern.callback, (bits, p_pattern, pattern.default_args))
File "/Library/Python/2.7/site-packages/Django-1.6.4-py2.7.egg/django/core/urlresolvers.py" in callback
230. self._callback = get_callable(self._callback_str)
File "/Library/Python/2.7/site-packages/Django-1.6.4-py2.7.egg/django/utils/functional.py" in wrapper
32. result = func(*args)
File "/Library/Python/2.7/site-packages/Django-1.6.4-py2.7.egg/django/core/urlresolvers.py" in get_callable
118. (lookup_view, mod_name))
Exception Type: ViewDoesNotExist at /admin/
Exception Value: Could not import Chinatown.views. View does not exist in module Chinatown.
`
But when i check my other project with which i follow the official django tut I dont have the mentioned views file in the project directory but I am able to see the admin page. Any suggestions why is the error being raised?
i think it will be more useful if just copy / paste error log . use:
./manage.py runserver --traceback
you need to add function in chinatown/views.py say "food"
and a url pattern in project's urls.py:
from django.conf.urls import url
urlpatterns = [
url(r'^food/$', 'chinatown.views.food'),
]
https://docs.djangoproject.com/en/dev/topics/http/urls/

Django error 'too many values to unpack' in objects.get(id)

I have url like this http://gagandeepdesk/2690/ which I am filtering with urls.py file and sending 2690 as one of the parameters to the function.
my urls.py filter looks like this,
url(r'^(\d+)/', 'scango.scanner.views.download'),
And that function looks like this,
def download(request, MediaId):
media = Media.objects.get(id=int(MediaId))
#print media
return HttpResponse(FileIterWrapper(open(media.path)))
I am getting error 'too many values to unpack' on line
media = Media.objects.get(id=int(MediaId))
I also tried running this function standalone without request object and it is running perfectly fine. So, I am confused what I have done wrong here.
Environment:
Request Method: GET
Request URL: http://gagandeepdesk/2690/
Django Version: 1.3
Python Version: 2.7.1
Installed Applications:
['haystack',
'scanner',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Users\gagasing\Desktop\ideas\scango\..\scango\scanner\views.py" in download
21. media = Media.objects.get(id=int(MediaId))
File "C:\Python27\lib\site-packages\django\db\models\manager.py" in get
132. return self.get_query_set().get(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in get
343. clone = self.filter(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in filter
552. return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
570. clone.query.add_q(Q(*args, **kwargs))
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in add_q
1170. can_reuse=used_aliases, force_having=force_having)
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in add_filter
1013. arg, value = filter_expr
Exception Type: ValueError at /2690/
Exception Value: too many values to unpack
(r'^(?P<MediaId>\d+)/$', 'scango.scanner.views.download')
Maybe try this instead?
This is an example of named groups.
In Python regular expressions, the syntax for named regular expression
groups is (?Ppattern), where name is the name of the group and
pattern is some pattern to match.

Categories

Resources