'Post' object is not iterable even though i'm using filter


I’m trying to get all posts for a certain Vehicle and this is the code that i have:

class UserVehicleListView(ListView):
    model = Vehicle
    template_name = 'vehicles/vehicles.html'  # <app>/<model>_<viewtype>.html
    context_object_name = 'vehicles'
    def get_queryset(self):
        print(Vehicle.objects.filter(owner_id= self.request.user.id))
        return Vehicle.objects.filter(owner_id= self.request.user.id)

class UserVehicleDetailView(DetailView):
    model = Post
    template_name = 'vehicles/vehicle_detail.html'  # <app>/<model>_<viewtype>.html
    context_object_name = 'posts'

    def get_queryset(self):

        vehicle = get_object_or_404(Vehicle, id =self.kwargs.get('pk'))
        print(Post.objects.filter(vehicle= vehicle))
        return Post.objects.filter(vehicle= vehicle)


urlpatterns = [
    path('vehicles/', UserVehicleListView.as_view(), name='vehicle-list'),
    path('vehicles/<int:pk>/',  UserVehicleDetailView.as_view() , name='vehicle-detail'),


urlpatterns += staticfiles_urlpatterns()

  {% for vehicle in vehicles %}

      <div class="col-lg-6 mb-3 mb-lg-0">
          <div class="hover-overlay" ></div>
          <div class="hover-1-content px-5 py-4">
            <a href=" {%url 'vehicle-detail' vehicle.id %}">
            <h3 class="hover-1-title text-uppercase font-weight-bold mb-0"> <span class="font-weight-light">Volvo </span></h3>

            <p class="hover-1-description font-weight-light mb-0">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>


{% extends "blog/base.html" %}
{% block content %}
<article class="media content-section">
    {% for post in posts %}


{% endblock content %}

When i print with Vehicle.objects.filter(owner_id= self.request.user.id) I get in the cmd:

<QuerySet [<Post: Post object (1)>, <Post: Post object (3)>]>
but when I pass the values with the for loop in the vehicle_detail.html I get:

** TypeError at /vehicles/1/ ‘Post’ object is not iterable**

When i pass as {{object.date_posted}} I get only 1 Post, how can I pass all posts? Thanks in advance for the help!


Found out the problem, i was passing as DetailView instead of ListView

Answered By – boytoy.zip

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published