Ben Kilah
Ben Kilah

Reputation: 3475

Django initial value of choicefield

I'm having a strange problem where I can't seem to set the initial value of one of the fields in my forms in django.

My model field is:

section = models.CharField(max_length=255, choices=(('Application', 'Application'),('Properly Made', 'Properly Made'), ('Changes Application', 'Changes Application'), ('Changes Approval', 'Changes Approval'), ('Changes Withdrawal', 'Changes Withdrawal'), ('Changes Extension', 'Changes Extension')))

My form code is:

class FeeChargeForm(forms.ModelForm):
    class Meta:
        model = FeeCharge
        # exclude = [] # uncomment this line and specify any field to exclude it from the form

    def __init__(self, *args, **kwargs):
        super(FeeChargeForm, self).__init__(*args, **kwargs)
        self.fields['received_date'] = forms.DateField(('%d/%m/%Y',), widget=forms.DateTimeInput(format='%d/%m/%Y', attrs={'class': 'date'}))
        self.fields['comments'].widget.attrs['class']='html'
        self.fields['infrastructure_comments'].widget.attrs['class']='html'

My view code is:

form = FeeChargeForm(request.POST or None)
form.fields['section'].initial = section

Where section is a url var passed to the function. I've tried:

form.fields['section'].initial = [(section,section)]

With no luck either :(

Any ideas what I'm doing wrong or is there a better way to set the default value (before a form submit) of this choice field from a url var?

Thanks in advance!

Update: It seems to be something to do with the URL variable.. If I use:

form.fields['section'].initial = "Changes Approval"

It works np.. If I HttpResponse(section) it's outputs correctly tho.

Upvotes: 5

Views: 15303

Answers (2)

Mateus Padua
Mateus Padua

Reputation: 193

The problem is use request.POST and initial={'section': section_instance.id}) together. This happens because the values of request.POST always override the values of parameter initial, so we have to put it separated. My solution was to use this way.

In views.py:

if request.method == "POST":
    form=FeeChargeForm(request.POST) 
else:
    form=FeeChargeForm() 

In forms.py:

class FeeChargeForm(ModelForm):
    section_instance = ... #get instance desired from Model
    name= ModelChoiceField(queryset=OtherModel.objects.all(), initial={'section': section_instance.id})

---------- or ----------

In views.py:

if request.method == "POST":
    form=FeeChargeForm(request.POST) 
else:
    section_instance = ... #get instance desired from Model
    form=FeeChargeForm(initial={'section': section_instance.id}) 

In forms.py:

class FeeChargeForm(ModelForm):
    name= ModelChoiceField(queryset=OtherModel.objects.all())

Upvotes: 4

rolling stone
rolling stone

Reputation: 13016

UPDATE Try escaping your url. The following SO answer and article should be helpful:

How to percent-encode URL parameters in Python?

http://www.saltycrane.com/blog/2008/10/how-escape-percent-encode-url-python/

Try setting the initial value for that field as follows and see if that works:

form = FeeChargeForm(initial={'section': section})

I assume you're going to be doing a lot of other things when the user posts the form, so you could separate the POST form from the standard form using something like:

if request.method == 'POST':
    form = FeeChargeForm(request.POST)
form = FeeChargeForm(initial={'section': section})

Upvotes: 1

Related Questions