代码之家  ›  专栏  ›  技术社区  ›  boyenec

如何在html模板中显示djago验证错误消息?

  •  0
  • boyenec  · 技术社区  · 4 年前

    我为每个提交的表单设置了max_length限制。我希望当任何用户超过最大长度限制时,联系表单将不会被提交并显示错误消息。例如,如果任何用户忘记填写姓名字段,那么它将显示姓名是必需的,或者如果超过最大长度限制,那么它会显示“最多允许300个字符”。这是我的代码:

    #forms.py
    from django import forms
    
    class ContactForm(forms.Form):
        name =  forms.CharField(max_length=300)
        email = forms.EmailField(max_length=300)
        subject = forms.CharField(max_length=1000)
        message = forms.CharField(max_length=3000)
    
    
    #models.py
    from django.db import models
    from django.utils import timezone
    
    # Create your models here.
    class Contact(models.Model):
          current_time = models.DateTimeField(blank=True, null=True,default=timezone.now)
          name =models.CharField(max_length=300)
          subject =models.CharField(max_length=1000, default="")
          email =models.EmailField(max_length=300)
          message = models.TextField(max_length=3000)
    
    
    
    views.py
    @csrf_exempt 
    def home_view(request,*args,**kwargs):
        if request.method == "POST":
          contacts = ContactForm(request.POST)
          if contacts.is_valid():  
              name = request.POST['name']
              email = request.POST['email']
              subject = request.POST['subject']
              message = request.POST['message']
              post = Contact(name=name,email=email,subject=subject,message=message)
              post.save()
              
              context= {'message_name':name}
              return render(request, 'index.html',context)
            
            else:
               print('not submittd')
    
            
        fm = ContactForm()
        context= {'form':fm}
        return render(request, 'index.html',context)
    

    这是我的联系人的html代码:

               <section class="contact section" id="contact">
                    <h2 class="section-title">Contact</h2>
     {% if message_name %}
                    <div class="centerTest">
                         <h1> Thanks {{ message_name }} for your message. We will get back to you very soon</h1>  
                    </div>
    {% else %} 
                    <div class="contact__container bd-grid">
                        <form action="#contact" method = "POST" class="contact__form">
                            <input type="text" placeholder="Name" name="name" class="contact__input">
                            <input type="mail" placeholder="Email" name="email" class="contact__input">
                            <input type="text" placeholder="subject" name="subject" class="contact__input">
                            <textarea name="message" placeholder="message"  id="" cols="0" rows="10"   class="contact__input"></textarea>
                             <div class="g-recaptcha" data-sitekey="6LciYlMaAAAAAE28SyHrqdm9g6a43UGIf6_ImvF8"></div>
                             <br/>
                            <input type="submit" value="Send" class="contact__button button">
    {% endif %}
                        </form>
                    </div>
                </section>
    

    我也在forms.py中尝试过,但没有看到任何错误消息:

    #Validation #DataFlair
    def clean_name(self):
      name = self.cleaned_data['name']
      if len(name) > 300:
          raise forms.ValidationError("maximum character exceed")
      return name
       
    
    0 回复  |  直到 4 年前
        1
  •  1
  •   quickhaze    4 年前

    在表单无效的其他情况下:-

    else:
      name = request.POST.get('name', None)
      if name:
         if len(name) > 300:
             name_error = "maximum 300 characters allowed"
      else:
         name_error = "Name required"
      context = {"fm":ContactForm(), "name_error": name_error}
      return render(request, 'index.html', context)
    

    在html中

       <input type="text" placeholder="Name" name="name" class="contact__input">
       {% if name_error %}
       <small> {{name_error}} </small>
       {% endif %}
    

    或者,您可以使用ModelForm或html验证(文本输入需要maxlength属性)