mixing classes and view functions?

Disclaimer : Very new to django & python.

What is your opinion of this kind of code, where I use a view function which has classes in it for rendering to a template?

#objects for use in view

class Article():

def getContent(self):

    return "this is an amazing hard-coded article"  #I guess you could link this to a model

Create your views here.

def index(request):

#template

template = loader.get_template('index.html')



#objects

article = Article()

#collection of objects    

collection = {

    'article': article,

}

#pass to the template the collection for use in the template

return HttpResponse(template.render(collection, request))

Yay or nay? and reasons why please.

When you post code here, please post it between lines consisting of only three backtick (`) characters. So you would have a line ```, your lines of code, and then another line of ```.

A very common pattern might look something like this (off the cuff and possibly with syntax errors):

def my_view(request):
    collection = Article.objects.all()
    context = { 'articles': collection }
    return render(request, 'index.html', context=context)

(Render already returns an HttpResponse object, so no further processing required there.)

Maybe your example doesnā€™t really demonstrate what youā€™re trying to achieve, but Iā€™m just not seeing the point youā€™re trying to express here. Or, to be more accurate, Iā€™m not seeing a difference between your example and the ā€œcommon caseā€.

Ken

Noted, with formatting, Iā€™ll do better next timeā€¦I didnā€™t mean that to happen :slight_smile:

What I was thinking was if you have multiple models, then it might be nice to wrap them in a class which deals with accessing the various parts of the models (which are wrapped in other classes), so that in the templates you can perhaps chain together in some way . So you have a class which kind of act likes an iterator in some way.

{{Articles.First}}

{{Articles.Popular}}

Iā€™m a little shakey (among other things) on how to loop things at the moment in templatesā€¦

Oh, ok.

Assuming my trivial example above, where the context contains an element named ā€˜articlesā€™, your template could look like this:

{% for article in articles %}
    {{ article.some_field_name }}
{% endfor %}
1 Like

FYI, and not to say that you need to do this, but you could go back and edit your original post. (Not really necessary in this case, but handy to know in the future.)