1๐
โ
A quick example of using function-based views:
# your_app/views.py
def rock_and_feat(request):
feats = Feat.objects.order_by('-num')[:1]
rocks = Rockinfo.objects.order_by('-rank')[:50]
context = RequestContext(request, {
'feats': feats, 'rocks': rocks
})
return render_to_response('template.html', context)
And for urls:
# deprecated in 1.8:
# urlpatterns = patterns('',
urlpatterns = [
# Example:
url(r'^rock_and_feat/$', app.views.rock_and_feat, name='rock_and_feat'),
]
# )
This method is usefull, when you have a complex logic in your view. For example, you need to show aggregated data from several models.
Read about function-based views in the docs and consider this approach in the future development.
๐คsobolevn
1๐
How about something simplistic like:
views.py
class MyTemplateView(TemplateView):
template_name = 'myapp/mytemplate.html'
def get_context_data(self, request, **kwargs):
context = super(MyView, self).get_context_data(request, **kwargs)
context['widget_1'] = ModelFoo.objects.all()
context['widget_2'] = ModelBar.objects.all()
return context
myapp/mytemplate.html
{% if widget_1 %}
<ul class="widget widget_1">
{% for item in widget_1 %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% endif %}
You could DRY this up even further with an โas_widgetโ property on the model class that returns a widget template using render_to_string et cetera et cetera..
Source:stackexchange.com