Form not validating in Django

771 Views Asked by At

I have a weird issue with a Django form. There is this form where I can accomplish different actions according to which submit button was clicked. At some point in the development, everything worked fine: my form was validating OK and it was doing exactly what I wanted it too. But now (and I really don't know what I could have done wrong to break it), the submit actions just don't work. I don't receive any errors, it just does nothing.

Here is the code in my forms.py file:

class AssetModif(forms.Form):    
    def __init__(self, *args, **kwargs):
        proj_id = kwargs.pop('proj_id')
        super(AssetModif, self).__init__(*args, **kwargs)
        self.proj_id = proj_id
        EPISODE_CHOICES = [('-1', '------------')]
        for e in Project.objects.filter(proj_id_parent=proj_id).order_by('proj_saison', 'proj_numepisode'):
            EPISODE_CHOICES.append((e.proj_name,
                "e" + str(e.proj_saison).zfill(2) + str(e.proj_numepisode).zfill(2) +
                "_" + e.proj_name))
            self.fields['episodes'].choices = EPISODE_CHOICES
            self.fields['episode_etat'].choices = EPISODE_CHOICES

    TYPE_CHOICES = [(type.type_name, type.type_name) for type in Type.objects.all()]
    ASSET_CHOICES = (('', '-- choisir un type en premier'))

    type = forms.ChoiceField(choices=TYPE_CHOICES,
                widget=forms.Select(attrs={'onchange':'get_asset_from_type();'}))
    asset = LazyChoiceField(choices=ASSET_CHOICES, required=False)
    episodes = forms.ChoiceField()

    etat = forms.CharField()
    episode_etat = forms.ChoiceField()

    commentaire = forms.CharField(widget=forms.Textarea)

Plus some save_action() methods that I can add if someone asks. The code in my views.py:

def modif_asset(request):
    try:
        proj = request.session['proj']
        nom = request.session['nom']
    except:
        request.session['proj'] = 1
        proj = request.session['proj']
        request.session['nom'] = ""
        nom = ""

    if request.method == 'POST' and (request.POST.get("action_add_episode", "") == "Ajout Episode"):
        form = AssetModif(request.POST, proj_id = request.session['proj'])
        if form.is_valid():
            asset = form.save_episode()
            #return HttpResponseRedirect(reverse('menu'))
            return render_to_response("asset/modif.html", {'proj':proj, 'form':form, 'asset':asset}, context_instance=RequestContext(request))
        else:
            asset = form.save_episode()
            return render_to_response("asset/modif.html", {'proj':proj, 'form':form, 'asset':"toooooooo"}, context_instance=RequestContext(request))

    elif request.method == 'POST' and (request.POST.get("action_delete_asset", "") == "Suppression BDD"):
        form = AssetModif(request.POST, proj_id = request.session['proj'])
        if form.is_valid():
            asset = form.delete_asset()
            #return HttpResponseRedirect(reverse('menu'))
            return render_to_response("asset/modif.html", {'proj':proj, 'form':form, 'asset':asset}, context_instance=RequestContext(request))

    elif request.method == 'POST' and (request.POST.get("action_ajout_etat", "") == "Ajout Etat"):
        form = AssetModif(request.POST, proj_id = request.session['proj'])
        if form.is_valid():
            asset = form.save_etat()
            return render_to_response("asset/modif.html", {'proj':proj, 'form':form, 'asset':asset}, context_instance=RequestContext(request))

    elif request.method == 'POST' and (request.POST.get("action_ajout_comment", "") == "Ajout Commentaire"):
        form = AssetModif(request.POST, proj_id = request.session['proj'])
        if form.is_valid():
            asset = form.save_comment()
            return render_to_response("asset/modif.html", {'proj':proj, 'form':form, 'asset':asset}, context_instance=RequestContext(request))

    else:
        form = AssetModif(proj_id=request.session['proj'])

    c = {'proj': proj, 'form':form, 'asset':" Miiii "}
    c.update(csrf(request))
    return render_to_response("asset/modif.html", c, context_instance=RequestContext(request))

And my template is like this:

<form method="POST" action="" name="form_modif">{% csrf_token %}
  <table>
    <tr><td> Type </td><td> {{ form.type }} </td>
    <td> Asset </td><td> {{ form.asset }} </td></tr>
  </table>

  <div id="ajout_episode">
    <p><b> Premier &eacute;pisode de l'asset </b></p>
    <table>
      <tr><td>Episode</td><td> {{ form.episodes }}</td></tr>
      <tr><td><input type="submit" name="action_add_episode" value="Ajout Episode" /></td></tr>
    </table>
  </div>

  <div id="creation_etat">
    <p><b> Ajout d'un &eacute;tat </b></p>
    <table>
      <tr><td>Etat</td><td> {{ form.etat }}</td></tr>
      <tr><td>Premier &eacute;pisode de l'&eacute;tat</td><td> {{ form.episode_etat }}</td></tr>
      <tr><td><input type="submit" name="action_ajout_etat" value="Ajout Etat" /></td></tr>
    </table>
  </div>

  <div id="ajout_comment">
    <p><b> Ajout d'un commentaire </b></p>
    <table>
      <tr><td> {{ form.commentaire }}</td></tr>
      <tr><td> <input type="submit" name="action_ajout_comment" value="Ajout Commentaire" /></td></tr>
    </table>
  </div>

  <div id="suppression_bdd">
    <p><b> Suppression de l'asset en BDD </b></p>
    <input type="submit" onclick="return verifier();" name="action_delete_asset" value="Suppression BDD" />
</form>

I'd really appreciate any help as I'm completely stuck with it

2

There are 2 best solutions below

0
On

Not an answer too much, but pointers on getting the errors.

Your first starting point should be to look for field errors, you're currently not outputting them at all.

So if you do

    <div id="ajout_episode">
    <p><b> Premier &eacute;pisode de l'asset </b></p>
    <table>
    <tr><td>Episode</td><td> {{ form.episodes }}</td></tr>

    <tr><td><input type="submit" name="action_add_episode" value="Ajout Episode" /></td></tr>
    </table>
    {{form.episodes.errors}}
    </div>

Then it'll display the errors for that field. You could use the following snippet for checking errors: http://djangosnippets.org/snippets/1094/

Forms also have a global error variable, though I can't find or remember the name of it at the moment.

6
On
<form method="POST" action="url_to_your_view" name="form_modif">