Django: fill out the get method form

The form:

class SearchJobForm(forms.Form):
    query = forms.CharField()  
    types = forms.ModelChoiceField(queryset=JobType.objects.all(), widget=forms.CheckboxSelectMultiple())

View

def jobs_page(request):
if 'query' in request.GET:
    form = SearchJobForm(request.GET)
else:
    form = SearchJobForm()
variables = RequestContext(request, {

                                     'form':form,
                                     })
return render_to_response('jobs_page.html', variables)

After I submit the form, I will try to return its values ​​in the form

 form = SearchJobForm(request.GET)

but it does not work (some fields disappear). Perhaps this is due to ModelChoiceField. How to fill out a form with your values ​​using the get method?

+3
source share
3 answers

It looks like you are trying to show the user a pre-filled form. To do this, you need to pass the initial argument to your form:

SearchJobForm(initial=request.GET)
+6
source

Actually, can you post your entire browsing method? I just tested it and did

form = SearchJobForm(request.GET)

works great. This should be a problem for the surrounding code ...


, , HTML ... , ? (, , , - ).

:

def jobs_page(request):
    if 'query' in request.GET:
        form = SearchJobForm(request.GET)
        if form.is_valid():
            print form.cleaned_data['query']
            print form.cleaned_data['types']
        else:
            print form.errors
    else:
        form = SearchJobForm()
    variables = RequestContext(request, {
                                 'form':form,
                                 })
    return render_to_response('jobs_page.html', variables)

, .

django docs.

+1

Form objects must be omitted from django.forms.Form:

from django import forms

class SearchJobForm(forms.Form):
    query = forms.CharField()
    types = forms.ModelChoiceField()
0
source

Source: https://habr.com/ru/post/1725078/


All Articles