devashish-patel
devashish-patel

Reputation: 723

Clean `ChoiceField` from Django Form

Model:

class SocialGroup(models.Model):
    INDIVIDUAL = 'individual'
    INSTITUTE = 'institute'
    options = ((INDIVIDUAL, 'Individual'),
               (INSTITUTE, 'Institute'))
    level = models.CharField(choices=options, max_length=100)

    def __unicode__(self):
        return self.name

    class Meta:
        ordering = ['name']

Form:

class GroupLevelForm(forms.Form):
    level = forms.ChoiceField(choices=SocialGroup.options)

    def clean_level(self):
        return self.cleaned_data['level']

When I call my form I do it like level = GroupLevelForm({level: 'Individual'}). I want individual back into cleaned data.

Thanks in advance!

Upvotes: 2

Views: 1760

Answers (2)

eman.lodovice
eman.lodovice

Reputation: 192

If I understand the question correctly, I think you can do

def clean_level(self):
    selected_display_name = self.cleaned_data['level']
    for val, disp_name in SocialGroup.options:
        if disp_name == selected_display_name:
            return val
    return selected_display_name  # or whatever default you want

Upvotes: 1

rchurch4
rchurch4

Reputation: 899

The error is occurring because you don't call is_valid() on your form at any time. cleaned_data only exists once that has been called.

You want something along the lines of [pseudocode incoming]:

def clean_fields():
    if form.is_valid():
        self.cleaned_data['level']

Refer to the docs for django's explanation: building a form

Upvotes: 3

Related Questions