Oblivionkey3
Oblivionkey3

Reputation: 1862

Error Instantiating View Classes in Django

I'm new to Django and have used generic views for all my projects so far. I've called them in the url.py code with

patterns(r'^url$',DetailView.as_view())

However, now I'm trying to make my own class based views and am having trouble at it. I tried making a simple test where I call a model.py function from my view, but I get an error that I haven't instantiated an instance of the class. How should I instantiate the view class? Also, how come I don't get the same error when calling DetailView.as_view() the DetailView class isn't instantiated either, right?

My code:

models.py

class Post(models.Model):
    title = models.CharField(max_length=140)
    body = models.TextField()

    def __unicode__(self):
        return self.title

    def getBody(self):
        return self.body

view.py

class RatingView(generic.DetailView):
    model = Post
    template_name = "like.html"

    def __init__(self):
        model = Post
        template_name = "like.html"

    def modelFuncTest(self):
        return HttpResponse(self.model.getBody())

url.py

from django.conf.urls import patterns, include, url
from django.views.generic import ListView, DetailView
from blog.views import RatingView
from blog.models import Post

urlpatterns = patterns('',
    url(r'^(?P<pk>\d+)/like/$', RatingView.modelFuncTest()),
)

Upvotes: 4

Views: 457

Answers (2)

awwester
awwester

Reputation: 10182

Change your views.py to be just:

class RatingView(generic.DetailView):
    model = Post
    template_name = "like.html"

and change urls.py to be:

from django.conf.urls import patterns, url
from blog.views import RatingView

urlpatterns = patterns('',
    url(r'^(?P<pk>\d+)/like/$', RatingView.as_view()),
)

and that should get you started, let me know if there are errors after making these changes.

There are some good examples in the django docs if you haven't seen them yet.

EDIT: Also, in the template, you should get your body like this:

{{ post.body }}

The beauty of the Class-based views is that the context of your object gets passed for you.

Upvotes: 1

Brian Neal
Brian Neal

Reputation: 32399

You still need to call the as_view() function on your class in your urlpatterns:

urlpatterns = patterns('',
                       url(r'^(?P<pk>\d+)/like/$', RatingView.as_view()),
                       )

As for this:

Also, how come I don't get the same error when calling DetailView.as_view() the DetailView class isn't instantiated either, right?

The as_view() function is a class method, which returns an instance of the view class that can be called when your URL pattern is hit.

Upvotes: 0

Related Questions