Optimized way of submitting form in all django view functions
I have form
one that is needed in all the view functions of my django project .
I have a common template
printable form, but for this I need to pass the form from all of my view functions.
I have about 8 applications . To include the form in all my view functions. In addition, the form can be anchored or empty depending on the session value.
If I write lines to include a form, I have to write 5 lines. So I have to write these 5 lines to all the functions of my view. Any way to make it better?
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 5 lines i had to overlay all my view functions.
source to share
If you can use this form in django templates (each) you should write context processors: Please read the following 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
source to share
As stated @Mubariz Feyziyev
, you can use context processors
to render your form in every template. This is one way to do it. Besides,
If you're ok with not
using django forms:
- Build your form with pure client side html,
- Set the value
action
for a particular URL-addresses, for example/api/handle-my-nice-form
, - Create a view that handles this form request and connects it to the record
url
(/api/handle-my-nice-form/
)
If you are new to Django
, you should use inline forms. But as your application grows and becomes more complex, or if you decide to use a library like React
or Angular
; perhaps a better build an api based system
to handle this kind of thing.
source to share