Search code examples
pythondjangoformsdajaxicedajax

django form.is_valid() always returns false


My is valid function in my view always seems to be returning false even though the post seems to be sending the right data (I think). I'm pretty new to django and python and I'm using the Django Docs as a guide. I am also trying to implement my form using the django form example in dajax (I have already installed and used dajax successfully in the same project). My other Dajax methods are get methods and I'm sure they don't interfere with my post.

Each time I hit post, the "form is not valid" error alert I have shows up and I am not sure why it doesn't enter the if block.

I have read similar questions on here and have double checked everything I could think of. I would be so grateful if anyone could help point out where the problem is. I am pasting the required code below.

forms.py

class BedSelectForm(forms.Form):
Branch = forms.ModelChoiceField(
    label = u'Branch',
    queryset = Result.objects.values_list('branch', flat =True).distinct(),
    empty_label = 'Not Specified',
    widget = forms.Select(attrs = {'onchange' : "Dajaxice.modmap.updatecomboE(Dajax.process, {'optionB':this.value})"})
    )
Env = forms.ModelChoiceField(
    label = u'Environment',
    queryset = Result.objects.values_list('environment', flat =True).distinct(),
    empty_label = 'Not Specified',
    widget = forms.Select(attrs = {'onchange' : "Dajaxice.modmap.updatecomboD(Dajax.process, {'optionE':this.value})"})
    )
Disc = forms.ModelChoiceField(
    label = u'Discipline',
    queryset = Result.objects.values_list('discipline', flat =True).distinct(),
    empty_label = 'Not Specified'

    )

template.html

<form action="" method="post" id = "select_form">
        <div style = "color :white" class="field_wrapper">
             {{ form.as_p }}
        </div>        
        <input type="button" value="Display Table" onclick="send_form();"/>
</form>

<script type="text/javascript">
    function send_form(){
        Dajaxice.modmap.dispTable(Dajax.process,{'form':$('#select_form').serialize(true)});
    }
 </script>

ajax.py

@dajaxice_register
def dispTable(request, form):
    dajax = Dajax()
    form = BedSelectForm(deserialize_form(form))

    if form.is_valid():
        dajax.remove_css_class('#select_form input', 'error')
        dajax.alert("Form is_valid(), your username is: %s" % form.cleaned_data.get('Branch'))
    else:
        dajax.remove_css_class('#select_form input', 'error')
        for error in form.errors:
            dajax.add_css_class('#id_%s' % error, 'error')
        dajax.alert("Form is_notvalid()")

    return dajax.json()

This is what my post looks like..

argv    {"form":"Branch=Master&Env=ProdCoursera&Disc=ChemistryMOOC"}

Solution

  • I found the solution to my problem. I was trying to pick tuples using a ModelChoiceField which is a very hacky way of doing things because a ModelChoiceField expects model objects not arbitrary strings.

    I replaced my forms with Choice Fields and populated them by overriding the init function. Below are the changes I made to my form for reference. I hope this helps someone!

    class BedSelectForm(forms.Form):
    Branch = forms.ChoiceField(
        choices = [],)
    
    Env = forms.ChoiceField(
        choices = [],)
    
    Disc = forms.ChoiceField(
        choices = [],)
    
    def __init__(self, *args, **kwargs):
        super(BedSelectForm, self).__init__(*args, **kwargs)
        self.fields['Branch'].choices = [(x.pk, x.branch) for x in Result.objects.distinct()]
        self.fields['Env'].choices = [(x.pk, x.environment) for x in Result.objects.distinct()]
        self.fields['Disc'].choices = [(x.pk, x.discipline) for x in Result.objects.distinct()]