2

I'm setting up my layout in Django using functional views but decide to change it out for classes. I'm a bit lost as to how I can get the information from the views into my template however.

My first attempt was below

class Menu(generic.ListView):
  model = Categories
  template_name = 'portfolio/layout.html'
  context_object_name = 'category_list'
  # def get_queryset(self):
    # return Categories.objects.all()

class IndexView(Menu):
  template_name = 'portfolio/index.html'

This allowed me to set up layout.html with my menu items by iterating through "category_list". The menu items carried over in index.html that extended layout.html

After doing a bit more research, I decided to set up my views as follows:

class MenuView(object):
  def get_context_data(self, *args, **kwargs):
    context = super(MenuView, self).get_context_data(*args, **kwargs)
    context['menu'] = Categories.objects.all()

    return context

class LayoutView(generic.TemplateView):
  template_name = 'portfolio/layout.html'

I'm still getting my head around how this works, but according to this tutorial (https://blog.safaribooksonline.com/2013/10/28/class-based-views-in-django/) I think I am updating the get_context_data function to include my query for the Categories model. I can't figure out how to access context['menu'] to display into my template however.

1 Answer 1

2

Your MenuView class should be a subclass of one of the class-based view classes rather than object - which one depends on what behavior you're expecting. Possibly TemplateView if you just want to display a template with context information.

Accessing context variables in the template works the same way whether the context was built by a functional view or a class-based view - your queryset of categories will be available as {{ menu }}, or you can iterate through with {% for category in menu %}, etc.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.