Saturday, September 26, 2009

Use objects as a django view functions

To use objects instead of simple functions I apply the following method:

class Page(object):
    # Variables
    template = "main.html"
    vars = {}
    redirect_url = ""

    def __call__(self,request,*args,**kwargs):
        # Before calling a "main" content-generating method
        # "Main" content-generating method. Must be declared in descendants
        # After generating content

        # if need to redirect - do it
        if self.redirect_url:
            # if is present special redirect-field in GET
            url = request.GET.get(REDIRECT_FIELD_NAME)
            return HttpResponseRedirect(url if url else self.redirect_url)
        # Just return early declared template
        return render_to_response(self.template, context_instance=RequestContext(request, self.vars))

    def before_content(self,request,*args,**kwargs):
    def after_content(self,request,*args,**kwargs):

class PageAuth(Page):
    def __call__(self,request,*args,**kwargs):
        if request.user.is_authenticated():
            return super(PageAuth,self).__call__(request,*args,**kwargs)
        return HttpResponseRedirect("{0}?{1}={2}".format(reverse(settings.LOGIN_VIEW),REDIRECT_FIELD_NAME,request.path))

class MainView(Page):
    def content(self,request,*args,**kwargs):
        self.template = 'template_name.html'
        self.vars['list'] = []
And has been changed url declarations. An example:
url(r'^$', MainView(), name="main_page")
(I couldn't find decision without using name parameter).

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.