Greg
Greg

Reputation: 43

Django 2.0 dynamically generate urlpatterns

I wrote this code that dynamically generates url patterns from the database. These urls have only one level path: domain.com/something.

someapp/models.py

class SomeModel(models.Model):
    pattern = models.CharField(max_length=50)
    name = models.CharField(max_length=50)
    text = models.CharField(max_length=50)

someapp/apps.py

class SomeAppConfig(AppConfig):
    name = 'someapp'

    def ready(self):
        from .models import SomeModel
        from .urls import urlpatterns
        from . import views

        urls_in_db = SomeModel.objects.all()
        for url_in_db in urls_in_db:
            urlpatterns.append(path(url_in_db.pattern,
                                    views.SpecialView.as_view(),
                                    name=url_in_db.name)

someapp/views.py

class SpecialView(generic.TemplateView):
    template_name = 'template/view_template.html'
    model = SomeModel

    def get_context_data(self, **kwargs):
        context = super(SpecialView, self).get_context_data(**kwargs)
        context['content'] = SomeModel.objects.get(pattern=self.request.path)
    return context

Is this solution an anti-pattern? And, if so, why? Thanks

Upvotes: 2

Views: 3115

Answers (1)

ndmeiri
ndmeiri

Reputation: 5029

Yes, your solution is an anti-pattern. Django supports parameters in URL patterns that get captured and become available in the corresponding view. Using these URL parameters, you can write and maintain a single URL pattern for every record of a certain type in your database.

Take a look at this example of URL parameters.

Finally, also note how your solution could potentially have very poor performance since you are potentially creating millions of URL patterns depending on the size of your database.

Upvotes: 3

Related Questions