Django AttributeError: 'str' object has no attribute 'get' - django

When visiting a url it returns a error mentioned in the question title.
The View itself is a ListView.
When i debuged the view, it only looped through the dispatcher function and return the following error without getting to queryset.
Here's the code.
ListView
class MailingListView(ListView, LoginRequiredMixin):
# model = MailingList
template_name = 'mailinglist/mailing_list.html'
def get_queryset(self):
return MailingList.objects.filter(owner=self.request.user)
def dispatch(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return reverse('user:login')
return super().dispatch(request, *args, **kwargs)
Model
class MailingList(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4(), editable=False)
name = models.CharField(max_length=140)
owner = models.ForeignKey(to=user_model,
on_delete=models.CASCADE)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('mailinglist:manage_list', kwargs={'pk': self.id})
def user_can_use_mailinglist(self, user):
return user == self.owner
Traceback
> Internal Server Error: /mailinglist/ Traceback (most recent call
> last): File
> "/venv/lib/python3.7/site-packages/django/core/handlers/exception.py",
> line 34, in inner
> response = get_response(request) File "/venv/lib/python3.7/site-packages/django/utils/deprecation.py",
> line 93, in __call__
> response = self.process_response(request, response) File /venv/lib/python3.7/site-packages/django/middleware/clickjacking.py",
> line 26, in process_response
> if response.get('X-Frame-Options') is not None: AttributeError: 'str' object has no attribute 'get'

reverse() returns a string. But you are supposed to return HTTP responses.
Change in dispatch in MailingListView.
from django.http import HttpResponseRedirect
return HttpResponseRedirect(reverse('user:login'))

Related

Error when serializing foreign key object with django-rest-framework-gis to geojson

I am trying to serialize into geojson a model with a foreign key that has a geometry field. I am using the django-rest-framework-gis. I am using django 2.2
I'm stuck on this and none of the other related answers on Stack Overflow work for me. e.g. I have tried versions of this:
How can I flatten a foreignkey object with django-rest-framework-(gis)
Set serializer geo_field as PointField from another model - Django
The problem is I get this error:
Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'statements.models.Response'>
Models:
from django.contrib.gis.db import models
from django.contrib.gis.geos import Point
class Hexgrid_10km2(models.Model):
lng = models.FloatField()
lat = models.FloatField()
polygon = models.MultiPolygonField(srid=4326)
centroid = models.PointField(default=Point(0,0), srid=4326)
def __str__(self):
return f'lng: { self.lng } lat: {self.lat }'
class Response(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
statement = models.ForeignKey(Statement, on_delete=models.CASCADE)
hexgrid_10km2 = models.ForeignKey(Hexgrid_10km2, on_delete=models.CASCADE, null=True, blank=True)
#property
def polygon(self):
return self.hexgrid_10km2.polygon
Views
class ResponseHeatmapAPIView(APIView): #ReadOnly
def get(self, request, pk):
final = Response.objects.all()
serializer = ResponseHeatmapSerializer(final, many=True)
return Response(serializer.data)
Serializers
class ResponseHeatmapSerializer(GeoFeatureModelSerializer):
""" A class to serialize hex polygons as GeoJSON compatible data """
hexgrid_10km2 = GeometrySerializerMethodField()
def get_hexgrid_10km2(self, obj):
return obj.hexgrid_10km2.polygon
class Meta:
model = Response
geo_field = 'hexgrid_10km2'
id_field = False
fields = ('id',)
Traceback
OrderedDict([('type', 'FeatureCollection'), ('features', [OrderedDict([('id', 2), ('type', 'Feature'), ('geometry', GeoJsonDict([('type', 'MultiPolygon'), ('coordinates', [[[[0.52353663711945, 50.8631481850499], [0.538799411254891, 50.86870974483], [0.554062185390241, 50.8631481850499], [0.554062185390241, 50.852023074998], [0.548895002474644, 50.85013962], [0.540831980000019, 50.85013962], [0.53199000192362, 50.8489417564374], [0.52353663711945, 50.852023074998], [0.52353663711945, 50.8631481850499]]]])])), ('properties', OrderedDict([('response_date', '2020-04-15T21:04:04.599597Z'), ('agree', 1), ('hasLocation', False), ('location', GeoJsonDict([('type', 'Point'), ('coordinates', [0.550660257722784, 50.851541821108924])])), ('latitude', 50.851541821108924), ('longitude', 0.5506602577227836), ('locationAccuracy', 0.0), ('user', 1), ('statement', 1)]))])])])
Internal Server Error: /statements/api/heatmap/1
Traceback (most recent call last):
File "C:\Users\anton\OneDrive\Documents\django\karate-project-2.2\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\anton\OneDrive\Documents\django\karate-project-2.2\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\anton\OneDrive\Documents\django\karate-project-2.2\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\anton\OneDrive\Documents\django\karate-project-2.2\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\anton\OneDrive\Documents\django\karate-project-2.2\venv\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\anton\OneDrive\Documents\django\karate-project-2.2\venv\lib\site-packages\rest_framework\views.py", line 507, in dispatch
self.response = self.finalize_response(request, response, *args, **kwargs)
File "C:\Users\anton\OneDrive\Documents\django\karate-project-2.2\venv\lib\site-packages\rest_framework\views.py", line 419, in finalize_response
assert isinstance(response, HttpResponseBase), (
AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'statements.models.Response'>`
[15/Apr/2020 21:55:04] "GET /statements/api/heatmap/1 HTTP/1.1" 500 89414
Serializer is waiting for data from you. I got the same error when I tried your view with a simple modeling. I think there is something wrong with the definition. can you try the presentation:
def get(self, request):
final = Response.objects.all()
serializer = ResponseHeatmapSerializer(data=final, many=True)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
EDITED:
Please excuse me because of my sleeplessness.
The BIG problem here is the name of the table: Response. You have to change the name; somehow it conflicts with the 'Response' that the RestAPI uses.
Change Response(model.Model)'s name to different name.
python manage.py makemigrations
python manage.py migrate
and the view is ready to run (I changed the model name to 'Strawberry':
class ResponseHeatmapList(APIView):
def get(self, request):
final = Strawberry.objects.all()
serializer = ResponseHeatmapSerializer(final, many=True)
return Response(serializer.data)
class ResponseHeatmapDetail(APIView):
def get_object(self, pk):
try:
return Strawberry.objects.get(pk=pk)
except Strawberry.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
final = self.get_object(pk)
serializer = ResponseHeatmapSerializer(final)
return Response(serializer.data)

ValueError - didn't return an HttpResponse object. - In Delete View Django

I am getting ValueError while deleting a user
Error -
ValueError at /employee/delete/31/
The view apps.employee.views.EmployeeDeleteView didn't return an HttpResponse
object. It returned None instead.
class EmployeeDeleteView(LoginRequiredMixin, generic.DeleteView):
model = User
template_name = 'employee/employee_confirm_delete.html'
context_object_name='employees'
def get(self, request, *args, **kwargs):
# Tab Opts Checking
if request.user.userprofile.user_company.company_tab_opts:
return redirect('admin_employee')
def delete(self, request, *args, **kwargs):
self.object = self.get_object()
self.object.userprofile.soft_delete()
messages.success(request, 'Employee Deleted Successfully.')
return HttpResponseRedirect(reverse('admin_employee'))
This is the traceback of the error
Internal Server Error: /employee/delete/31/
Traceback (most recent call last):
File "/home/.virtualenvs/apollo_django-njoxc1BQ/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/.virtualenvs/apollo_django-njoxc1BQ/lib/python3.5/site-packages/django/core/handlers/base.py", line 137, in _get_response
"returned None instead." % (callback.__module__, view_name)
ValueError: The view apps.employee.views.EmployeeDeleteView didn't return an HttpResponse object. It returned None instead.
Here what i did. But don't know is it right approach
class EmployeeDeleteView(LoginRequiredMixin, generic.DeleteView):
model = User
template_name = 'employee/employee_confirm_delete.html'
context_object_name='employees'
def delete(self, request, *args, **kwargs):
# Tab Opts Checking
if request.user.userprofile.user_company.company_tab_opts:
return redirect('admin_employee')
self.object = self.get_object()
self.object.userprofile.soft_delete()
messages.success(request, 'Employee Deleted Successfully.')
return HttpResponseRedirect(reverse('admin_employee'))

Generic detail viewResult must be called with either an object pk or a slug

I got this error shown as title. According to document, I added "slug_url_kwarg = 'result'", (result is the app name). It doesn't work, then I added "def get_object(self):", it returns the error as "id is a KeyError"
The database it has created by itself a primary ket:"id", so I used this "id" as slug_field. Is this correct?
Do you think if it is necessary for me to use UpdateView? I want the html to display a result after submiting the form(using ajax)?
Thans in advance for your reply.
url
url(r'^result_list/$',ResultView.as_view(),name='result'),
views.py
class ResultView(UpdateView):
context_object_name = 'result_list'
template_name = 'result_list.html'
form_class = InputForm
slug_field = 'result.id' ---here means the pk,right?
slug_url_kwarg = 'result'
def get_queryset(self):
return Result.objects.all()
def post(self, request, *args, **kwargs):
form = InputForm(request.POST)
if form.is_valid():
if self.request.is_ajax():
company = form.cleaned_data['company']
region = form.cleaned_data['region']
queryset=Result.objects.filter(region=region)
return HttpResponse(simplejson.dumps(to_json),mimetype='application/json')
else:
return HttpResponse(form.errors)
def get_context_data(self, **kwargs):
context = super(ResultView, self).get_context_data(**kwargs)
context["sales"] = self.get_queryset().aggregate(Sum('sales'))
def get_object(self):
object = get_object_or_404(Result,id=self.kwargs['id']) <!here is not correct--->
return object
traceback
File "C:\Python27\lib\site-packages\django-1.8.3-py2.7.egg\django\core\handlers\base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django-1.8.3-py2.7.egg\django\views\generic\base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django-1.8.3-py2.7.egg\django\views\generic\base.py" in dispatch
89. return handler(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django-1.8.3-py2.7.egg\django\views\generic\edit.py" in get
267. self.object = self.get_object()
File "C:\Users\user\Desktop\project\result\views.py" in get_object
54. object = get_object_or_404(Result,id=self.kwargs['id'])
Exception Type: KeyError at /result_list/
Exception Value: 'id'
You forgot to map the url pattern, you don't need to specify slug_field and slug_url_kwarg in your case:
url(r'^dupont_list/(?P<pk>[0-9]+)/$', DupontView.as_view(), name='dupont'),

AttributeError at /Follow/ 'function' object has no attribute 'objects'

I'm trying to create a function that list all the people who are following a particular user but I keep encountering this error which I can't seem to solve . Can someone give me a hand please :)
error
AttributeError at /Follow/
'function' object has no attribute 'objects'
Request Method: GET
Request URL: http://127.0.0.1:8000/Follow/
Django Version: 1.5.1
Exception Type: AttributeError
Exception Value:
'function' object has no attribute 'objects'
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\endless_pagination\decorators.py" in decorated
35. return view(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
25. return view_func(request, *args, **kwargs)
"C:\mysite\pet\views.py" in Followings
97. followers = Follow.objects.followers(user)
Exception Type: AttributeError at /Follow/
Exception Value: 'function' object has no attribute 'objects'
models
class Follow(models.Model):
""" Model to represent Following relationships """
follower = models.ForeignKey(AUTH_USER_MODEL, related_name='following')
followee = models.ForeignKey(AUTH_USER_MODEL, related_name='followers')
created = models.DateTimeField(default=timezone.now)
objects = FollowingManager()
class Meta:
verbose_name = _('Following Relationship')
verbose_name_plural = _('Following Relationships')
unique_together = ('follower', 'followee')
def __unicode__(self):
return "User #%d follows #%d" % (self.follower_id, self.followee_id)
def save(self, *args, **kwargs):
# Ensure users can't be friends with themselves
if self.follower == self.followee:
raise ValidationError("Users cannot follow themselves.")
super(Follow, self).save(*args, **kwargs)
class Person(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=30, blank=True)
def __unicode__(self):
return self.user.username
views
#page_template('pagination.html')
#login_required
def Followings(request,template='following.html', extra_context=None):
followers = Follow.objects.followers(user)
person = Person.objects.filter(user__in=followers)
context = {
'page_template': 'pagination.html',
'person' :Person.objects.filter(user__in=followers),
}
extra_context = {'person':person,}
if extra_context is not None:
context.update(extra_context)
return render_to_response(
template, context, context_instance=RequestContext(request))
url
url(
r'^Follow/$',
'pet.views.Followings',
name= 'Followings',
),
change
followers = Follow.objects.followers(user)
to
followers = request.user.followers.all()

Django REST framework: help on object level permission

Following this tutorial:
http://django-rest-framework.org/tutorial/1-serialization.html
through http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html
I have this code:
# models.py
class Message(BaseDate):
"""
Private Message Model
Handles private messages between users
"""
status = models.SmallIntegerField(_('status'), choices=choicify(MESSAGE_STATUS))
from_user = models.ForeignKey(User, verbose_name=_('from'), related_name='messages_sent')
to_user = models.ForeignKey(User, verbose_name=_('to'), related_name='messages_received')
text = models.TextField(_('text'))
viewed_on = models.DateTimeField(_('viewed on'), blank=True, null=True)
# serialisers.py
class MessageSerializer(serializers.ModelSerializer):
from_user = serializers.Field(source='from_user.username')
to_user = serializers.Field(source='to_user.username')
class Meta:
model = Message
fields = ('id', 'status', 'from_user', 'to_user', 'text', 'viewed_on')
# views.py
from permissions import IsOwner
class MessageDetail(generics.RetrieveUpdateDestroyAPIView):
model = Message
serializer_class = MessageSerializer
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (permissions.IsAuthenticated, IsOwner)
# permissions.py
class IsOwner(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit or delete it.
"""
def has_permission(self, request, view, obj=None):
# Write permissions are only allowed to the owner of the snippet
return obj.from_user == request.user
# urls.py
urlpatterns = patterns('',
url(r'^messages/(?P<pk>[0-9]+)/$', MessageDetail.as_view(), name='api_message_detail'),
)
Then opening the URL of the API i get this error:
**AttributeError at /api/v1/messages/1/
'NoneType' object has no attribute 'from_user'**
Traceback:
File "/var/www/sharigo/python/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/var/www/sharigo/python/lib/python2.6/site-packages/django/views/generic/base.py" in view
48. return self.dispatch(request, *args, **kwargs)
File "/var/www/sharigo/python/lib/python2.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
77. return view_func(*args, **kwargs)
File "/var/www/sharigo/python/lib/python2.6/site-packages/rest_framework/views.py" in dispatch
363. response = self.handle_exception(exc)
File "/var/www/sharigo/python/lib/python2.6/site-packages/rest_framework/views.py" in dispatch
351. self.initial(request, *args, **kwargs)
File "/var/www/sharigo/python/lib/python2.6/site-packages/rest_framework/views.py" in initial
287. if not self.has_permission(request):
File "/var/www/sharigo/python/lib/python2.6/site-packages/rest_framework/views.py" in has_permission
254. if not permission.has_permission(request, self, obj):
File "/var/www/sharigo/sharigo/apps/sociable/permissions.py" in has_permission
17. return obj.from_user == request.user
Exception Type: AttributeError at /api/v1/messages/1/
Exception Value: 'NoneType' object has no attribute 'from_user'
It seems like None is being passed as the value for the parameter "obj" to isOwner.has_permission().
What am I doing wrong? I think i followed strictly the tutorial.
When has_permission() is called with obj=None it's supposed to return whether the user has permission to any object of this type. So you should handle the case when None is passed.
Your code should be something like:
def has_permission(self, request, view, obj=None):
# Write permissions are only allowed to the owner of the snippet
return obj is None or obj.from_user == request.user
Use function has_object_permission instead of has_permission.
ex:
def has_object_permission(self, request, view, obj=None):
return obj.from_user == request.user
and call function check_object_permissions inside get_object in views
def get_object(self):
obj = get_object_or_404(self.get_queryset())
self.check_object_permissions(self.request, obj)
return obj