

A better way for passing Django context
source link: https://www.rockandnull.com/django-template-variable/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

A better way for passing Django context
I like Python as a language and Django as a framework. They are super practical and let you create incredible things in no time.
But if there's one thing I dislike is the use of dictionaries everywhere. I am mainly referring to the Context object that requires a dictionary to be passed to render a Django template. I find this to be extremely ugly. For instance, if you need to render the template in multiple places, you would need to repeat the dictionary keys when constructing the dictionary. You could save the dictionary keys in some variables and use those in the dictionary, but this is not that elegant.
The solution I prefer in this situation is to use data classes for each template, and convert that data class to a dictionary when needed. With this approach, I get the type of safety, elegance, and DRY (Don't Repeat Yourself) principle quickly and easily.
For instance, take this use case:
[...]
return render(request,
template_name='template.html',
context={
'key1': 'value1',
'key2': 42
})
If you have to use this template in another View, then you would need to repeat those keys. Instead, you could create a data class for the context and convert that to a dict
when needed:
@dataclass # 1.
class MyViewContext:
key1: str # 2.
key2: int
def dict(self): # 3.
return asdict(self)
[...]
return render(request,
template_name='template.html',
context=MyViewContext(key1='value1', key2=42).dict()) # 4.
- Data classes were introduced in Python 3.7. A data class comes with the basic functionality needed to initialize and compare a class. Its aim is just to contain data in an object-oriented manner.
- Data types are optional but highly recommended.
asdict
converts a data class into a dictionary with the variable names as keys. Here we create a convenience member method to make that conversion.- Initialize the data class, and convert that to a dictionary!
Hopefully, you would prefer this approach when creating context objects for rendering Django templates.
Happy coding!
Recommend
-
68
-
46
So you’ve probably noticed the recent rise of headless components – i.e. components that facilitate the reuse of control logic by delegating their presentation to a render prop. There’s a...
-
68
While creating a component in a typical React app, we end up creating layers of functional components and class components. Much of the time, we end up following a pattern where we pass props to a functional or class comp...
-
13
Standard Django: Passing Form Values in URL Lets say you have a form that is used to drive the next page. For example, it might contain parameters for running a report. One way to ha...
-
12
Better Done Than Perfect. Switch Interviews & Strategic Context with Alli Blum Published December 25, 2020 by Jane Portman Categories:...
-
9
@regquerlyvalueexAlex ZaietsPython developerWe are gonna’ look into cloning Django model instances, applicability of Iterator and Visitor...
-
4
In this tutorial you'll learn how to implement Django Rest Framework authentication in your web application by leveraging the built-in Django session framework. This approach is way simpler (and secure) than other popular methods such...
-
7
On how to better understand context and communicate questions Jul 6, 2022 , by Vipul A M 3 minute read ...
-
11
In this tutorial, I'll explain how to add context menus to elements of a web page using my newly developed component. This menu can appear when a user right-clicks on an element of a web page or just puts the mouse cursor on that element. This is...
-
9
AppContext [0.4.7.2] - Better application c...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK