user5827910
user5827910

Reputation:

Filtering model objects in django view

I'm currently creating a Social platform with Django. Right now, I'm developing their Profile page and want endusers to be able to see a timeline with their own posts. This is my Post model:

class Post(models.Model):
    user = models.ForeignKey(User)
    posted = models.DateTimeField()
    content = models.CharField(max_length=150)
    Likes = models.IntegerField()

def __str__(self):
    return self.user.username

In the view I wanted to filter out all the posts created by the current user. But I keep getting the error:

invalid literal for int() with base 10: 'Admin'

This is my views:

@login_required
def profile_view(request):
    all_posts = Post.objects.get(user=User.username).order_by('-posted')
    return render(request, 'Dashboard/profiel.html', {'posts':all_posts})

What am I doing wrong?

Upvotes: 1

Views: 8491

Answers (3)

Pyvonix
Pyvonix

Reputation: 827

get() can only return 1 element in the query.

In the Django doc filter and get. The part who is interesting is :

Retrieving a single object with get()

filter() will always give you a QuerySet, even if only a single object matches the query - in this case, it will be a QuerySet containing a single element.

If you know there is only one object that matches your query, you can use the get() method on a Manager which returns the object directly:

So use filter and use have a query with all matching :

@login_required
def profile_view(request):
    all_posts = Post.objects.filter(user=request.user).order_by('-posted')
    return render(request, 'Dashboard/profiel.html', {'posts':all_posts})

And in your Template, your query is like a list, use loop for display it 1 by 1.

Upvotes: 1

Max
Max

Reputation: 1010

You have three misunderstandings in your approach:

  1. The user attribute on the Post awaits an instance of User. In your filter you compare the user with User.username, which is a CharField.
  2. User is not the user of the current request. The user of the current request is attached on the request object as part of Django's Request-Response-Lifecycle.
  3. You need to use filter() instead of get() when you want to get a QuerySet, instead of a single instance, see the Django docs on making queries.

Example:

@login_required
def profile_view(request):
    all_posts = Post.objects.filter(user=request.user).order_by('-posted')
    return render(request, 'Dashboard/profiel.html', {'posts':all_posts})

Upvotes: 4

flowfree
flowfree

Reputation: 16462

You should get the current user from the request object:

@login_required
def profile_view(request):
    all_posts = Post.objects.filter(user=request.user).order_by('-posted')
    return render(request, 'Dashboard/profiel.html', {'posts':all_posts})

Upvotes: 0

Related Questions