tags:

views:

353

answers:

3

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 try to get its values back in the form

 form = SearchJobForm(request.GET)

but it doesn't work(some fields dissapear). Maybe it's because of the ModelChoiceField. How do i fill the form with its values using get method?

A: 

Form objects should descend from django.forms.Form:

from django import forms

class SearchJobForm(forms.Form):
    query = forms.CharField()
    types = forms.ModelChoiceField()
mipadi
I have it in my code, just forgot to paste here
barin
The problem is somewhere else.
barin
Please edit your question to reflect that. And see my comment to your question: what is not getting populated in the form and how are you checking that the data was populated?
celopes
A: 

Actually, could you post your entire view method? I just tested it and doing

form = SearchJobForm(request.GET)

works fine. It has to be a problem at the surrounding code...


From your code I think you are expecting the form values to render back in HTML with the values populated... Is that how you are trying to check that the form object was populated? This won't work (and probably isn't what you want to do anyhow - you want to process the form values).

Try adding this to your view:

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)

Check what gets printed out.

You really should go through this trail from the django docs.

celopes
A: 

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

SearchJobForm(initial=request.GET)
Harold