This is my code for the view:
@login_required
def get_top(type):
o = Work.objects.filter(types = "Fan Fiction").order_by("-date_updated")[:10]
list = []
for o in o:
l.title = o.title
l.href = "/" + o.id
list.append(l)
return l
@login_required
def main_home(request):
fanfiction = get_top("ff")
poetry = get_top("pw")
originalwork = get_top("ow")
return render_to_response("Main/main_home.html", {'STATIC_URL':STATIC_URL, "poetry":poetry, "fan":fanfiction, "original":originalwork})
This is the code for the model:
class Work(models.Model):
title = models.CharField(max_length=30)
summery = models.TextField()
user = models.ForeignKey(User)
date_published = models.DateField()
date_updated = models.DateField()
one_shot = models.BooleanField()
completed = models.BooleanField()
TYPES = (
('FF', 'Fan Fiction'),
('OF', 'Original Work'),
('PW', 'Poetry Work'),
)
types = models.CharField(max_length=2, choices=TYPES)
fandom1 = models.ForeignKey(Book, blank = True, null= True, related_name='f_1')
fandom2 = models.ForeignKey(Book, blank = True, null= True, related_name='f_2')
def __unicode__(self):
return self.title + '-' + self.user.email
This is the error: 'str' object has no attribute 'user'
at "get_top("ff")"
The Python "AttributeError: 'str' object has no attribute" occurs when we try to access an attribute that doesn't exist on string objects. To solve the error, make sure the value is of the expected type before accessing the attribute.
The Python "AttributeError: 'str' object has no attribute 'append'" occurs when we try to call the append() method on a string (e.g. a list element at specific index). To solve the error, call the append method on the list or use the addition (+) operator if concatenating strings.
Please remove @login_required
decorator for get_top
method.
What this is trying to do is, @login_required
tries to verify if that user is logged in or not. this is trying to find a User
object instance in ff
which is a str
hence the stacktrace. Normally @login_required
gets User
from request
obj, but since you are not passing that in get_top
hence the error.
My suggestion is you should maintain a certain set of methods in views.py
which are linked to the API urls in urls.py
some of these might require @login_required
. other set of methods are helper method (like get_top
). these are not exposed to outside world (hence no need for @login_required
).
In case you must expose get_top
both internally and externally, then your first parameter to get_top
has to be request
object then followed by other params.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With