I have a base_page.html which has a navbar included. I want to place a trigger (button/link) which calls a view to create a new object in DB. Is there a way to create a single “create view” with a form which will be applied around the whole project where a navbar displays?
Yes, but it’s not a “view”.
What you’re looking for is a context processor. See the docs page starting with Using RequestContext, including the section on writing your own context processor.
That will allow you to inject the form into every page in which that object is being rendered. Then you’ll still need to write the view to handle the POST request from that form.
Thanx for a quick response. I’m know that context processors can store and deliver a data within a whole project but in that case I have to create a view on every page to to handle POST request anyway? That makes the context processor useless in my particula case.
There no other way to create an object without duplicating a code on every app I need this functionality?
If the form is being rendered in a base template, then it would be one url that the form would be posting to, regardless of the page in which it resides.
Also, you want to change your perspective. You wrote:
That’s not the way you should be thinking about Django. Django views create the pages. You don’t create a view on any page. A page can submit data to a view. And a “page” is the output of a view.
Thank your for detailed answer. Now I got the point.
I made a form renders globaly utilizing context processor as per your advice. But I’m still confused regarding processing the POST request. Every view renders a single .html page and it sends/receives data from that page only. So even I have a form renders in a base_page from a context processor I still need a lot of views for every app to process the POST request is being passed from that form. I’m right? If not could you please explain with more details on how to make a code more DRYer processing that POST request with a single view?
No, you are not correct.
That form being rendered in the base page should be a complete form - and that means it has its
<form> element as part of what’s being rendered.
<form> element contains the
action attribute, identifying the URL to which that form will be submitted.
If that same form is being rendered in the context processor, it doesn’t matter what view is rendering the page extending that base page. Every instance of that base page being rendered is going to have the same
action attribute in that form - which means all submissions for that form will be sent to the same url - and therefore the same view.
That is complitely clear now.
Thank you for a guidance!