AttributeError: 'instancemethod' object has no attribute 'short_description' - python-2.7

I try to update an attribute of a method, but fails:
class Activity(object):
def my_method(self):
return 'foo'
my_method.short_description = 'old'
Activity.my_method.short_description = 'new'
Exception:
Activity.my_method.short_description = 'new'
AttributeError: 'instancemethod' object has no attribute 'short_description'
Is there a way to update my_method.short_description?
This needs to work with Python 2.7. With Python 3.x this exception does not happen.

I found this solution:
import types
class Activity(object):
def my_method(self):
return 'foo'
my_method.short_description = 'old'
# Activity.my_method.short_description = 'new'
# --> Exception
class UpdateableInstanceMethod():
# Otherwise: 'instancemethod' object has no attribute 'short_description'
def __init__(self, orig_method, short_description):
self.orig_method = orig_method
self.short_description = short_description
def __call__(self, obj):
return self.orig_method(obj)
Activity.my_method = types.MethodType(UpdateableInstanceMethod(
Activity.my_method,
'new'
), None, Activity)
assert Activity.my_method.short_description == 'new'
assert Activity().my_method.short_description == 'new'
assert Activity().my_method() == 'foo'
print('ok')

Related

AttributeError at /profile/chandan 'tuple' object has no attribute 'another_user'

I am trying to get follower system to work but it just wont work
class Followers(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
another_user = models.ManyToManyField(User, related_name='another_user')
def __str__(self):
return self.user.name
def profile(request, user_name):
user_obj = User.objects.get(username=user_name)
session_user, create = User.objects.get(username=user_name)
session_following, create = Followers.objects.get_or_create(user=session_user)
following = Followers.objects.get_or_create(user=session_user.id)
check_user_followers = Followers.objects.filter(another_user=user_obj)
is_followed = False
if session_following.another_user.filter(username=user_name).exists() or following.another_user.filter(username=user_name).exists():
is_followed=True
else:
is_followed=False
param = {'user_obj': user_obj,'followers':check_user_followers, 'following': following,'is_followed':is_followed}
if 'user' in request.session:
return render(request, 'users/profile2.html', param)
else:
return redirect('index')
I am getting the error:
AttributeError at /profile/chandan
'tuple' object has no attribute 'another_user'
get_or_create(…) [Django-doc] returns a 2-tuple with as first item the object, and as second item a boolean that indicates if the object was created (True), or already in the database.
You can make use of iterable unpacking to set the boolean to a "throwaway" variable:
# ↓ throw away the second item of the 2-tuple
session_following, __ = Followers.objects.get_or_create(user=session_user)
following, __ = Followers.objects.get_or_create(user=session_user)

'str' object has no attribute 'META' error while returning a JsonResponse

I want to return a JsonResponse/HttpResponse from my Django views function. However I am getting 'str' object has no attribute 'META' error. The code for the function is given below.
def search(request):
queryset_list = Influencer.objects.orderby('username')
if 'username' in request.GET:
username = request.GET['username']
if username:
queryset_list = queryset_list.filter(username__iexact=username)
#Full Name
if 'fullname' in request.GET:
fullname = request.GET['fullname']
if fullname:
queryset_list = queryset_list.filter(full_name__iexact=fullname)
context = {
'listings':queryset_list,
'values':request.GET
}
filtered_data = serializers.serialize("json",context)
return JsonResponse(filtered_data)
Instead of serializing the context I serialized the query_list obtained and the function worked correctly.
The code after the last if statement should be this.
serialized_list = serializers.serialize('json',queryset_list)
return HttpResponse(serialized_list, content_type='application/json')

Get most recently created object in a queryset?

Attempting to get the most recent object in a query set and I keep getting error
TypeError at / 'PostManager' object is not iterable
How do you do this without iterating?
class DashboardTemplateView(TemplateView):
template_name = "base.html"
context_object_name = 'name'
def get_context_data(self, *args, **kwargs):
context = super(DashboardTemplateView,self).get_context_data(*args, **kwargs)
context["title"] = "This is about us"
return context
class MyView(ContextMixin, TemplateResponseMixin, View):
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
# mission_statement = Content.objects.filter(Content.objects.title == 'test')
# context = {'mission_statement' : mission_statement,
# 'content_list' : Content.objects.all(),
# 'post_list' : Post.objects.all()}
# context = {'content_list' : Content.objects.all(), 'post_list' : Post.objects.all()}
home_list = list(Post.objects).order_by('-id')[0]
context = {'content_list' : Content.objects.all(), 'home_list' : home_list.objects.all()}
return self.render_to_response(context)
This line is wrong:
home_list = list(Post.objects).order_by('-id')[0]
Post.objects is the PostManager : it is not a iterable, you cannot list() it.
I guess what you are after is this:
home_list = Post.objects.all().order_by('-id').first()
The difference between first() and [0] is that first() won't throw IndexError if no result in query set, it will return None.
A small paranthesis error on line below
home_list = list(Post.objects).order_by('-id')[0]
Change this to
home_list = list(Post.objects.all().order_by('-id'))[0]
An alternative one
home_list = Post.objects.all().order_by('-id').first()
Also calling objects method on home_list is not needed. Below would also work fine
context = {'content_list' : Content.objects.all(), 'home_list' : home_list}

Flask login 'function' object has no attribute 'is_active'

I try to use flask login in may app:
My controller:
#app.route("/process_log", methods=['POST'])
def process_login():
filled_form = LoginForm(request.form)
if filled_form.validate():
phone = filled_form.phone.data
password = filled_form.password.data
if User.phone_exists(phone) and User.pass_match(phone, password):
user = User.get_by_phone(phone)
login_user(user.get_id)
return redirect(url_for("index"))
else:
return render_template("login.html", form = filled_form, error = u"Не верный логин или пароль")
else:
return render_template("home.html", form = filled_form)
and I have some class with defined functions which required for API of flask login
My User class:
from pymongo import MongoClient
from bson.objectid import ObjectId
class User():
client = MongoClient()
db = client['test']
col = db['user']
user_id = None
def __init__(self, dic):
self.dic = dic
def is_authenticated():
return True
def is_anonymous():
return False
def is_active():
return True
def get_id(self):
return unicode(str(self.user_id))
def save(self):
self.user_id = self.col.insert(self.dic)
print "Debug:" + str(self.user_id)
#staticmethod
def _get_col():
client = MongoClient()
db = client['test']
col = db['user']
return col
#staticmethod
def phone_exists(phone):
col = User._get_col()
if col.find_one({'phone': phone}) != None:
return True
else:
return False
#staticmethod
def pass_match(phone, password):
col = User._get_col()
if col.find_one({'phone': phone})['password'] == password:
return True
else:
return False
#staticmethod
def get(userid):
col = User._get_col()
return col.find_one({'_id':userid})
#staticmethod
def get_by_phone(phone):
col = User._get_col()
dic = col.find_one({'phone': phone})
print dic['password']
return User(dic)
As you see function is_active is defined(Note:I also tried to pass refference with self)
But I still have this error AttributeError: 'function' object has no attribute 'is_active'
I am sorry for too much code here, but it should be pretty straightforward.
Note: I am using mongodb for my project.
Please help me to find my error. Thank you too much
One more thing:
Should I provide login_user(....) with Id or with my user object?
You must sent to login_user User instance (not id), see: https://github.com/maxcountryman/flask-login/blob/master/flask_login.py#L576.
So next code must work:
user = User.get_by_phone(phone)
login_user(user)

Django custom template tag problem

This is my python code for 'box':
register = Library()
class KeyNode(Node):
def __init__(self, _node):
self._node = _node,
def render(self, context):
try:
#content = "this works!"
content = self._node.render(context)
return content
except:
bilogger.exception('KeyNode')
return ''
#register.tag('box')
def wrapper(parser, token):
try:
#fn, _option = token.split_contents()
node = parser.parse(('endbox',))
parser.delete_first_token()
except ValueError:
raise TemplateSyntaxError("INVALID FORMAT PROVIDED FOR BOX")
return KeyNode(node)
self._node.render(context) is an empty string, and nothing is returned back. However, content = "this works!", works.
Whats wrong here?