Refactoring Django class representations, clearing 18 repeating classes.

https://github.com/AnthonyBRoberts/fcclincoln/blob/master/apps/story/views.py

I am a little embarrassed to admit that it is mine. But this.

class FrontpageView(DetailView):
    template_name = "welcome_content.html"
    def get_object(self):
        return get_object_or_404(Article, slug="front-page")
    def get_context_data(self, **kwargs):
        context = super(FrontpageView, self).get_context_data(**kwargs)
        context['slug'] = "front-page"
        events = Article.objects.filter(slug="events")
        context['events'] = events
        return context

So, this is a pretty ordinary cool detail view in Django.

It assigns a template, receives an Article object, and adds some things to context_data.

Then I copied this class 17 times. Each time, there is a different template, and a different slug, and various things added to context_data.

The idea is that the WYSIWYG editor for administrators can modify the web content and user authentication system to allow multiple users to access the contents of the site. In principle, a super-simple CMS, so no one should edit html to update the site.

, , 18 . , , .

+4
3

, TemplateResponseMixin, DetailView, ( SingleObjectTemplateResponseMixin) get_template_names(), , .

django-blog-zinnia

def get_template_names(self):
    """
    Return a list of template names to be used for the view.
    """
    model_type = self.get_model_type()
    model_name = self.get_model_name()

    templates = [
        'zinnia/%s/%s/entry_list.html' % (model_type, model_name),
        'zinnia/%s/%s_entry_list.html' % (model_type, model_name),
        'zinnia/%s/entry_list.html' % model_type,
        'zinnia/entry_list.html']

    if self.template_name is not None:
        templates.insert(0, self.template_name)

    return templates

Django , , . , .

Update

, , - :

urls.py

# convert each url
url(r'^$', FrontpageView.as_view()),
url(r'^history/$', HistoryView.as_view()),
url(r'^calendar/$', CalendarView.as_view()),
url(r'^news/$', NewsView.as_view()),
url(r'^visitors/$', VisitorsView.as_view()),
...
# to just
url(r'^(?P<slug>[\w\d/-]+)/$', SuperSpecialAwesomeView.as_view()),
# but, put this at the end of urls list after any routes that don't use this view

DetailView, class model, , slug url kwargs, , slug, , , do: Article.ojects.get(slug=self.kwargs['slug'])

models.py

type Article. , . , ChildrenView, YouthView AdultView music ( - , , ).

ARTICLE_TYPE_CHOICES = (
    (0, 'music'),
    (1, 'weddings'),
    (2, 'outreach'),
    ...
)

class Article(models.Model):
     ...
     type = models.IntegerField(choices=ARTICLE_TYPE_CHOICES)
     ...

view.py

class SuperSpecialAwesomeView(DetailView):
    template_name = None
    model = Article
    def get_template_names(self):
        slug = self.kwargs.get('slug', '')
        templates = [
            # create a template based on just the slug
            '{0}.html'.format(slug),
            # create a template based on the model type
            '{0}.html'.format(self.object.get_type_display()),
        ]
        # Allow for template_name overrides in subclasses
        if self.template_name is not None:
            templates.insert(0, self.template_name)

        return templates

music slug ministry/children, Django ministry/children.html music.html.

(, , , SermonsView), SuperSpecialAwesomeView

class SermonsView(SuperSpecialAwesomeView):
    paginate_by = 2
    queryset = Article.objects.order_by('-publish_date')
+6

: ( ). DetailView , get_template_names, ( , try: except:). "" . , , . FrontPageView , , , . , , , Mixins.

+1

Rarely can I find places where I need to use CBD.

You can reorganize it like this:

def editable_page(slug):
    return {
        'context': {
            'slug': slug
        }
        'template': 'mysupertemplates/{0}.html'.format(slug)
    }

def frontpage(req):
    return editable_page('frontpage')

def chat(req):
    return editable_page('char')

def about(req):
    return editable_page('about')
0
source

Source: https://habr.com/ru/post/1544961/


All Articles