2

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"}
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
Abhinav Nair
  • 116
  • 10

2 Answers2

2

Try adding {{ form.non_field_errors }} to your template. This will show you errors not related to fields.

Also, if you can, for the sake of debugging, do this instead of {{ form.as_p }}

{% for field in form.fields %}
    <div>{{ field }}</div>
    {% if field.errors %}
            <div class="alert alert-danger">
                {{ field.errors }}
            </div>
    {% endif %}
{% endfor %}

See if that shows some errors on POSTing.

  • Thanks for the quick response. I had tried that earlier too but I wasn't sure where to look for the error. But now I notice that on POSTing, I can see class="error" being set for the select element in each select tag. Forgive the naive question, but what does this mean and how do I proceed to find the root of the problem? – Abhinav Nair Jul 16 '14 at 02:00
  • Forgive the naive question, but where am I supposed to look for these? If they are supposed to show up in on the web-page next-to/around the fields they don't. I noticed no change anywhere except the addition of class="error" in my select tags in firebug. – Abhinav Nair Jul 16 '14 at 02:43
  • Oh, I just noticed your ajax.py file and realized that you're probably setting the class yourself. `dajax.add_css_class('#id_%s' % error, 'error')` Can you `print form.errors` somewhere in the else clause? Or return them as HTTP response? –  Jul 16 '14 at 11:22
  • Good suggestion. I did print it as a dajax alert and got this.
    Form is_notvalid(), your error is:
    • Disc
      • Select a valid choice. That choice is not one of the available choices.
    • Env
      • Select a valid choice. That choice is not one of the available choices.
    • Branch
      • Select a valid choice. That choice is not one of the available choices.
    .
    This is despite selecting things correctly and getting the post with correct arguments as shown above.
    – Abhinav Nair Jul 16 '14 at 13:33
  • Do you think it is because instead of actually sending the form as an argument, it is sending form elements? – Abhinav Nair Jul 16 '14 at 14:44
  • Can you use some developer tools for the browser and see exactly what is being POSTED to the view? –  Jul 16 '14 at 15:48
  • I added that to my original question. I used firebug to check that and here's what's getting posted argv {"form":"Branch=Master&Env=ProdCoursera&Disc=ChemistryMOOC"} – Abhinav Nair Jul 16 '14 at 17:36
  • Source argv=%7B%22form%22%3A%22Branch%3DMaint%26Env%3DStaging%26Disc%3DAuthoring%22%7D – Abhinav Nair Jul 16 '14 at 17:38
  • I'm not familiar with Dajax, but shouldn't you use `form = BedSelectForm(request.POST)`? –  Jul 16 '14 at 17:39
  • It does the same thing. No change in output whatsoever. But the debugging suggestions you've made lead me to think that on validation, the choices are being compared to an empty list? I am populating my ModelChoiceFields from my database. Do you have any idea how I could turn off auto validation? At this point, I really don't know what I'm doing wrong. :/ – Abhinav Nair Jul 16 '14 at 18:10
  • http://www.dajaxproject.com/fullform/ Here's the link to the example I'm referring too. Seemed pretty straightforward for CharFields. That's really the only major difference. – Abhinav Nair Jul 16 '14 at 18:13
  • I'm at a loss to explain. I have no idea, sorry :( –  Jul 16 '14 at 18:41
  • All of you , Look at the answer below. That will solve your issue. It has solved mine. :) – Shashank Hegde Dec 31 '16 at 05:13
1

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()]
Abhinav Nair
  • 116
  • 10