What did mean by AttributeError at /login_user/? - django

My target is to get all the products a user added to the cart, that's why I decided to fetch the ShopingCart model from the context processor. And I added it to the context processor, and it worked well. But the problem is when I try to log out, then I get an error. Where did the actual problem occur? 😢...
models.py:
class ShopingCart(models.Model):
User = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='UserShoppingCartRelatedName',on_delete=models.CASCADE)
Product = models.ForeignKey(Products, related_name='ShoppingCartRelatedName',on_delete=models.CASCADE)
context_processors:
def ShoppingCart(request):
return {"ShoppingCart":request.user.UserShoppingCartRelatedName.all()}
error:
AttributeError at /login_user/
'AnonymousUser' object has no attribute 'UserShoppingCartRelatedName'
Request Method: GET
Request URL: http://127.0.0.1:8000/login_user/
Django Version: 4.0.4
Exception Type: AttributeError
Exception Value:
'AnonymousUser' object has no attribute 'UserShoppingCartRelatedName'
Exception Location: D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\lib\site-packages\django\utils\functional.py, line 259, in inner
Python Executable: D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\Scripts\python.exe
Python Version: 3.9.5
Python Path:
['D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce site',
'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\python39.zip',
'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\DLLs',
'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\lib',
'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39',
'D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce site\\env',
'D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce '
'site\\env\\lib\\site-packages']
Server time: Tue, 09 Aug 2022 11:48:23 +0000

Check if user is not none and authenticated.
def ShoppingCart(request):
if request.user is not None and request.user.is_authenticated():
return {"ShoppingCart":request.user.UserShoppingCartRelatedName.all()}
else:
return {}

It looks as if you are not logged in!
You must login before you can access the user atrubute.
If you are not loged in it says you are 'AnonymousUser'
'AnonymousUser' object has no attribute 'UserShoppingCartRelatedName'
Login and then try it!!

Related

AttributeError at /BRMapp/view-books/

I am developing Book Record Management system as my first project on django but after performing all my functionalities I got a problem in my views.py file in a function name view-book in a line(books=models.Book.objects.all()).Although i have made a class name 'Book' in models.py and i also have imported models in my views.py file with a line(form django.db import models).Although it is not working.Kindly help
Error showing like this:::
module 'django.db.models' has no attribute 'Book'
Request Method: GET
Request URL: http://localhost:8000/BRMapp/view-books/
Django Version: 3.2.5
Exception Type: AttributeError
Exception Value:
module 'django.db.models' has no attribute 'Book'
Exception Location: G:\Django projects\firstproject\BRMapp\views.py, line 41, in viewBooks
Python Executable: C:\Users\amann\AppData\Local\Programs\Python\Python39\python.exe
Python Version: 3.9.2
Python Path:
['G:\\Django projects\\firstproject',
'C:\\Users\\amann\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
'C:\\Users\\amann\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
'C:\\Users\\amann\\AppData\\Local\\Programs\\Python\\Python39\\lib',
'C:\\Users\\amann\\AppData\\Local\\Programs\\Python\\Python39',
'C:\\Users\\amann\\AppData\\Roaming\\Python\\Python39\\site-packages',
'C:\\Users\\amann\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages']
Server time: Thu, 12 Aug 2021 10:19:08 +0000
Based on the exception models points to the models submodule of the django.db module, but there is no Book defined in that module.
Likely the Book originates from elsewhere, from an appname.models module.
You thus import this with:
from appname.models import Book
# …
def viewBooks(request):
# …
# ↓ no models.
books = Book.objects.all()
# …

'DeferredAttribute' object is not callable

I'm working on a simple django project, but i face this problem that you see below so, i want a solution because i really got tired
I expect the output of that code to be numberone but the actual output is this error :
TypeError at /db/
'DeferredAttribute' object is not callable
Request Method: GET
Request URL: http://127.0.0.1:8000/db/
Django Version: 2.1.5
Exception Type: TypeError
Exception Value:
'DeferredAttribute' object is not callable
Exception Location: /home/mohammed/Desktop/New life programming/python /pythonDjano/Filecorse/NewDjango/MohammedAlaa/Abdullah/views.py in db, line 16
Python Executable: /usr/bin/python3
Python Version: 3.6.8
Python Path:
['/home/mohammed/Desktop/New life '
'programming/python/pythonDjano/Filecorse/NewDjango/MohammedAlaa',
'/usr/local/lib/python3.6/dist-packages/pip-19.1.1-py3.6.egg',
'/usr/lib/python36.zip',
'/usr/lib/python3.6',
'/usr/lib/python3.6/lib-dynload',
'/home/mohammed/.local/lib/python3.6/site-packages',
'/usr/local/lib/python3.6/dist-packages',
'/usr/lib/python3/dist-packages']
Server time: Sat, 31 Aug 2019 11:13:18 +0000
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Product
def Home(request):
return HttpResponse('Welcome, Mohammed Alaa :)')
def htm(request):
return render(request,'htm.html',{'hello':"hello Mohammed Abo Alaa again:)", 'days':['wed', 'fri', 'thru']
})
def others(request):
return HttpResponse('Welcome, Mohammed Alaa :) form others')
def db(request):
dat = ''
p1 = Product(namee='numberone', pricee=500,Type='m')
p1.save()
dat = Product.namee()
return HttpResponse(dat)
You need to refer to the Product instance you just created, not the whole Product class. And it's just a string, no need to call it.
dat = p1.namee

Facebook authentication using angular JS and Django

I'm a beginner in both angular JS and django. I was following this particular tutorial in making a facebook authentication app.
http://cbdev.blogspot.in/2014/02/facebook-login-with-angularjs-django.html
I've followed the tutorial exactly. And when I start the server I get the error.
NameError at /
name 'strategy' is not defined
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.3.1
Exception Type: NameError
Exception Value:
name 'strategy' is not defined
Exception Location: /root/Documents/django/clueless/clueless_engine/../clueless_engine/views.py in <module>, line 1
Python Executable: /root/Documents/django/clueless/bin/python
Python Version: 2.7.13
Python Path:
['/root/Documents/django/clueless/clueless_engine',
'/root/Documents/django/clueless/lib/python2.7',
'/root/Documents/django/clueless/lib/python2.7/plat-x86_64-linux-gnu',
'/root/Documents/django/clueless/lib/python2.7/lib-tk',
'/root/Documents/django/clueless/lib/python2.7/lib-old',
'/root/Documents/django/clueless/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/root/Documents/django/clueless/local/lib/python2.7/site-packages',
'/root/Documents/django/clueless/lib/python2.7/site-packages']
Server time: Thu, 1 Jun 2017 07:30:14 +0530
my views.py file is
#strategy()
def auth_by_token(request, backend):
backend = request.strategy.backend
user=request.user
user = backend.do_auth(
access_token=request.DATA.get('access_token'),
user=user.is_authenticated() and user or None
)
if user and user.is_active:
return user# Return anything that makes sense here
else:
return None
#csrf_exempt
#api_view(['POST'])
#permission_classes((permissions.AllowAny,))
def social_register(request):
auth_token = request.DATA.get('access_token', None)
backend = request.DATA.get('backend', None)
if auth_token and backend:
try:
user = auth_by_token(request, backend)
except Exception, err:
return Response(str(err), status=400)
if user:
strategy = load_strategy(request=request, backend=backend)
_do_login(strategy, user)
return Response( "User logged in", status=status.HTTP_200_OK )
else:
return Response("Bad Credentials", status=403)
else:
return Response("Bad request", status=400)
I have created Social Auth authentication using python scocial auth. you can check:
https://github.com/ranvijay-sachan/django-rest-login-and-social_auth/tree/master/profiles
POST: http://localhost:8000/api/v1/login/2/
Content-Type : application/json
{ "accessToken": "alert token" }
The problem was that I forgot to import modules.
from social.apps.django_app.utils import load_strategy strategy = load_strategy(request)

I am using django haystack with whoosh , But there some error after entering some search query in searchbar, below is the description

Error screenshot
AttributeError at /search/
'NoneType' object has no attribute '_default_manager'
Request Method: GET
Request URL: http://127.0.0.1:8000/search/?q=desktop
Django Version: 1.9
Exception Type: AttributeError
Exception Value:'NoneType' object has no attribute '_default_manager'
Exception Location: /home/ankit/venv/django/lib/python3.4/site-packages/haystack/query.py in post_process_results, line 219
Python Executable: /home/ankit/venv/django/bin/python
Python Version: 3.4.3
Python Path: ['/home/ankit/venv/django/p2',
'/home/ankit/venv/django/lib/python3.4',
'/home/ankit/venv/django/lib/python3.4/plat-x86_64-linux-gnu',
'/home/ankit/venv/django/lib/python3.4/lib-dynload',
'/usr/lib/python3.4',
'/usr/lib/python3.4/plat-x86_64-linux-gnu',
'/home/ankit/venv/django/lib/python3.4/site-packages']
Server time: Sun, 27 Dec 2015 10:29:28 +0000
My search_indexes.py
import datetime
from haystack import indexes
from inventory.models import Item
class ItemIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
pub_date = indexes.DateTimeField(model_attr='pub_date')
content_auto = indexes.EdgeNgramField(model_attr='title')
def get_model(self):
return Item
def index_queryset(self, using=None):
return self.get_model().objects.all()
My settings.py file
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'),
},
}
The django.db.model.get_model is not available any longer in 1.9, so None is returned when calling django.db.models.get_model, but in the more recent commit (from the 3rd of January) the utils.app_loading.py is used to either use the django.apps.apps.get_model when using Django 1.7 or higher, otherwise the old django.db.models._get_models is used.
So, best to upgrade to the latest development version git+https://github.com/django-haystack/django-haystack.git.

500-error when adding a picture

In Django-CMS, I select the picture plugin and add a picture from my harddrive, then when I click on that picture-plugin I get the error as seen below. What is the reason for this?
ValueError at /admin/cms/page/2/edit-plugin/7/cms_page_media/2/parking_mockup.png/
invalid literal for int() with base 10: '2/edit-plugin/7/cms_page_media/2/parking_mockup.png'
Request Method: GET
Request URL: http://localhost:8000/admin/cms/page/2/edit-plugin/7/cms_page_media/2/parking_mockup.png/
Django Version: 1.3.1
Exception Type: ValueError
Exception Value:
invalid literal for int() with base 10: '2/edit-plugin/7/cms_page_media/2/parking_mockup.png'
Exception Location: C:\Python27\lib\site-packages\django\db\models\fields\__init__.py in get_prep_value, line 479
Python Executable: C:\Python27\python.exe
Python Version: 2.7.2
Python Path:
['C:\\djangoworkspace\\hulawai',
'C:\\Python27\\lib\\site-packages\\django_classy_tags-0.3.4.1-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\django_sekizai-0.5-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\html5lib-0.95-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\virtualenv-1.7.1.2-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\pip-1.1-py2.7.egg',
'C:\\Windows\\system32\\python27.zip',
'C:\\Python27\\DLLs',
'C:\\Python27\\lib',
'C:\\Python27\\lib\\plat-win',
'C:\\Python27\\lib\\lib-tk',
'C:\\Python27',
'C:\\Python27\\lib\\site-packages',
'C:\\Python27\\lib\\site-packages\\PIL']
Server time: Thu, 22 Mar 2012 11:03:58 +0100
Traceback Switch to copy-and-paste view
C:\Python27\lib\site-packages\django\core\handlers\base.py in get_response
for middleware_method in self._view_middleware:
response = middleware_method(request, callback, callback_args, callback_kwargs)
if response:
break
if response is None:
try:
response = callback(request, *callback_args, **callback_kwargs) ...
except Exception, e:
# If the view raised an exception, run it through exception
# middleware, and if the exception middleware returns a
# response, use that. Otherwise, reraise the exception.
for middleware_method in self._exception_middleware:
response = middleware_method(request, e)
UPDATE Full stacktrace available here: https://gist.github.com/2157837
I edited my settings.py
From
MEDIA_URL = 'media/'
To
MEDIA_URL = 'http://localhost:8000/media/'