Saturday, April 25, 2015

Concept of partial views to be resolved from other views or template tags

Hi all,

I am wondering if the following is considered a bad practice and might lead to issues. I think it provides a useful pattern, for example for creating template tags or simple ajax use cases where the rendered result of a partial will get frequently updated.

# partials.py
class SomePartial(View):
   
""" A view providing partial content. """
   
def get(self, request):
       
# related views logic like lookups ...
       
return render(request, 'patterntests/_partial.html', {})

# views.py
class SomeView(View):
   
""" Including the partial by calling get on `SomePartial`. """
   
def get(self, request):
        someview
= SomePartial()
        res
= someview.get(request)
        ctx
= {
           
'partial_content': mark_safe(res.content)
       
}
       
return render(request, 'patterntests/test.html', ctx)


class AnotherView(View):
   
""" Including the partial by resolving its view. """
   
def get(self, request):
        rev
= reverse('patterntests:somepartial')
        view
, vargs, vkwargs = resolve(rev)
        vkwargs
['request'] = request
        res
= view(*vargs, **vkwargs)

        ctx
= {
           
'partial_content': mark_safe(res.content)
       
}

       
return render(request, 'patterntests/test.html', ctx)

My main question is about the following two lines in SomeView. Does that have serious flaws (edge cases, performance, security)?

class SomeView(View):
   
def get(self, request):
       
# ...
        someview
= SomePartial()
        res
= someview.get(request)
       
# ...

I like that approach because it leads to any partial being a separated piece of logic that can be tested and developed on a dedicated url. If necessary it can be wrapped in a templatetag, which makes it easy to use from the template layer. On top of that, by implementing something like a format='json|html|xml|...' attribute it could be further improved to allow for more advanced ajax use cases. However, since I've not seen it being used that way I think that this might be for a good reason. (-:

Would appreciate your feedback,

Regards,
Stephan


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/1fe114be-f037-4318-8da6-49dca4003266%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment