I have a form which is needed in all the view functions of my django project.
I have a common template for printing the form but for this I have to pass the form from all my view functions.
I have about 8 apps. To include the form in all my view functions. Plus the form can be bound or blank depending on a session value.
If I write the lines for including the form I have to write 5 lines. So I have to write those 5 lines to all my view functions. Any way to do this in a better way?
forms.py
class LanguageSelectForm(forms.Form):
language = forms.ModelChoiceField(empty_label='--Select A Language--', queryset=Language.objects.all(),
widget=forms.Select(attrs={'class': 'form-control'}))
in views.py
form = LanguageSelectForm
if 'language_id' in request.session:
form_data = dict()
form_data['language'] = request.session['language_id']
form = LanguageSelectForm(form_data)
these are the 5 lines i had to put on all of my view functions.
As @Mubariz Feyziyev mentioned, you can use context processors to render your form in each template. This is one way to this. Additionally,
If you are OK with not using django forms:
action value to a particular url like /api/handle-my-nice-form,url record (/api/handle-my-nice-form/)If you are new to Django, You should use built-in forms. But as your app grows and gets complicated or if you decided to use a library like React or Angular; it might be better building an api based system to handle this kind of stuff.
If you can want to use this form in django templates(every) you must write context processors: Please read this links:
https://docs.djangoproject.com/en/1.10/_modules/django/template/context_processors/
https://docs.djangoproject.com/en/1.10/ref/templates/api/#writing-your-own-context-processors