I'm trying to make a follower system using django and have come accross this issue can someone please help me with it, or give me some suggestions regarding making a follower system with django.
the traceback is as following
Traceback:
File "C:\Users\Mustafa
Lakhani\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py"
in inner
34. response = get_response(request)
File "C:\Users\Mustafa
Lakhani\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py"
in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "C:\Users\Mustafa
Lakhani\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py"
in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Mustafa
Lakhani\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py"
in view
68. return self.dispatch(request, *args, **kwargs)
File "C:\Users\Mustafa
Lakhani\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py"
in dispatch
88. return handler(request, *args, **kwargs)
File "D:\sb\blog\views.py" in get
186. if request.user.is_authenticated():
Exception Type: TypeError at /user/mustafalakhani/follow Exception
Value: 'bool' object is not callable
the code is given below
models.py
class Profile(models.Model):
user=models.OneToOneField(User, on_delete=models.CASCADE)
image=models.ImageField(default='default.jpg',upload_to='profile_pics',blank=True)
description=models.TextField(max_length=200, blank=True)
following = models.ManyToManyField(User, related_name='followed_by', blank=True)
def __str__(self):
return f'{self.user.username} Profile'
def saveimg(self):
super().save()
img=Image.open(self.image.path)
if img.height>300 or img.width>300:
output_size=(300,300)
img.thumbnail(output_size)
img.saveimg(self.image.path)
views.py
class UserFollowView(View):
def get(self, request, username, *args, **kwargs):
toggle_user=get_object_or_404(User,username__iexact=username)
if request.user.is_authenticated():
user_profile, created=Profile.objects.get_or_create(request.user)
if toggle_user in user_profile.following.all():
user_profile.following.remove(toggle_user)
else:
user_profile.following.add(toggle_user)
return HttpResponseRedirect(home)
urls.py
path('user/<str:username>/follow', UserFollowView.as_view(),name='follow_user'),
In Django 2, user.is_authenticated is an attribute, so you you need to drop the ()
request.user.is_authenticated
user.is_authenticated is a boolean. That it means it can either be True or False. As it is not a function, nothing is returned when you attempt to call it.
Simply remove the parentheses that indicate that you'd like to call it:
if request.user.is_authenticated:
Related
I have been trying to solve this circular import issue in order to implement unit testing without failure. If I may show you the short version of the previous solution I got:
This....
serializer_class = serializers.CompanyMappingSerializer
should be changed to This:
serializer_class = "serializers.CompanyMappingSerializer"
After doing this, the unit tests run fine. However, when I run the api with POSTMAN, it shows this error:
TypeError at /api/v1/company/
'str' object is not callable
What should I do in this situation?
P.S.:
For more information here is the full traceback:
Traceback:
File "/Users/nick/myvenv/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/Users/nick/myvenv/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "/Users/nick/myvenv/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/nick/myvenv/lib/python3.8/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/Users/nick/myvenv/lib/python3.8/site-packages/rest_framework/viewsets.py" in view
114. return self.dispatch(request, *args, **kwargs)
File "/Users/nick/myvenv/lib/python3.8/site-packages/rest_framework/views.py" in dispatch
505. response = self.handle_exception(exc)
File "/Users/nick/myvenv/lib/python3.8/site-packages/rest_framework/views.py" in handle_exception
465. self.raise_uncaught_exception(exc)
File "/Users/nick/myvenv/lib/python3.8/site-packages/rest_framework/views.py" in raise_uncaught_exception
476. raise exc
File "/Users/nick/myvenv/lib/python3.8/site-packages/rest_framework/views.py" in dispatch
502. response = handler(request, *args, **kwargs)
File "/Users/nick/work/shiftwork_backend/api/views/company.py" in list
74. serializer = self.get_serializer(page, many=True)
File "/Users/nick/myvenv/lib/python3.8/site-packages/rest_framework/generics.py" in get_serializer
110. return serializer_class(*args, **kwargs)
Exception Type: TypeError at /api/v1/company/
Exception Value: 'str' object is not callable
and below is the more detailed version of api/company.py
...
...
from api.models import Company, Pattern, UserCompany, CompanyMapping, Category, COUNTRY_CODE_CHOICES
from statistics.models import CompanySearch
# from api.serializers import CompanySerializer, PatternSerializer, UserCompanySerializer, CompanyMappingSerializer, CategorySerializer
from api import serializers
from api.views import get_user_company_by_local_id, get_user_pattern_by_local_id
...
...
class CompanyMappingViewSet(viewsets.ModelViewSet):
queryset = CompanyMapping.objects.all()
serializer_class = serializers.CompanyMappingSerializer
permission_classes = (IsAuthenticated,)
The error is because you have defined the serializer_class attribute as string rather than a class.
Thus it should be as
class CompanyMappingViewSet(viewsets.ModelViewSet):
queryset = CompanyMapping.objects.all()
serializer_class = serializers.CompanyMappingSerializer
permission_classes = (IsAuthenticated,)
If you want to omit the circular import issue, you can make use of the get_serializer_class(...) method as,
class CompanyMappingViewSet(viewsets.ModelViewSet):
queryset = CompanyMapping.objects.all()
serializer_class = serializers.CompanyMappingSerializer
permission_classes = (IsAuthenticated,)
def get_serializer_class(self):
from api.serializers import CompanyMappingSerializer
return CompanyMappingSerializer
I don't know if this a best solution but if you can't do something to break the circular loop you can override your serializer's get_serializer_class and add your imports in that method like:
class CompanyMappingViewSet(viewsets.ModelViewSet):
queryset = CompanyMapping.objects.all()
permission_classes = (IsAuthenticated,)
def get_serializer_class(self):
from api.serializer import CompanyMappingSerializer
return CompanyMappingSerializer
And this should prevent from circular import happening.
I am trying to parse hashtags from title field and save to tags field with a post_save signal in django. I am using django-taggit package for tags but getting this error while saving the form.save_m2m. Can someone help to solve this error?
this is the link to the package: https://django-taggit.readthedocs.io/en/latest/getting_started.html
signal.py
def parse_hash_tags(sender, instance, created, **kwargs):
post_save.disconnect(parse_hash_tags, sender=Post)
instance.tags = ','.join(re.findall(r'(?:#(\w+))', instance.title))
instance.save()
post_save.connect(parse_hash_tags, sender=Post)
post_save.connect(parse_hash_tags, sender=Post)
traceback
Traceback:
File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\mixins.py" in dispatch
52. return super().dispatch(request, *args, **kwargs)
File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py" in dispatch
97. return handler(request, *args, **kwargs)
File "C:\danny\Study\test\posts\views.py" in post
231. form.save_m2m()
File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\forms\models.py" in _save_m2m
441. f.save_form_data(self.instance, cleaned_data[f.name])
File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\taggit\managers.py" in save_form_data
517. getattr(instance, self.name).set(*value)
Exception Type: AttributeError at /posts/create/
Exception Value: 'str' object has no attribute 'set'
You can not use a comma separated list as value for a many-to-many relation. You can however make a list of tags, and then use the .set(…) method [readthedocs]:
def parse_hash_tags(sender, instance, created, **kwargs):
tags = re.findall(r'(?:#(\w+))', instance.title)
instance.tags.set(*tags)
post_save.connect(parse_hash_tags, sender=Post)
Setting a many-to-many relation does not trigger saving the instance itself, so there is no need to call instance.save() either and disconnecting/reconnecting. Disconnecting is also a bit "tricky" since another model object that is modified concurrently could then no longer trigger the signal.
I have never had any problems with it previously but when I clicked on it just then, it did not do anything. However my login works fine.
I'm running a custom signup class (so I can include google recaptcha) - this has already been tried and tested to work:
class AllauthSignupForm(forms.Form):
captcha = ReCaptchaField()
class Meta:
model = User
def signup(self, request, user):
""" Required, or else it throws deprecation warnings """
pass
I believe I may have altered the source code in django-allauth/blob/master/allauth/account/forms.py however I can't figure out what I changed. So I tried copy pasting the whole forms.py on github to my forms.py, and that returned this error:
Traceback:
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/zorgan/Desktop/vorsso/venvor/draft1/views.py" in boxes_view
116. return render(request, 'boxes.html', context)
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/shortcuts.py" in render
30. content = loader.render_to_string(template_name, context, request, using=using)
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/template/loader.py" in render_to_string
68. return template.render(context, request)
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/template/backends/django.py" in render
66. return self.template.render(context)
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/template/base.py" in render
205. with context.bind_template(self):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/contextlib.py" in __enter__
59. return next(self.gen)
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/template/context.py" in bind_template
263. updates.update(processor(self.request))
File "/Users/zorgan/Desktop/project/app/draft1/processors.py" in everywhere
12. allauth_signup = SignupForm(request.POST or None)
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/allauth/account/forms.py" in __init__
364. super(SignupForm, self).__init__(*args, **kwargs)
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/allauth/account/forms.py" in __init__
321. getattr(self, 'field_order', None) or default_field_order)
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/allauth/utils.py" in set_form_field_order
252. for f in fields_order)
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/allauth/utils.py" in <genexpr>
252. for f in fields_order)
Exception Type: KeyError at /news/
Exception Value: 'email2'
so I believe I may have tampered something with email2.
Any idea what the problem is?
EDIT
Ok when I remove captcha = ReCaptchaField() from my custom form the register works. Any idea why?
EDIT2
So it seems it works on chrome but not firefox. Some problem with google recaptcha not working on firefox.
Python 3.6.5 & Django 1.11
Pseudo explanation:
Two Models, with model2 using model1 as a ForeignKey
Admin for model1 uses an inline for model2
On model1, I want to get a shortened URL and store that in a property when there is a new entry. To do that, model1 has to be saved because the long URL (the one I want to shorten) is based on Autoslug.
Relevant portion of Models.py
class Model1(models.Model):
name = models.CharField(max_length=100)
slug = AutoSlugField(populate_from='name', unique=True,
null=True, default=None)
class Model2(models.Model):
owner = models.ForeignKey(
'Model1',
on_delete=models.CASCADE,
)
This is my signal...
#receiver(post_save, sender=Model1)
def shorten_url(sender, instance, created, **kwargs):
if created:
if not instance.short_url:
url_short = url_shorten(instance.get_absolute_url())
instance.short_url = url_short
post_save.disconnect(shorten_url, sender=sender)
instance.save()
post_save.connect(shorten_url, sender=sender)
return instance
else:
post_save.disconnect(shorten_url, sender=sender)
instance.save()
post_save.connect(shorten_url, sender=sender)
return instance
The disconnect, connect is to prevent loops, I'm not 100% sure that it is correct yet either, but without it, I see calls to shorten the url over and over...
The issue I'm trying to solve now is that I get the error
save() prohibited to prevent data loss to unsaved related object 'model1' when I am calling save().
Here is the traceback:
File "/home/username/.virtualenvs/project/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/home/username/.virtualenvs/project/lib/python3.6/site-packages/django/core/handlers/base.py" in _legacy_get_response
249. response = self._get_response(request)
File "/home/username/.virtualenvs/project/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/username/.virtualenvs/project/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/username/.virtualenvs/project/lib/python3.6/site-packages/django/contrib/admin/options.py" in wrapper
551. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/username/.virtualenvs/project/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/home/username/.virtualenvs/project/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "/home/username/.virtualenvs/project/lib/python3.6/site-packages/django/contrib/admin/sites.py" in inner
224. return view(request, *args, **kwargs)
File "/home/username/.virtualenvs/project/lib/python3.6/site-packages/django/contrib/admin/options.py" in add_view
1508. return self.changeform_view(request, None, form_url, extra_context)
File "/home/username/.virtualenvs/project/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper
67. return bound_func(*args, **kwargs)
File "/home/username/.virtualenvs/project/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/home/username/.virtualenvs/project/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func
63. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/username/.virtualenvs/project/lib/python3.6/site-packages/django/contrib/admin/options.py" in changeform_view
1408. return self._changeform_view(request, object_id, form_url, extra_context)
File "/home/username/.virtualenvs/project/lib/python3.6/site-packages/django/contrib/admin/options.py" in _changeform_view
1449. self.save_related(request, form, formsets, not add)
File "/home/username/.virtualenvs/project/lib/python3.6/site-packages/django/contrib/admin/options.py" in save_related
1003. self.save_formset(request, form, formset, change=change)
File "/home/username/.virtualenvs/project/lib/python3.6/site-packages/django/contrib/admin/options.py" in save_formset
991. formset.save()
File "/home/username/.virtualenvs/project/lib/python3.6/site-packages/django/forms/models.py" in save
649. return self.save_existing_objects(commit) + self.save_new_objects(commit)
File "/home/username/.virtualenvs/project/lib/python3.6/site-packages/django/forms/models.py" in save_new_objects
783. self.new_objects.append(self.save_new(form, commit=commit))
File "/home/username/.virtualenvs/project/lib/python3.6/site-packages/django/forms/models.py" in save_new
927. obj.save()
File "/home/username/.virtualenvs/project/lib/python3.6/site-packages/django/db/models/base.py" in save
762. "unsaved related object '%s'." % field.name
Exception Type: ValueError at /admin/wa/model1/add/
Exception Value: save() prohibited to prevent data loss due to unsaved related object 'model1'.
I assume that this is because I'm post_save on model1 and I have model2 rows waiting for a model1 key the error isn't saying that. If the error said model2 that would make more sense to me, but it doesn't.
In looking at base.py line 762 which is raising the error, it also appears to be handling this case of an unsaved (no PK) object but again.. I'm post_save here aren't I?
Another Update
In attempting to break this problem down further, I submitted the admin form with no data in the inline form section (i.e. no data in Model2). When I do this, I get two entries in Model1 each with NO PK... PK==None. wow.
Thanks for the help!
For the future...
The key point to note was when I discovered that the ID was not being generated and if you hit that you should think... what else has changed recently.
In my case, a few days ago on my dev box I had changed from SQLITE3 to PostgreSQL in anticipation of doing the same in production. However, my procedure was flawed and what happed was I had a perfectly working READ database, but none of the IDs were autogenerating on write.
In my case I had used PGLOADER to load the data. Do not do that.
Use the Django tools to dumpdata and loaddata.
Problem :
I am getting an error like this :
Traceback:
File
"/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py"
in inner
41. response = get_response(request)
File
"/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py"
in _get_response
187. response = self.process_exception_by_middleware(e, request)
File
"/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py"
in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File
"/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py"
in wrapped_view
58. return view_func(*args, **kwargs)
File
"/usr/local/lib/python2.7/dist-packages/rest_framework/viewsets.py" in
view
87. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py"
in dispatch
474. response = self.handle_exception(exc)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py"
in handle_exception
434. self.raise_uncaught_exception(exc)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py"
in dispatch
471. response = handler(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/mixins.py"
in list
42. page = self.paginate_queryset(queryset)
File
"/usr/local/lib/python2.7/dist-packages/rest_framework/generics.py" in
paginate_queryset
172. return self.paginator.paginate_queryset(queryset, self.request, view=self)
File
"/usr/local/lib/python2.7/dist-packages/rest_framework/pagination.py"
in paginate_queryset
311. self.count = _get_count(queryset)
File
"/usr/local/lib/python2.7/dist-packages/rest_framework/pagination.py"
in _get_count
54. return len(queryset)
Exception Type: TypeError at /api/userprofiles/ Exception Value:
object of type 'NoneType' has no len()
What I am trying to do :
I just want people to get their own profile, when they connect to the api, so instead of applying UserProfile.objects.all , I thought it would be better if I used UserProfile.objects.get(user=request.user).
But as you can well see it isn't working, perhaps because pagination has some problem cause it is trying to get len() but the object it's getting is NoneType although I printed the queryset just after it's fetched so as to determine whether it really is NoneType , but it isn't.
Here's my UserProfileViewSet :
class UserProfileViewSet(viewsets.ModelViewSet):
"""
This viewset automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
"""
# queryset = UserProfile.objects.all(user=request.user)
serializer_class = UserProfileSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly,)
pagination_class = LimitTenPagination
def get_queryset(self):
try:
queryset = self.request.user.profile.all() # UserProfile.objects.get(user=self.request.user)
print queryset
except:
queryset = None
return queryset # UserProfile.objects.get(user=self.request.user)
#detail_route(renderer_classes=[renderers.JSONRenderer])
def perform_create(self, serializer):
serializer.save(user=self.request.user)
Answer ( got it almost instantly )
Well, when I was using UserProfile.objects.get(user=self.request.user) I was getting an object , instead what I needed to get was a queryset.
So changed the queryset to queryset = UserProfile.objects.filter(user=self.request.user)