palewire/django-bakery

Allow BuildableTemplateView to utilise reverse_lazy (prevent duplicatation of URLs, allow directory paths)

mattaustin opened this issue · 2 comments

I've recently been using django-bakery on a project for the first time. There are a couple of non-model urls which should live in a directory path (e.g. '/terms-of-use/'), and need to be build in a similar way to how the BuildableDetailView does things.

I was also thinking that defining the url in urls.py, as well as on the view class seemed to duplicate things a little (I got caught out, where urls.py was updated, but not the build_path on the view).

I've been using the following mixin in my project. This is likely a little rough around the edges, and breaks when explicitly specifying a build_path such as index.html - but I thought it might prompt some discussion.

If this approach is considered a good idea, then I could continue with it (time permitting), and get it ready as a proper patch. Just wanted some feedback before I continued with it.

class ReversableBuildableTemplateMixin(object):

    def build(self):
        logger.debug('Building {}'.format(self.template_name))
        self.request = self.create_request(self.build_path)
        self.build_file(self.get_build_path(), self.get_content())

    def get_build_path(self):
        # Adapted from BuildableDetailView, so we can use a reversed (lazy)
        # url, rather than defining the url multiple times.
        target_path = path.join(settings.BUILD_DIR,
                                str(self.build_path).lstrip('/'))
        if not self.fs.exists(target_path):
            logger.debug('Creating {}'.format(target_path))
            self.fs.makedirs(target_path)
        return path.join(target_path, 'index.html')
class ExampleView(ReversableBuildableTemplateMixin, BuildableTemplateView):

    build_path = reverse_lazy('example_url_name')
urlpatterns = [
    path('example-path/', views.ExampleView.as_view(), name='example_url_name'),
]

I like the idea of being able to provide a URL name to link things up. I've used something similar in some of my projects.

Could we do this without breaking any existing tests and use cases? If we can establish a unittest alongside this new feature, I'm all for including it.

Is it something you'd want to submit a pull request on?

I think we have at least partial support for the feature proposed here. @mattaustin, if you want to take it further, let me know, but I'm closing the ticket for now. Thanks again for your patch.