AttributeError at /notify/notify/ 'UserNotifications' object has no attribute 'user' - python

I am trying to make a notifications app. I have a middle that collects info about the action the user should be notified about and in the view that handles the action it automatically creates an instance in the UserNotification model. This is all working. Now, if a user's post gets liked by another user, that actions needs to be displayed on the notifications page. However, I obviously don't want any one use to be able to see every notification that is being created on the site, but rather only the notifications that are created by their posts.
I am running into an issue with the view and filtering the notifications based on the current user. More specifically, I am getting this error:
AttributeError at /notify/notify/
'UserNotifications' object has no attribute 'user'
With traceback:
Traceback (most recent call last):
File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/contrib/auth/mixins.py", line 56, in dispatch
return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/views/generic/base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/views/generic/list.py", line 160, in get
self.object_list = self.get_queryset()
File "/Users/garrettlove/Desktop/evverest/notify/views.py", line 30, in get_queryset
return UserNotification.objects.filter(user=request.user)
Here is my view pertaining to this:
// Bunch of imports are all here
User = get_user_model()
class UserNotifications(LoginRequiredMixin,ListView):
login_url = 'account_login'
model = UserNotification
template_name = 'notify/usernotification_list.html'
context_object_name = 'notifies'
paginate_by = 25
def get_queryset(request):
return UserNotification.objects.filter(user=request.user)
Here is my UserNotification model:
from django.db import models
from django.contrib.auth import get_user_model
from django.db.models.signals import post_save
from django.dispatch import receiver
User = get_user_model()
# Create your models here.
class UserNotification(models.Model):
user = models.ForeignKey(User,related_name='user',null=True)
post = models.ForeignKey('feed.UserPost',related_name='post')
timestamp = models.DateTimeField(auto_now_add=True)
notify_type = models.CharField(max_length=6)
read = models.BooleanField(default=False)
def __str__(self):
return str(self.user)

def get_queryset(self):
return UserNotification.objects.filter(user=self.request.user)

Related

Django genecric.FormView: 'NoneType' object is not callable

I'm trying to render a really basic FormView but it says it can't get the form model. Full error:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
response = get_response(request)
File "/usr/local/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.10/site-packages/django/views/generic/base.py", line 103, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/django/views/generic/base.py", line 142, in dispatch
return handler(request, *args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/django/views/generic/edit.py", line 144, in get
return self.render_to_response(self.get_context_data())
File "/usr/local/lib/python3.10/site-packages/django/views/generic/edit.py", line 74, in get_context_data
kwargs["form"] = self.get_form()
File "/usr/local/lib/python3.10/site-packages/django/views/generic/edit.py", line 39, in get_form
return form_class(**self.get_form_kwargs())
Exception Type: TypeError at /new-game/
Exception Value: 'NoneType' object is not callable
Form:
class NewGameForm(ModelForm):
class Meta:
model = models.Game
fields = ['title', 'bank_money', 'player_starting_money', 'golden_card_amount']
View:
class NewGameView(generic.FormView):
template_name = 'games/create_game.html'
form = forms.NewGameForm
Note that django development server is running on a linux docker container with python 3.10.7
The form class of a FormView is given by the form_class class attribute, not form.
class NewGameView(generic.FormView):
template_name = 'games/create_game.html'
form_class = forms.NewGameForm
See Form handling with class-based views

(Django) 'CommentView' object has no attribute 'body'

I have been trying to emulate comment functionality with a decorator.
import json
import jwt
from django.views import View
from django.http import JsonResponse
from functools import wraps
from django.db.models import Q
from .models import Comment
from account.models import Account
class CommentView(View):
def login_required(func):
#wraps(func)
def wrapper(request, *args, **kwargs):
# import pdb; pdb.set_trace()
given_token = json.loads(request.body)['access_token']
decoded_token = jwt.decode(given_token,None,None)
try:
if Account.objects.filter(username=decoded_token).exists():
return func(request, *args, **kwargs)
return JsonResponse({"message": "username does not exist"})
except KeyError:
return JsonResponse({"message": "INVALID_KEYS"}, status=403)
return wrapper
#login_required
def post(self, request):
print("request ", json.loads(request.body))
data = json.loads(request.body)
Comment.objects.create(
username = jwt.decode(json.loads(request.body)['access_token']),
content = data['content'],
)
return JsonResponse({"message":"Comment Created!"}, status=200)
def get(self, request):
return JsonResponse({'comment':list(Comment.objects.values())}, status=200)
And I used the program called Httpie to give JSON POST request like so:
http -v http://127.0.0.1:8000/comment access_token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImJlY2sifQ.2unop67pLHOshcGs385GwOvaZZW_J--TRNXyHI3gKNU" content="hello"
There is no problem with the token since this is the exact copy of the token give during the SignInView(which is in another app).
Below is the models.py file in the 'comment' app.
from django.db import models
from account.models import Account
class Comment(models.Model):
username = models.ForeignKey(Account, on_delete=models.CASCADE)
content = models.TextField()
created_time= models.DateTimeField(auto_now_add = True)
updated_time= models.DateTimeField(auto_now = True)
class Meta:
db_table = 'comments'
def __str__(self):
return self.username + ": " + self.content
However, when I send the POST request with the Httpie like above, I get this error:
Internal Server Error: /comment
Traceback (most recent call last):
File "/Users/woohyunan/miniconda3/auth/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Users/woohyunan/miniconda3/auth/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/woohyunan/miniconda3/auth/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/woohyunan/miniconda3/auth/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/woohyunan/miniconda3/auth/lib/python3.8/site-packages/django/views/generic/base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "/Users/woohyunan/projects/Wecode/westagram/KillaGramz-backend/comment/views.py", line 19, in wrapper
given_token = json.loads(request.body)['access_token']
AttributeError: 'CommentView' object has no attribute 'body'
[20/May/2020 17:35:40] "POST /comment HTTP/1.1" 500 73224
I have been wondering what would cause the error. I wonder if there is no way to put the json request body into the decorator which would allow me to decode the token(the decoded version will be the username) so that I can see if it matches with the username in the database.
Thank you so much!!
I solved the problem!
def wrapper(request, *args, **kwargs):
needs to be
def wrapper(self, request, *args, **kwargs):

AttributeError: 'property' object has no attribute 'copy' - while trying to get object list in Django Rest

To practice my Django skills i try to make simple module that should work more or less like Admin site in Django. It should gather all Models from Application, list them and show every object from each Model. i try to do is using Django Rest Framework.
Here is my views.py. I have 2 views. The api_root listens all models but it also sends params-models_names to another view 'model_view'. The ModelViewSet should list all objects from particular model.
class ModelsViewSet(viewsets.ModelViewSet):
def get_serializer(self, *args, **kwargs):
serializer_name = '{model_name}Serializer'.format(
model_name=self.kwargs.get('name').split(".")[1]
)
return getattr(serializers, serializer_name)
def get_model(self):
"""methods return model based on name kwargs
:return:
"""
return apps.get_model(self.kwargs.get('name'))
def get_queryset(self):
return self.get_model().objects.all()
def get_object(self):
return self.get_model().objects.get(pk=self.kwargs.get('pk'))
#api_view(['GET'])
def api_root(request, format=None):
return Response([reverse(
viewname='model_view',
kwargs={'name': i._meta.label}) for i in apps.get_models()])
Here is my serializers.py. In this file serializers classes are dynamically build. Each class is built on the basis of the model from django.apps.
from django.apps import apps
from rest_framework import serializers
from admin_site import serializers as m
from . import models
app_models = apps.get_models()
for item in app_models:
name = "{}Serializer".format(item.__name__)
class Meta(type):
model = item
fields = '__all__'
m.__dict__[name] = type(name, (serializers.ModelSerializer,), {})
m.__dict__[name].__metaclass__ = Meta
And finally here is my my_app.urls.py file. I think that maybe the problem is that ModelSetView isn't registered using DefaultRouter() but on the other hand i need to pass param to urlpattern. I don't know
urlpatterns = [
url(r'^$', views.api_root),
url(r'^model/(?P<name>[\w\-\.]+)/$',
views.ModelsViewSet.as_view({'get': 'list', 'put':'update'}), name='model_view'),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
Everything is fine when i'm on api_root, i can see list of models. But when i add to root url /model/auth.User/ i get this error:
Traceback (most recent call last):
File "/home/wojjak/Projects/envs/taskenvv/lib/python3.6/site-
packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/home/wojjak/Projects/envs/taskenvv/lib/python3.6/site-
packages/django/core/handlers/base.py", line 217, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/wojjak/Projects/envs/taskenvv/lib/python3.6/site-
packages/django/core/handlers/base.py", line 215, in _get_response
response = response.render()
File "/home/wojjak/Projects/envs/taskenvv/lib/python3.6/site-
packages/django/template/response.py", line 107, in render
self.content = self.rendered_content
File "/home/wojjak/Projects/envs/taskenvv/lib/python3.6/site-
packages/rest_framework/response.py", line 72, in rendered_content
ret = renderer.render(self.data, accepted_media_type, context)
File "/home/wojjak/Projects/envs/taskenvv/lib/python3.6/site-
packages/rest_framework/renderers.py", line 716, in render
context = self.get_context(data, accepted_media_type,
renderer_context)
File "/home/wojjak/Projects/envs/taskenvv/lib/python3.6/site-
packages/rest_framework/renderers.py", line 650, in get_context
raw_data_put_form = self.get_raw_data_form(data, view, 'PUT',
request)
File "/home/wojjak/Projects/envs/taskenvv/lib/python3.6/site-
packages/rest_framework/renderers.py", line 565, in get_raw_data_form
data = serializer.data.copy()
AttributeError: 'property' object has no attribute 'copy'
Any clue what can i do to accomplish my task and avoid this error?
override get_serializer_class() not get_serializer()

Where has cleaned_data vanished in Django 1.11?

I have created an inlineformset_factory as below :
formset = inlineformset_factory(Author, Book, form=BookForm,
formset=BaseBookFormSet,
can_order=False, can_delete=True,
extra=1, fields=('id', name)
)
BookForm is as below:
class BookForm(forms.ModelForm):
name = forms.Charfield(required=True)
def __init__(self, *args, **kwargs):
super(BookForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_tag = False
self.helper.layout = Layout(
Div(
Field("id", type="hidden"),
Field("name"),
Field("DELETE")
)
)
class Meta:
model = Book
fields = ('id', 'name')
def clean_name(self):
book_name = self.cleaned_data['name']
try:
book = Book.objects.get(name=book_name)
return book
except:
return book_name
def clean(self):
cleaned_data = super(BookForm, self).clean()
... other operations on cleaned_data ...
def has_changed(self):
changed = super(BookForm, self).has_changed()
cleaned_data = self.clean()
... other code here ...
This is throwing an error on submitting the form :
Exception Type: AttributeError
Exception Value: 'BookForm' object has no attribute 'cleaned_data'
when formset.is_valid() is called in views.py. Traceback first shows the line in has_changed where the self.clean is being called, and then the line in clean() where the super clean is being called.
This used to work fine in django 1.10.
When I tried printing dir(self) in Django 1.10 it does show 'cleaned_data' as one of the attributes where as in Django 1.11 it does not.
Where has the 'cleaned_data' vanished in Django 1.11?
EDIT: Adding traceback:
Traceback (most recent call last):
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
response = self._get_response(request)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/views/generic/base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "/vagrant/test_os/inventory/views.py", line 297, in post
if formset.is_valid():
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/forms/formsets.py", line 321, in is_valid
self.errors
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/forms/formsets.py", line 295, in errors
self.full_clean()
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/forms/formsets.py", line 345, in full_clean
if not form.has_changed():
File "/vagrant/test_os/inventory/forms.py", line 220, in has_changed
cleaned_data = self.clean()
File "/vagrant/test_os/inventory/forms.py", line 177, in clean
cleaned_data = super(BookForm, self).clean()
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/forms/models.py", line 344, in clean
return self.cleaned_data
AttributeError: 'BookForm' object has no attribute 'cleaned_data'
Formsets were fixed in 1.11 (in #26844) to ignore empty forms when validating the minimum number of forms. As a side-effect, formsets now call form.has_changed() on each form before validating the form. Django expects form.has_changed() to be safe to call before the form is validated, and the default implementation is indeed safe to call.
You have overridden form.has_changed() to call self.clean(), which now happens before the form is validated. Since form.clean() requires that the form is validated, this fails.
Since form.full_clean() actually calls self.has_changed(), you can't simply validate the form from within form.has_changed(). You don't show what you do in has_changed(), but it would most likely be a good idea to put this code elsewhere.

Django AssertionError at url

While learning Django rest framework, I got a AssertionError at /tasks/1 error
Expected view TaskDetail to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly.
My model.py
class Task(models.Model):
owner=models.ForeignKey('auth.User',related_name='tasks')
completed=models.BooleanField(default=False)
title=models.CharField(max_length=100)
description=models.TextField()
serializer.py
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
read_only=('owner.username',)
fields=('title','description','completed','owner.username')
permission.py
class IsOwnerOrReadOnly(BasePermission):
def has_object_permission(self, request, view, obj):
if request.method is SAFE_METHODS:
return True
return obj.owner==request.user
views.py
class TasksMixins(object):
queryset = Task.objects.all()
serializer_class=TaskSerializer
permission_classes=(IsOwnerOrReadOnly,)
def pre_save(self,obj):
obj.owner=self.request.user
class TaskList(TasksMixins,ListCreateAPIView):
pass
class TaskDetail(TasksMixins,RetrieveUpdateDestroyAPIView):
pass
Urls.py
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^tasks/$', views.TaskList.as_view(), name='task_list'),
url(r'^tasks/(?P<id>[0-9]+)$', views.TaskDetail.as_view(), name='task_detail')
]
Traceback
Traceback (most recent call last):
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/rest_framework/views.py", line 466, in dispatch
response = self.handle_exception(exc)
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/rest_framework/views.py", line 463, in dispatch
response = handler(request, *args, **kwargs)
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/rest_framework/generics.py", line 286, in get
return self.retrieve(request, *args, **kwargs)
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/rest_framework/mixins.py", line 56, in retrieve
instance = self.get_object()
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/rest_framework/generics.py", line 93, in get_object
(self.__class__.__name__, lookup_url_kwarg)
AssertionError: Expected view TaskDetail to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly.
When ever I navigate to the link I get this error
Any help is much appreciated...Thanks in advace
error image
If you want to target by 'pk', just rename id -> pk into your url.py:
url(r'^tasks/(?P<pk>[0-9]+)$', views.TaskDetail.as_view(), name='task_detail')
If you want to target by other field than pk,, you have to adjust the url.py, the view.py AND the serializer.py precising a lookup_field (that can be Nested) for example, it could be for you.
url.py:
url(r'^tasks/(?P<owner__username>[0-9]+)$', views.TaskDetail.as_view(), name='task_detail')
view.py:
class TasksMixins(object):
queryset = Task.objects.all()
serializer_class=TaskSerializer
permission_classes=(IsOwnerOrReadOnly,)
lookup_field = 'owner__username'
serializer.py
class TaskSerializer(serializers.ModelSerializer):
owner = serializers.SlugRelatedField(slug_field='username',many=False, read_only=True)
class Meta:
model = Task
fields='__all__'
lookup_field = 'owner__username'

Categories