Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django initial value of choicefield

Tags:

python

django

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.

like image 385
Ben Kilah Avatar asked Oct 24 '11 05:10

Ben Kilah


People also ask

What is initial in Django forms?

initial is used to change the value of the field in the input tag when rendering this Field in an unbound Form. initial accepts as input a string which is new value of field. The default initial for a Field is empty. Let's check how to use initial in a field using a project.

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

What is CharField in Django?

CharField is a string field, for small- to large-sized strings. It is like a string field in C/C+++. CharField is generally used for storing small strings like first name, last name, etc. To store larger text TextField is used. The default form widget for this field is TextInput.

What is the superclass of Django form?

Django provides a Form class which is used to create HTML forms. It describes a form and how it works and appears. It is similar to the ModelForm class that creates a form by using the Model, but it does not require the Model.


1 Answers

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())
like image 161
Mateus Padua Avatar answered Sep 22 '22 21:09

Mateus Padua