88dax
88dax

Reputation: 307

Django : AttributeError

When I'm trying to retrieve data using a Foreign key from other table I'm getting the below exception:

'User' object has no attribute 'UserFeed_set'

View :

def user_page(request, username):
    try:
        u = User.objects.get(username=username)
    except User.DoesNotExist:
        raise Http404(u'Requested user not found.')
    feeds = u.UserFeed_set.all()
    variables = RequestContext(request, {
        'username' : username,
        'feeds' : feeds
    })
    return render_to_response('user_page.html', variables)

models.py:

from django.contrib.auth.models import User

class AllFeeds(models.Model):
    url = models.CharField(unique=True, max_length=40)

    def __unicode__(self):
        return self.url

class UserFeed(models.Model):
    user = models.ForeignKey(User)
    myfeeds = models.ForeignKey(AllFeeds)

    def __unicode__(self):
        return u'%s %s'%(self.user.username,self.link.url)

Upvotes: 1

Views: 22912

Answers (3)

user1564928
user1564928

Reputation: 21

as I know, if you have the two models using manytomany relation, you can use u.userfeed_set.all(), but as u said, your models are using one-to-one relation

Upvotes: 0

Burhan Khalid
Burhan Khalid

Reputation: 174748

The main issue here is you need to use the correct related name format, which is all lowercase; but there are some further issues with your models.

Clearning up your code, you end up with this:

from django.shortcuts import get_object_or_404, render

def user_page(request, username):
    u = get_object_or_404(User, username=username)
    feeds = u.userfeed_set.all()
    variables = {
        'username' : username,
        'feeds' : feeds
    }
    return render(request, 'user_page.html', variables)

Your models also need some editing, because you have no self.link.url:

from django.contrib.auth.models import User

class AllFeeds(models.Model):
    url = models.URLField(unique=True, max_length=40)

    def __unicode__(self):
        return unicode(self.url)

class UserFeed(models.Model):
    user = models.ForeignKey(User)
    myfeeds = models.ForeignKey(AllFeeds)

    def __unicode__(self):
        return unicode('{0} {1}'.format(self.user.username, self.myfeeds.url))

Upvotes: 1

DanielB
DanielB

Reputation: 2958

If you haven't a related_name on the ForeignKey field of the UserFeed model, it should be a accessible as user.userfeed_set. (The default name is model.__name__.lower() + "_set").

If you have set the releated_name, the method will be called whatever you named gave as the value.

Upvotes: 1

Related Questions