I am getting the follwing error message the I try to open the url:
Request Method: GET
Request URL: http://localhost:8000/core/jmc/material/generate
Django Version: 1.8
Exception Type: AttributeError
Exception Value: 'bool' object has no attribute 'user'
Exception Location: /usr/local/lib/python2.7/dist-packages/django/contrib/auth/decorators.py in _wrapped_view, line 21
Also the traceback looks like this:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/decorators.py" in _wrapped_view
22. return view_func(request, *args, **kwargs)
File "/home/dev/Documents/Program Codes/Python/Django/Zeus2/core/project/jmc.py" in jmc_material_generator
168. jmc_material_generator(False)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/decorators.py" in _wrapped_view
21. if test_func(request.user):
My view is as follows:
#login_required(login_url='login')
def jmc_material_generator(request):
# Permission level check
if request.user.groups.all()[0].name not in ['Super-Admin', 'Admin']:
return redirect('index')
with transaction.atomic():
jmc_material_generator(False)
return redirect('index')
Your view function name is the same as the function being called on line 8 (jmc_material_generator(False)). This in turn is calling your view function again and passing in a boolean instead of a request object. You need to either rename your view function or rename the jmc_material_generator(False) import when you import it into the view.py file.
# you can do import x as X which renamed the imported function
from ... import jmc_material_generator as jmc_generator
#login_required(login_url='login')
def jmc_material_generator(request):
# Permission level check
if request.user.groups.all()[0].name not in ['Super-Admin', 'Admin']:
return redirect('index')
with transaction.atomic():
jmc_generator(False) # notice the rename of this function
return redirect('index')
Related
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'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:
I use Django Custom User Model. Everything works fine in Admin - login, logout etc. However when i try to call login from my own view.py:
def my_login(request, *args, **kwargs):
response = login(request, *args, **kwargs)
return response
I get the following error:
AssertionError at /cust/login/
sensitive_post_parameters didn't receive an HttpRequest. If you are decorating a classmethod, be sure to use #method_decorator.
Request Method: POST
Request URL: http://localhost:8000/cust/login/
Django Version: 1.6.1
Python Version: 2.7.3
Traceback:
File "virtual_env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "virtual_env/local/lib/python2.7/site-packages/django/views/generic/base.py" in view 69. return self.dispatch(request, *args, **kwargs)
File "virtual_env/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 57. return view_func(*args, **kwargs)
File "virtual_env/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 399.response = self.handle_exception(exc)
File "virtual_env/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 396.response = handler(request, *args, **kwargs)
File "virtual_env/local/lib/python2.7/site-packages/rest_framework/decorators.py" in handler 49.return func(*args, **kwargs)
File "virtual_env/myproject/myidentity/views.py" in my_login 13.response = login(request, *args, **kwargs)
File "virtual_env/local/lib/python2.7/site-packages/django/views/decorators/debug.py"in sensitive_post_parameters_wrapper 68."sensitive_post_parameters didn't receive an HttpRequest. If you "
Exception Type: AssertionError at /cust/login/
Exception Value: sensitive_post_parameters didn't receive an HttpRequest. If you are decorating a classmethod, be sure to use #method_decorator.
Request information:
GET: No GET data
Didn't find much reference about this issue, except this:
Django AssertionError "sensitive_post_parameters didn't receive an HttpRequest" on add users in admin
Thank you
WORKAROUND. I'm not a django expert, and very likely this is not the most healthy solution, however digging into the course of the login process i came across this Assertion command in the Django site-packages, that was blocking the code just beneath it which looks quite reasonable, after commenting the assertion, it works just fine.
virtual_env > lib > python2.7 > site-packages > django > views > decorators > debug.py
def decorator(view):
#functools.wraps(view)
def sensitive_post_parameters_wrapper(request, *args, **kwargs):
'''
assert isinstance(request, HttpRequest), (
"sensitive_post_parameters didn't receive an HttpRequest. If you "
"are decorating a classmethod, be sure to use #method_decorator."
)
'''
if parameters:
request.sensitive_post_parameters = parameters
else:
request.sensitive_post_parameters = '__ALL__'
return view(request, *args, **kwargs)
return sensitive_post_parameters_wrapper
return decorator
I'm writing a basic RSS feed reader in Django. I have a form in which a user submits a rss feed, and I add it to his feeds list. But for some reason, I'm unable to extract basic information about the feed using feed parser.
when i run the following code:
def form_valid(self, form):
user = self.request.user
link = form.cleaned_data['link']
feed = feedparser.parse(link).feed
title = feed.title
try:
feed_obj = Feed.objects.get(link=link)
except ObjectDoesNotExist:
feed_obj = Feed(link=link, title=title)
feed_obj.save()
user.get_profile().feeds.add(feed_obj)
return super(DashboardView, self).form_valid(form)
Django throws me an "object has no attribute 'title'" exception on line 5:
title = feed.title
Full error details are:
Traceback:
File "/home/yaniv/nextfeed/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/home/yaniv/nextfeed/venv/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
25. return view_func(request, *args, **kwargs)
File "/home/yaniv/nextfeed/venv/local/lib/python2.7/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/yaniv/nextfeed/venv/local/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
86. return handler(request, *args, **kwargs)
File "/home/yaniv/nextfeed/venv/local/lib/python2.7/site-packages/django/views/generic/edit.py" in post
165. return self.form_valid(form)
File "/home/yaniv/nextfeed/profiles/views.py" in form_valid
48. title = feed.title
File "/home/yaniv/nextfeed/venv/local/lib/python2.7/site-packages/feedparser.py" in __getattr__
416. raise AttributeError, "object has no attribute '%s'" % key
Exception Type: AttributeError at /dashboard
Exception Value: object has no attribute 'title'
What am I doing wrong?
EDIT: I traced the program with pdb. Right before the problematic line, I got:
(Pdb) link
u'http://feedparser.org/docs/examples/rss20.xml'
(Pdb) feed
{'xhtml_script': {'type': u'text/javascript', 'language': u'javascript'}, 'summary': u''}
It's been a while since I used feedparser, but IIRC, the parser returns a dictionary, like so:
foo = feedparser.parse(link)
feed = foo['feed']
title = feed['title']
You seem to have gotten an object back from foo.feed, but that's not what you want.
I have this code in my view:
def add_intern(request):
if request.method == 'POST':
form = InternApplicationForm(request.POST)
if form.is_valid():
form.save()
form = InternApplicationForm()
else:
form = InternApplicationForm()
return render_to_response('application.html', {'form': form},
context_instance = RequestContext(request))
The form is a ModelForm, and the underlying model contains an IntegerField.
When I post a form with empty value, the validation message is displayed just fine.
When I post the form with a non-integer value, I get this:
KeyError at /
'invalid'
It kind of surprises me that the code seems to crash on is_valid() call, which I assumed is safe (i.e. should return False if there is a problem and not just crash). How do I fix this?
Stacktrace
Django Version: 1.3
Python Version: 2.6.5
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/home/dan/www/ints/backend/views.py" in add_intern
14. if form.is_valid():
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/forms/forms.py" in is_valid
121. return self.is_bound and not bool(self.errors)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/forms/forms.py" in _get_errors
112. self.full_clean()
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/forms/forms.py" in full_clean
267. self._clean_fields()
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/forms/forms.py" in _clean_fields
284. value = field.clean(value)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/forms/fields.py" in clean
169. value = self.to_python(value)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/forms/fields.py" in to_python
248. raise ValidationError(self.error_messages['invalid'])
Exception Type: KeyError at /
Exception Value: 'invalid'
Okay, so I just nailed it down.
I followed this advice to set my custom error message for validation.
So I had this code:
def __init__(self, *args, **kwargs):
super(InternApplicationForm, self).__init__(*args, **kwargs)
for field in self.fields.values():
field.error_messages = {'required':'*'}
that set the same required field validation message for all fields.
When the error was different (invalid for non-integer), Django looked in the dictionary I supplied—and guess what, KeyError. Because there is no message for invalid there (and that's my fault).
So the fix is
field.error_messages = {'required': '*', 'invalid': "That's not a number, sir."}
(and possibly other error message keys)