[Answer]-Django – relations between models

1πŸ‘

βœ…

I think you should change your Profile model and add a OneToOne relationship to the User model(for more info see here):

class Profile(models.Model):
    user = models.OneToOneField(User)
    ...

class Posts(models.Model):
    author = models.ForeignKey(User)
    ...

and then in your views you can do:

user = get_object_or_404(User, username=username)
post_list = Post.objects.filter(author=user).filter(isdraft=False).order_by("-posted") 

return render_to_response('index.html', 
                           {'post_list': post_list, 'user': user, ...}, ...)

And then in your template you are able to access the user’s profile.More here
e.g {{user.get_profile.slogan}}

πŸ‘€thikonom

0πŸ‘

In your view:

def index(request, username):
    user = User.objects.get(username=username)
    return render(request, 'index.html', {'user':user})

In your template:

{{ user.post_set }}

and You will receive list of posts of current user.

πŸ‘€yakxxx

0πŸ‘

The most natural way to achieve that is to add a OneToOne relation between your Profile model and the django’s User model.

from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User)
    # More fields

class Article(models.Model):
    author = models.ForeignKey(User)
    # More fields

This way, you can access the profile data through a User object. Would be something like this:

user = User.objecets.get(username=username)
profile = user.profile

More info about this, you can read the django model fields documentation here
and you can also see this cool answer about the diference between the ForeignKey with unique=True and the OneToOneField

I hope this helps

πŸ‘€iferminm

Leave a comment