Django Filtering Objects - django

I have here some issue with the Product.objects
def say_hello(request):
queryset = Product.objects.filter(collection__id=1)
return render(request, ‘hello.html’, {‘name’: ‘Mosh’, ‘products’: list(queryset)})
I get the Error:
Unresolved attribute reference ‘objects’ for class ‘Product’.:6
It returns no list on: http://127.0.0.1:8000/playground/hello/
Does somebody know what can be the issue?

Related

Get latest ID in Django returns object is not iterable

I tried to get the latest id in Django but get the error.
def getlatestid(request):
cot_info = COT.objects.latest('id')
return JsonResponse({"data": list(cot_info)})
TypeError: 'COT' object is not iterable
latest(...) returns an object, not a list. So, you can try like this to fix the error:
def getlatestid(request):
cot_info = COT.objects.values().latest('id')
return JsonResponse({"data": cot_info})

Object of type 'Response' has no len() in DRF

ive combined two models. one model's field is annotated to another model's so they can merge. However, when I try to return the data, I get TypeError: object of type 'Response' has no len(). I've followed several examples on stackoverflow and it doesnt seem to be working.
Here's what I have:
class ExploreAPIView(generics.ListAPIView):
def get_queryset(self):
merged_queryset = Place.get_queryset(self.request.user)
usr_pks = [u.pk for u in merged_queryset]
queryset = Place.objects.filter(pk__in=usr_pks)
serialUser = UserSerializer( User.objects.annotate(time=Extract('date_joined','epoch')), many=True).data[:]
serialPlace = PlacesSerializer(queryset, many=True).data[:]
chained_list = sorted(serialPlace +serialUser, key=lambda x: x.get('time'))
return Response(chained_list)
I dont understand why it returns no len() when it returns items if i print out the chained_list
You're returning a Response from get_queryset. But that method is supposed to return a queryset, as the name implies.

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

django form: Passing parameter from view.py to forms gives out error

Newbie question:
I need to accept a parameter in a form from a method in views.py but it gave me troubles. In the view I created a method with following snippet:
def scan_page(request):
myClient = request.user.get_profile().client
form = WirelessScanForm(client = myClient) # pass parameter to the form
and in the forms.py I defined the following form:
class WirelessScanForm(forms.ModelForm):
time = forms.DateTimeField(label="Schedule Time", widget=AdminSplitDateTime())
def __init__(self,*args,**kwargs):
myClient = kwargs.pop("client") # client is the parameter passed from views.py
super(WirelessScanForm, self).__init__(*args,**kwargs)
prob = forms.ChoiceField(label="Sniffer", choices=[ x.sniffer.plug_ip for x in Sniffer.objects.filter(client = myClient) ])
But django keeps giving me error saying: TemplateSyntaxError: Caught NameError while rendering: name 'myClient' is not defined(This error happens in the query)
I'm afraid it would be something stupid missing here, but I cannot really figure out why. Please help, thanks.
Assuming I've corrected your formatting properly, you have an indentation issue: prob is outside __init__, so doesn't have access to the local myClient variable.
However if you bring it inside the method, it still won't work, as there are two other issues: first, simply assigning a field to a variable won't set it on the form; and second, the choices attribute needs a list of 2-tuples, not just a flat list. What you need is this:
def __init__(self,*args,**kwargs):
myClient = kwargs.pop("client") # client is the parameter passed from views.py
super(WirelessScanForm, self).__init__(*args,**kwargs)
self.fields['prob'] = forms.ChoiceField(label="Sniffer", choices=[(x.plug_ip, x.MY_DESCRIPTIVE_FIELD) for x in Sniffer.objects.filter(client = myClient)])
Obviously replace MY_DESCRIPTIVE_FIELD with the actual field you want displayed in the choices.

django-ratings problem

I have just installed the django-ratings app and I am having some trouble getting it working.
I have successfully added a rating field to my model, however, in the documentation, it says you can get a list of records by rating by using the following code:
# In this example, ``rating`` is the attribute name for your ``RatingField``
qs = qs.extra(select={
'rating': '((100/%s*rating_score/(rating_votes+%s))+100)/2' % (MyModel.rating.range, MyModel.rating.weight)
})
qs = qs.order_by('-rating')
I have added the following to my class based generic view:
def get_queryset(self):
return Resource.objects.filter(user=self.request.user).extra(select={
'rating': '((100/%s*rating_score/(rating_votes+%s))+100)/2' % (Resource.rating.range, Resource.rating.weight)
})
However, this gives me the following error:
'RatingField' object has no attribute 'range'
Can anyone see what I might have done wrong?
Any advice appreciated.
Thanks.