Sam
Sam

Reputation: 388

How to create a simple form in the base html template django

I have a Django app that contains multiple pages. Like the menu or footer, some elements are repeated in all of these pages, so I created a base template and added these duplicated codes. Now I want to have a form above the footer in the base template. But I don't know how to make it work. Should I make a view that returns the base.html? How can I inherit this form on every page of the website? Please guide me; I'm in a bit of a pickle!

this is my context_processor :

def base_forms(request):
    return {       
        'info_form': BasedContactForm()
    }

and this is my base.html: I extend it in all other pages:

<form method="post" action="">
      {% csrf_token %}
      {{ info_form }}
   </form>

and this is my Blog app views:

def base_info_form(request):
 if request.method == 'POST':
    info_form = BaseContactForm(request.POST)
    if info_form.is_valid():
        info_form.save()
        return redirect('Home-Page')
    else:
        info_form = BaseContactForm()
    return render(request, '', {'info_form': info_form})

Upvotes: 1

Views: 1019

Answers (1)

NKSM
NKSM

Reputation: 5854

You can add some data to global context through settings TEMPLATES > OPTIONS > context_processors - Writing your own context processors.

And for extending templates use template tag extends(Django Docs).

1. Adding variable to context


Create yourapp/context_processors.py:

from django.conf import settings

from yourapp.forms import MyForm


def base_data(request):
    data = {}
    # MyForm(request.GET, user=request.user)
    data["my_form"] = MyForm()
    data["my_email"] = settings.MYEMAIL
    return data

And add it to context_processors in settings.py:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
           ...
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                ...
                'yourapp.context_processors.base_data',
            ],
        },
    },
]

Now you can access your this data in any template:

{{ my_form }}, {{ my_email }}

2. Extending Templates


You can also use template tag extends(Django Docs) to extend your templates:

template.html
base.html

In template.html, the following paths would be valid:

{% extends "base.html" %}
<div class="container">
    Some HTML code
</div>

Additional info TEMPLATES(Django Docs) and OPTIONS (Django Docs) available parameters.

UPDATE


views.py:

def contact(request):
    if request.method == 'POST':
        form = BaseContactForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('Home-Page')
    else:
        form = BaseContactForm()
    return redirect(request.META.get('HTTP_REFERER'))

urls.py:

path('contact/', views.contact, name='contact'),

Upvotes: 1

Related Questions