user4383363
user4383363

Reputation:

Get the ID from URL and select it from the database

I have Post. In the index page, I show all of them, ordering by created_at, as it shows in here:

class IndexView(TemplateView):
    template_name = 'blog/index.html'

    def get(self, request):
    return render (request, self.template_name, {
        'posts': Post.objects.order_by('-created_at')
    })

I've created a view that I intend to redirect to another page, showing the whole Post. This is the url.py:

urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name = 'index'),
    url(r'^categories/$', views.CategoriesView.as_view(), name = 'categories'),
    url(r'^post/(?P<id>[0-9]+)/$', views.Post.as_view(), name = 'post')
]

and the view for such:

class Post(TemplateView):
    template_name = 'post.html'

    def get(self, request):
    id = request.GET.get('id', '')

    return render(request, self.template_name, {
        'post': get_object_or_404(Post, pk = id) 
    })

But then I am getting the error:

AttributeError at /

type object 'Post' has no attribute 'objects'.

Upvotes: 1

Views: 13877

Answers (1)

Selcuk
Selcuk

Reputation: 59445

Don't name both your view and model the same! Call it PostView, for example and the problem will be solved:

class PostView(TemplateView):
    ...

and

url(r'^post/(?P<id>[0-9]+)/$', views.PostView.as_view(), name = 'post')

You are also passing the id argument using URL rerouting; not through GET. Change the method signature to:

def get(self, request, id):

and use the id variable directly.

Upvotes: 3

Related Questions