0

私はこのコードを持っています:

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})

(それ自体は不格好ですが、それについては後で詳しく説明します)

URLからこれを呼び出すにはどうすればよいですか?

私は現在これを試しています:

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

しかし、djangoはそれを不平を言います

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

Request Method:     POST

私が求めていること:

  1. urls.pyからこのメソッドを(クラスのメソッドとして)呼び出すにはどうすればよいですか?
  2. メソッドを「動的」にする簡単な方法はありますか?つまり、何が設定されているかを確認し、必要に応じてデフォルトにするために、これらの醜い「if」ブロックをすべて用意する必要はありませんか?
4

1 に答える 1

2

これは、Djangoのクラスベースのビューを使用する方法ではありません。これらは、メソッドを介してurls.pyから参照する必要があります。as_view()クラスごとに複数のビューレンダリングメソッドを使用することを意図したものではありません。必要な場合は、共通コードを基本クラスに配置してサブクラス化することをお勧めします。ただし、あなたの場合は、おそらく既存のメソッドをもっと使用したいだけです。たとえば、レンダリングするテンプレートを決定するには、をオーバーライドする必要がありますget_template_names()

于 2012-05-21T13:34:18.547 に答える