Skip to content
Advertisement

Is there a more DRY way to create these repetitive django class based views, and URL patterns?

Is there a better, more DRY way to create repetitive sets of views and urls in django? Below are my views and urls. As you can probably see, There are currently two sets of views and urls that are would be identical if not for the different model name. Is there a way to create 3 classes at once as a mixin or something similar to that so that all I have to do to add a new set of classes is pass the model name to one function or child class? Is there something similar I could do for the urls? I found a related question here Class Based Generic Views and DRY but am not sure if and how the answer to that question applies here or is relevant.

relevant section in views:

JavaScript

relevant section in urls.py:

JavaScript

The answer to this question will be used in LibreBadge, LibreBadge GitHub, an open source, MIT licensed, ID badge solution. Feel free to answer this question in the form of a pull request if that’s your style!

Advertisement

Answer

I found a solution to the repetitive views problem!

JavaScript

I created a function that uses type to dynamically create class based views (learn more about using type to create classes here) and assign them to a dictionary.

Now I only have to call the applicationAdminCRUDFunction and assign it’s values to a variable. I can then call the views in urls.py like so

JavaScript

To solve the repetitive URL pattern problem, I created a function to return a list of urls with the modelName parameter

JavaScript

I then called that function by creating one path pattern with include and passed the applicationAdminURLS function as the parameter to include

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement