2017-11-03 13 views
1

ユーザーが電子メールを入力するフォームを作成しようとしています。通常、電子メールの検証エラー(空欄または適切な形式ではない)がブラウザによって表示されます。検証エラーがDjangoフォームに表示されない

基本的なフォームの例を使用して、すべてが正しく示しています。私の場合は

<form action="/notify-email/add/" method="post"> 
    {% csrf_token %} 
    {{ form }} 
    <input type="submit" value="Submit" /> 
</form> 

enter image description here

を、私は電子メールを保存し、モーダルを表示するAJAX要求を使用して検証エラーがない場合あなたにメッセージありがとうございます。しかし、妥当性チェックの誤りがある場合は、私が動かすだけで私はそれらを見ることができます。 enter image description here

また、検証にエラーがあった場合でもモーダルが表示されます。

これは私のmodels.pyです:

from django import forms 
from landing.models import NotifyEmail 


class NotifyEmailForm(forms.ModelForm): 
    class Meta: 
     model = NotifyEmail 
     fields = ["email"] 

    def __init__(self, *args, **kwargs): 
     super(NotifyEmailForm, self).__init__(*args, **kwargs) 

     self.fields['email'].widget = forms.EmailInput(attrs={'placeholder': 'Email', 
                   'required': True}) 

私のviews.py:

from django.shortcuts import render 
from django.http import JsonResponse 
from .forms import NotifyEmailForm 



def add_notify_email(request): 
    if request.method == "POST": 
     form = NotifyEmailForm(request.POST) 

     if form.is_valid(): 
      form.save(commit=True) 
      print("Email Added.") 
      return JsonResponse({'msg': 'Data saved'}) 
     else: 
      print("Error in Notify Form") 
      return JsonResponse({"msg": "Error"}) 

    else: 
     form = NotifyEmailForm() 
    return render(request, "landing/home.html", {"form": form}) 

私urls.py

from django.db import models 


class NotifyEmail(models.Model): 
    email = models.EmailField(max_length=255) 
    date_added = models.DateField(auto_now_add=True) 
    time_added = models.TimeField(auto_now_add=True) 

    def __str__(self): 
     return self.email 

これは、モデルに基づいた形であります:

from django.conf.urls import url 
from . import views 

urlpatterns = [url(r'^notify-email/add/$', views.add_notify_email)] 

htmlコード:

<div class="container-fluid" id="comingSoon"> 
    <div class="container"> 
     <h2>Coming Soon</h2> 
     <h5>If you want to get notified when we go live, please enter your email below.</h5> 
    </div> 
    <div class="container" id="notify-email-container"> 
     <form action="/notify-email/add/" method="post" id="notify-email-form"> 
      {% csrf_token %} 
      <div class="form-group row"> 
       <div class="col-sm-10" id="email-input-container"> 
        <input class="form-control" type="email" name="email" placeholder="Your email...." maxlength="255" required id="id_email" /> 
       </div> 

       {% for error in form.email.errors %} 
        <div class="alert alert-error"> 
         <p class="field-error"><i class="fa fa-exclamation-circle" aria-hidden="true"></i>{{ error|escape }}</p> 
        </div> 
       {% endfor %} 
       <div class="col-sm-2"> 
        <button type="button" class="btn btn-block btn-primary" onclick="addNotifyEmail()" id="submit-notify-email">Notify Me</button> 

       </div> 
      </div> 
     </form> 
    </div> 
</div> 


<div class="modal" tabindex="-1" role="dialog" id="thanks"> 
    <div class="modal-dialog" role="document"> 
    <div class="modal-content"> 
     <div class="modal-header"> 
     <h5 class="modal-title">Thank you</h5> 
     <button type="button" class="close" data-dismiss="modal" aria-label="Close"> 
      <span aria-hidden="true">&times;</span> 
     </button> 
     </div> 
     <div class="modal-body"> 
     <p>We would like to thank you for your interest.</p> 
     </div> 
     <div class="modal-footer"> 
     <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> 
     </div> 
    </div> 
    </div> 
</div> 

<script> 
    function addNotifyEmail(e){ 
     var notifyEmailForm = $("#notify-email-form"); 
     var thanksModal = $("#thanks"); 

     $.ajax({ 
     type: 'POST', 
     url: '/notify-email/add/', 
     data: notifyEmailForm.serialize(), 
     success: function(res){ 
        thanksModal.modal('show')} 

    })} 
</script> 

答えて

0

私はあなたの質問をよく理解してることはよく分かりません。

この問題は、「エラー」divに表示されるいくつかの検証エラーがある場合にのみ表示されます。そうである場合は、cssまたはjavascriptに関連しています。スクリプトとCSSファイルを確認してください。おそらくどこかで.field-error要素をトリガーします。

モーダルアフェアンスについてさて、あなたのAJAXリクエストについてです。

あなたのコードでは、HTTP Requestが200コードで回答を得ている間に、あなたのモーダルが表示されます。たとえ有効なフォームを持っていなくても、JsonResponseにいくつかのmsgを送ってそのページに戻すと、スクリプトが毎回successをトリガーするので、あなたのモーダルが表示されます。

JsonResponse({"msg": "Error"})を送信するだけでなく、エラーを処理するためにも使用してください。

function addNotifyEmail(e){ 
    var notifyEmailForm = $("#notify-email-form"); 
    var thanksModal = $("#thanks"); 

    $.ajax({ 
    type: 'POST', 
    url: '/notify-email/add/', 
    data: notifyEmailForm.serialize(), 
    success: function(res){ 
     if(res.msg !== "Error") { 
       thanksModal.modal('show'); 
     } 
    } 
})} 

AJAX要求でエラーを処理の詳細について見hereてください。

+0

電子メールのブラウザでは、通常、電子メールアドレスに@を含めるようなポップアップが表示されます このポップアップメッセージは、フォームの基本的な例では表示されますが、アヤックス1 – GiannisIordanou

+0

まあ、問題は間違いなく添付のidsとクラスに関連しており、それはCSSまたはJSを意味します。カスタムIDとクラスを削除してみてください。問題が存在する場合は、オプションタグ(div)を削除してみてください。基本的なDjango Formを使用する場合は、必要な要素をすべて必要な要素にレンダリングします。期待どおりに動作するDjango FormのHTMLコードとあなたのコードを比較することができます。そして、問題を検出するためにDjango Formバージョンに来て、ステップバイステップに進んでみてください。あなたがそれを見つけることを願っています。 – catscoolzhyk

+0

たとえば、入力parent(div)からそのid(email-input-container)を削除して、トップdiv削除クラス "row"から削除してみてください。 あなたのモーダルの問題はどうですか? – catscoolzhyk

関連する問題