Reputation: 6238
I have a parent template that I'm using in many parts of the site, called base.html
. This template holds a lot of functional components, such as buttons that trigger different forms (inside modal windows) allowing users to upload different kinds of content, etc. I want users to be able to click these buttons from almost any part of the site (from all the templates that inherit from base.html
).
I've written a view that handles the main page of the site, HomeView
(it renders homepage.html
, which inherits from base.html
). I've written a bunch of functionality into this view, which handles all the uploads.
Since many templates are going to inherit from base.html
, and therefore have all that same functionality, do I have to copy-and-paste the hundreds of lines of code from the HomeView
into the views that render all the other pages??
There's got to be a better way, right?
How do I make sure that the functionality in a parent base template holds true for all views which call child templates that inherit from this base template?
Upvotes: 1
Views: 323
Reputation: 1060
you can put all the lines of code from HomeView
in a separate function let be func
and have func
return a dictionary containing all context variables needed
and call it whenever needed so your HomeView
would look like this:
def HomeView(request):
dict = func(request)
... # rest of code that is not common with other views
and your func
would look like:
def func(request):
#all repeated code
#put all needed variables in a dictionary and return it
dict = {'var1': 4, 'var2': "a String" ...}
return dict
Upvotes: 1
Reputation: 64
Load the functionality part with ajax on your base.html.
That way you have a view_method that deals exclusively with those funcionalities.
Upvotes: 0
Reputation: 4816
Use TemplateResponse
instead of HttpResponse
in home_view
. This way you will be able to update context and switch template on the response.
Call home_view
inside other views like this:
from django.template.response import TemplateResponse
def other_view( request ):
#produce other_context
t = home_view( request )
t.context.update( other_context )
t.template = 'other_template.html'
return t
Upvotes: 0
Reputation: 22808
You can render many templates in just one view by requiring unique value in each or use request session.
Upvotes: 0
Reputation: 53386
I believe separating out your upload related functionality into separate views will be better way to go about it. That way all your templates (inheriting from base.html
) will refer to appropriate view for uploads.
You can use HTTP_REFERER
header to redirect to appropriate page from the upload views.
Upvotes: 0