Django 中的表单无法验证

发布于 2024-12-11 14:36:15 字数 5682 浏览 0 评论 0原文

我对 Django 表单有一个奇怪的问题。在这个表单中,我可以根据单击的提交按钮来完成不同的操作。在开发过程中的某个时刻,一切都运行良好:我的表单验证正常,并且它也完全按照我的要求进行。但现在(我真的不知道我可能做错了什么来破坏它),提交操作不起作用。我没有收到任何错误,它什么也没做。

这是我的 forms.py 文件中的代码:

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)

加上一些 save_action() 方法,如果有人询问,我可以添加这些方法。我的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))

我的模板是这样的:

<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 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 é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 état </b></p>
    <table>
      <tr><td>Etat</td><td> {{ form.etat }}</td></tr>
      <tr><td>Premier épisode de l'é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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

公布 2024-12-18 14:36:15

不是太多的答案,而是关于错误的提示。

您的第一个起点应该是查找字段错误,您目前根本没有输出它们。

因此,如果您

    <div id="ajout_episode">
    <p><b> Premier é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>

这样做,那么它将显示该字段的错误。
您可以使用以下代码片段来检查错误: http://djangosnippets.org/snippets/1094/

表单还有一个全局错误变量,尽管我目前找不到或记住它的名称。

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 é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.

萝莉病 2024-12-18 14:36:15
<form method="POST" action="url_to_your_view" name="form_modif">
<form method="POST" action="url_to_your_view" name="form_modif">
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文