Cannot assign "<SimpleLazyObject - django

class ProductDetailSlugview(ObjectViewedMixin, DetailView):
queryset = Product.objects.all()
template_name = "products/product_detail.html"
def get_context_data(self, *args, **kwargs):
context=super(ProductDetailSlugview, self).get_context_data(*args , **kwargs)
cart_object, new_object = Cart.objects.new_or_get(self.request)
context['cart']=cart_object
return context
this is my view
ValueError at /product/list/blackberry Cannot assign
"
at 0x7f0488733860>>": "ObjectViewed.user" must be a "User" instance.
Request Method: GET Request
URL: http://127.0.0.1:8000/product/list/blackberry Django
Version: 2.1.3 Exception Type: ValueError Exception Value: Cannot
assign "
object at 0x7f0488733860>>": "ObjectViewed.user" must be a "User"
instance. Exception
Location: /home/wiwigi/Desktop/django-virtual/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py
in set, line 210 Python
Executable: /home/wiwigi/Desktop/django-virtual/bin/python3 Python
Version: 3.6.5 Python Path: ['/home/wiwigi/Desktop/ecommerce_sample',
'/home/wiwigi/Desktop/ecommerce_sample',
'/home/wiwigi/Desktop/django-virtual/lib/python36.zip',
'/home/wiwigi/Desktop/django-virtual/lib/python3.6',
'/home/wiwigi/Desktop/django-virtual/lib/python3.6/lib-dynload',
'/usr/lib/python3.6',
'/home/wiwigi/Desktop/django-virtual/lib/python3.6/site-packages',
'/home/wiwigi/pycharm-2018.1.2/helpers/pycharm_matplotlib_backend']
Server time: mar, 26 Fév 2019 11:31:14 +0000
and my error code please help me

You are assigning an AnonymousUser object to the attribute user of an ObjectViewed instance. From the naming, my guess is that this happens in the ObjectViewedMixin.
For a more definite answer, you have to post the full stack trace and the relevant code.

This is because of you are accessing this view with out login (So it shows AnonymousUser) so you need to add LoginRequiredMixin to your class as below to ensure that only logged in users can visit this view.
from django.contrib.auth.mixins import LoginRequiredMixin
class ProductDetailSlugview(LoginRequiredMixin, ObjectViewedMixin, DetailView):
# rest of the code

Related

TypeError at /api/v1/accounts/me/ getMe() got an unexpected keyword argument 'version'

I am currently working on a Django project using django-rest-framewok versioning.
I am facing with a weird problem saying unexpected keyword argument named version.
views.py
class UserViewSet(viewsets.ModelViewSet):
queryset = ScreenShotUser.objects.all()
serializer_class = UserSerializer
def getMe(self,request):
user = ScreenShotUser.objects.get(pk=request.user.id)
return Response(user)
project url.py
router = routers.DefaultRouter()
router.register(r 'users', views.UserViewSet)
urlpatterns = [
url(r '^api/(?P<version>(v1|v2))/accounts/', include('Accounts.urls')),
]
and The accounts application's urls.py
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^me/$', views.getMe),
]
when I call http://127.0.0.1:8000/api/v1/accounts/me/
I got error like this
TypeError at /api/v1/accounts/me/
getMe() got an unexpected keyword argument 'version'
Request Method: GET
Request URL: http://127.0.0.1:8000/api/v1/accounts/me/
Django Version: 1.9.4
Exception Type: TypeError
Exception Value:
getMe() got an unexpected keyword argument 'version'
Exception Location: /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py in get_response, line 147
Python Executable: /Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5
Python Version: 3.5.1
Python Path:
['/Working_repo/screenshot/ScreenShot',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django_contrib_requestprovider-1.0.1-py3.5.egg',
'/Working_repo/screenshot/ScreenShot',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python35.zip',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages']
Server time: Mon, 28 Mar 2016 13:12:54 +0000
Django expert's please give me the hint I am missing. TIA
EDIT
I have got solution concept form Shang Wang's answer and this will be my solution
#api_view(['GET'])
def getMe(request, version):
user = ScreenShotUser.objects.get(pk=request.user.id)
result = UserSerializer(user).data
return Response(result)
If you have (?P<version>(v1|v2)) defined in url, it means your views.py method is expecting to take a parameter version. But your getMe method doesn't have that as parameter, hence the error. Easy fix would be removing the named parameter in your url definition.
Edit:
You should take a look at django doc about named group, in python (?P<name>pattern) means a regex named group. If you have that in django url definition, it means you are passing a parameter to views.py method. I don't think your views.py method is using version parameter, so you shouldn't have that defined in url. You just do:
url(r '^api/v1|v2/accounts/', include('Accounts.urls')),
If you can't remove the version parameter because some other methods do need it, just define it in getMe method and don't use it for anything:
def getMe(self, request, version):
user = ScreenShotUser.objects.get(pk=request.user.id)
return Response(user)
Read more details in django doc on how url dispatcher is working.

Django 1.7 matching query does not exist

I have the following error when I try to create a class-based view to Modify my model Destino.
If possible I would do without using slug or pk in the urls.py
Error:
Destino matching query does not exist.
Request Method: GET
Request URL: http://localhost:8002/modificarVC/modificar.html
Django Version: 1.7
Exception Type: DoesNotExist
Exception Value:
Destino matching query does not exist.
Exception Location: /usr/local/lib/python2.7/dist-packages/Django-1.7- py2.7.egg/django/db/models/query.py in get, line 357
Python Executable: /usr/bin/python
Python Version: 2.7.6
Python Path:
['/home/juanma/Escritorio/exPWfebrero/Django/AgenciaViajes',
'/usr/local/lib/python2.7/dist-packages/Django-1.7-py2.7.egg',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages/PILcompat',
'/usr/lib/python2.7/dist-packages/gtk-2.0',
'/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
'/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode']
URLS:
url(r'^modificarVC/modificar.html', modificarVC.as_view(), name='modificarDestino'),
VIEWS:
class modificarVC(UpdateView):
model = Destino
template_name = "modificarVC/modificar.html"
success_url = '/'
def get_object(self):
return Destino.objects.get(pk=self.request.GET.get('pk'))
As stated in some comments, you've done a few things that go against the power of class based views. In regards to the UpdateView which you're using, it's expecting a pk to be passed in.
# urls.py
url(r'^modificarVC/modificar/(?P<pk>\d+)/$', modificarVC.as_view(), name='modificarDestino')
When you hit a URL such as /modificarVC/modificar/5/ the UpdateView automatically sets the object by selected the object in your model Destino that has an id of 5.
# views.py
class modificarVC(UpdateView):
model = Destino
template_name = "modificarVC/modificar.html"
success_url = '/'
your error message hints at problem -- your request url didn't include a 'pk' request parameter (see 'Request URL')
Destino matching query does not exist.
Request Method: GET
Request URL: http://localhost:8002/modificarVC/modificar.html
run your request again, but add the pk parameter to the end as a query parameter: http://localhost:8002/modificarVC/modificar.html?pk=42

Django CBV - dealing with optional parameters in URLs

I have a Class Based View to list animals from a specific herd. There are multiple herds, so the user can either see all animals from ONE herd, or all animals from ALL herds.
How do I have an optional URL parameter and handle it in the CBV?
urls:
url(r'list/(?P<hpk>[0-9]+)/$', AnimalList.as_view(), name = 'animal_list'),
url(r'list/$', AnimalList.as_view(), name = 'animal_list'),
My view:
class AnimalList(ListView):
model = Animal
def get_queryset(self):
if self.kwargs is None:
return Animal.objects.all()
return Animal.objects.filter(herd = self.kwargs['hpk']) # <--- line 19 that returns an error
Going to a URL of like /animals/list/3/ works fine, while /animals/list/ fails with an error. Here's that error:
KeyError at /animals/list/
'hpk'
Request Method: GET
Request URL: http://localhost:8000/animals/list/
Django Version: 1.8.2
Exception Type: KeyError
Exception Value:
'hpk'
Exception Location: /var/www/registry/animals/views.py in get_queryset, line 19
I get that the self.kwargs is a dictionary, and when I print() it inside the view, it'll show it's empty. But I can't figure out how to capture that scenario. I feel like this is a simple, stupid error I'm missing.
To anyone who may stumble on this and need an answer, here is my working code after figuring it out:
class AnimalList(ListView):
model = Animal
def get_queryset(self):
if 'hpk' in self.kwargs:
return Animal.objects.filter(herd = self.kwargs['hpk'])
return Animal.objects.all()
Essentially we test to see if the URL parameter hpk is present in the list of self.kwargs. If it is, we filter the queryset. Otherwise, we return all animals.
Hope this helps someone :)
I would implement this using GET parameters instead of separate URLs. With this approach, there is only one URL /list/ that is filtered by parameters, for example /list/?hpk=1.
This is more flexible as you can eventually add more queries /list/?hpk=1&origin=europe
#url(r'list/$', AnimalList.as_view(), name = 'animal_list'),
class AnimalList(ListView):
model = Animal
def get_queryset(self):
queryset = Animal.objects.all()
hpk = self.request.GET.get("hpk"):
if hpk:
try:
queryset = queryset.filter(herd=hpk)
except:
# Display error message
return queryset

Sleekxmpp with Django not working?

Am working with sleekxmpp with python for sending messages and its working perfectly.Now i need to implement same in django to create web api for my mobile application.
When i implement that code in django its not getting connected to ejabberd server.xmpp=self.aaaa(jid,password,receiver,message) this function is throughing none value.
Below is my code in django:
class SendMessageView(APIView,sleekxmpp.ClientXMPP):
def aaaa(self,jid, password, recipient, message):
print "dddddddddddddddddddddddddddddddd",jid,password
sleekxmpp.ClientXMPP.__init__(self, jid, password)
self.recipient = recipient
self.msg = message
self.add_event_handler("session_start", self.start)
def start(self, event):
self.send_presence()
try:
self.get_roster()
except IqError as err:
logging.error('There was an error getting the roster')
logging.error(err.iq['error']['condition'])
self.disconnect()
except IqTimeout:
logging.error('Server is taking too long to respond')
self.disconnect()
self.send_message(mto=self.recipient,mbody=self.msg,mtype='chat')
self.disconnect(wait=True)
def post(self,request,format=None):
serializer=SendMessageSerializer(request.DATA)
jid=request.DATA.get('sender')
password=request.DATA.get('password')
receiver=request.DATA.get('receiver')
message=request.DATA.get('message')
print "ddddddddddddd",jid,password,receiver,message
xmpp=self.aaaa(jid,password,receiver,message)
print "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",xmpp
xmpp.register_plugin('xep_0030')
xmpp.register_plugin('xep_0199')
if xmpp.connect():
xmpp.process(block=False)
print "Connected"
else:
print "Not Connected"
Error shown is:
AttributeError at /chat-message/send/
'NoneType' object has no attribute 'register_plugin'
Request Method: POST
Request URL: ******/chat-message/send/
Django Version: 1.6
Exception Type: AttributeError
Exception Value:
'NoneType' object has no attribute 'register_plugin'
Exception Location: /home/ntech/projects/project_path/apps/chats/views.py in post, line 58
Python Executable: /home/ntech/Virtualenv/project_path/bin/python
Python Version: 2.7.6
Python Path:
['/home/ntech/projects/chatline',
'/home/ntech/Virtualenv/project_path/lib/python2.7',
'/home/ntech/Virtualenv/project_path/lib/python2.7/plat-i386-linux-gnu',
'/home/ntech/Virtualenv/project_path/lib/python2.7/lib-tk',
'/home/ntech/Virtualenv/project_path/lib/python2.7/lib-old',
'/home/ntech/Virtualenv/project_path/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-i386-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/home/ntech/Virtualenv/project_path/local/lib/python2.7/site-packages',
'/home/ntech/Virtualenv/project_path/lib/python2.7/site-packages']
Server time: Mon, 29 Dec 2014 06:02:10 +0000
Your method aaaa always return None. Try to use self.
Also it is not a good idea to multiple inheritance here. Try aggregation
class SendMessageView(APIView):
def aaaa(self,jid, password, recipient, message):
...
self.xmpp = sleekxmpp.ClientXMPP(jid, password)
...
def post(self,request,format=None):
...
self.aaaa(jid,password,receiver,message)
self.xmpp.register_plugin('xep_0030')
self.xmpp.register_plugin('xep_0199')
...
Or even better:
class SendMessageView(APIView):
def get_xmpp(self,jid, password, recipient, message):
...
return sleekxmpp.ClientXMPP(jid, password)
...
def post(self,request,format=None):
...
xmpp = self.get_xmpp(jid,password,receiver,message)
xmpp.register_plugin('xep_0030')
xmpp.register_plugin('xep_0199')
...

TypeError when form is submitted in django

I have a form at /item/3/sell_offer/4/
with action="add_post/"
I expect it go to /item/3/sell_offer/4/add_post
The relevant urlpatterns are
(r'^item/(?P<item_id>\d+)/sell_offer/(?P<sell_offer_id>\d+)/$', views.sell_offer_page),
(r'^item/(?P<item_id>\d+)/sell_offer/(?P<sell_offer_id>\d+)/add_post/$', views.sell_offer_add_post),
and the view looks like..
def sell_offer_add_post(request, item_id, sell_offer_id):
p = request.POST
if p.has_key("body") and p["body"]:
post = SellOfferPost(sell_offer=SellOfferPost.objects.get(pk=sell_offer_id))
form = SellOfferPostForm(p, instance=post)
post = form.save()
post.save()
return HttpResponseRedirect(reverse('views.sell_offer_page', args=[item_id, sell_offer_id]))
I think post action doesn't actually find it's way to the view.
Below is the error message
Request Method: POST
Request URL: http://......:8000/item/1/sell_offer/4/add_post/
Django Version: 1.3.1
Exception Type: TypeError
Exception Value:
sell_offer_add_post() got an unexpected keyword argument 'item_id'
Exception Location: /usr/local/lib/python2.6/dist-packages/Django-1.3.1-py2.6.egg/django/core/handlers/base.py in get_response, line 111
What am I doing wrong here?
Make sure you haven't called some other view sell_offer_add_post() further down.
Try setting your view signature to this:
def sell_offer_add_post(request, item_id=None, sell_offer_id=None):
I haven't tested but if I remember right, when you use named capture groups in your URL I think django tries to pass named keywords. You need to check the values in the view.