bharal
bharal

Reputation: 16164

How to create a method view in django?

I have this code:

class StoryViewClass(ListView):

... some listview methods here for one set of urls

def saveStory(self,request,context_object_name,
              template_name,
              success_template):
    if request.method == "POST":
        form = StoryForm(request.POST)
        form.user = request.user.id
        if form.is_valid():
            form.save()
            if (success_template):
                return render_to_response(success_template)
            else:
                return render_to_response('accounts/addStorySuccess.html')
    else:
        form = StoryForm()
    if (context_object_name):
        contextName = context_object_name
    else:
        contextName = 'form'
    if (template_name):
        return render_to_response(template_name,{contextName:form})
    else :
        return render_to_response('accounts/addStory.html',{contextName:form})

(which is itself klunky, more on that later)

how do i call this from my url?

I am currently trying this:

url(r'^addStory/$',
    StoryShowView.saveStory(
        context_object_name='form',
        template_name='accounts/addStory.html',
        success_template='accounts/addStorySuccess.html'
    )
),

but django complains that

unbound method saveStory() must be called with StoryShowView instance as first argument (got nothing instead)

Request Method:     POST

What i am asking:

  1. how do i call this method (as a method of a class) from the urls.py?
  2. is there a simpler way to make the method "dynamic" or what have you - i mean, so i do not need to have all those ugly "if" blocks there to check what has been set and default if necessary?

Upvotes: 0

Views: 433

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599520

That's not how you use Django's class-based views. These must be referred to from urls.py via the as_view() method. They're not meant to have more than one view-rendering method per class - if you need that, it's best to put common code in a base class and subclass it. But in your case, you probably just want to use the existing methods more - for example, to work out which template to render, you should override get_template_names().

Upvotes: 2

Related Questions