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

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()

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)

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

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'))

'invalid_choice' in field foreing key django

I have a problem with a foreing key field that I initialize with a queryset, the form is displayed but at the time of sending data the error 'in to_python raise ValidationError (self.error_messages [' invalid_choice '], code =' invalid_choice ')' appears' .
I know there is a way to invalidate the 'to_python' method but I still can not get it to work. I would appreciate any help.
My view:
class PlanesCreate(generic.CreateView):
model= Plan_Estudios
template_name= 'ControlEscolar/Administracion/planes/planes_form.html'
form_class= PlanForm
success_url = reverse_lazy('ControlEscolar:planes_filtro')
def get_form_kwargs(self):
kwargs = super(PlanesCreate, self).get_form_kwargs()
kwargs.update({'programa': self.request.session['programa']})
return kwargs
My form:
class PlanForm(forms.ModelForm):
class Meta:
model = Plan_Estudios
fields = "__all__"
widgets = {
'nombreplan': forms.TextInput(attrs={'class':'form-control'}),
'programa': forms.Select(attrs={'class':'form-control'}),
}
def __init__(self, *args, **kwargs):
p=kwargs.pop('programa', None)
super(PlanForm, self).__init__(*args, **kwargs)
query=Programa_Academico.objects.filter(pk=p)
self.fields['programa'].queryset=query #Inicialize field with query
My model:
class Plan_Estudios(models.Model):
nombreplan= models.CharField(max_length=30)
programa= models.ForeignKey(Programa_Academico, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.nombreplan
class Programa_Academico(models.Model):
nombreP= models.CharField(max_length=50)
siglas= models.CharField(max_length=10)
def __str__(self):
return self.siglas
Error:
File "C:\Users\Envs\py1\lib\site-packages\django\forms\forms.py" in is_valid
185. return self.is_bound and not self.errors
File "C:\Users\Envs\py1\lib\site-packages\django\forms\forms.py" in errors
180. self.full_clean()
File "C:\Users\Envs\py1\lib\site-packages\django\forms\forms.py" in full_clean
381. self._clean_fields()
File "C:\Users\Envs\py1\lib\site-packages\django\forms\forms.py" in _clean_fields
399. value = field.clean(value)
File "C:\Users\Envs\py1\lib\site-packages\django\forms\fields.py" in clean
147. value = self.to_python(value)
File "C:\Users\Envs\py1\lib\site-packages\django\forms\models.py" in to_python
1252.
raise ValidationError(self.error_messages['invalid_choice'],
code='invalid_choice')
Exception Type: KeyError at /ControlEscolar/planes/crear
Exception Value: 'invalid_choice'

Django ModelForm Inheritance with request.user results in TypeError on __init__

Trying to inherit ModelForm to create a BaseForm to update created_by, modified_by fields in model.
My BaseForm is as
class BaseForm(ModelForm):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('request', None).user
super(BaseForm, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
kwargs['commit']=False
obj = super(BaseForm, self).save(*args, **kwargs)
if self.user:
obj.modified_by = self.user.username
obj.save()
return obj
Child Form is as
class InviteForm(BaseForm):
class Meta:
model = UserInvitation
and I am passing the request in child form through view
form = InviteForm(instance=instance,request=request)
however it gives error
TypeError at /accounts/invitation/
__init__() got an unexpected keyword argument 'request'
The error is not there if I do not inherit the BaseForm and write the code in child form i.e. InviteForm.
Please advise what I am doing wrong, I do not want to repeat the code in each form.
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\django\contrib\auth\decorators.py" in _wrapped_view
25. return view_func(request, *args, **kwargs)
File "C:\Python27\Lib\site-packages\django\bin\mysite\userplus\views.py" in invitation
87. form = InviteForm(instance=instance,request=request)
Exception Type: TypeError at /accounts/invitation/
Exception Value: __init__() got an unexpected keyword argument 'request'
To update the modified_by field that you have in your UserInvitation model, you should exclude it from being shown in the form:
class BaseForm(ModelForm):
...
class InviteForm(BaseForm):
class Meta:
model = UserInvitation
exclude = ('modified_by',)
Then in your view
form = InviteForm(request.POST, instance=instance)
if form.is_valid():
invite = form.save(commit=false)
invite.modified_by = request.user
invite.save()
That way the user making the request is used.
Alternatively, you can set the user beforehand:
# views.py
instance = Invite(modified_by=request.user)
form = InviteForm(request.POST, instance=instance)
...

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