Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

85
Views
optimized way of passing a form in all view functions django

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.

8 months ago · Santiago Trujillo
2 answers
Answer question

0

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:

  • Create your form with pure html on client side,
  • Set its action value to a particular url like /api/handle-my-nice-form,
  • Create a view that handles this form's request and connect it to 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.

8 months ago · Santiago Trujillo Report

0

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

8 months ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.