D
D
dintear_koden2020-03-06 16:04:33
Django
dintear_koden, 2020-03-06 16:04:33

How to validate a ModelForm?

I don’t know how to do validation, I didn’t find it in the documentation. Help!
How to validate for email and phone number?

forms.py file

from django.forms import ModelForm
from .models import Question
from django import forms

class QuestionForm(ModelForm):
    class Meta:
        model = Question
        fields = ['name', 'phone', 'mail', 'question']
        widgets = {
            'name': forms.TextInput(attrs={'placeholder': 'Ваше имя:'}),
            'phone': forms.TextInput(attrs={'placeholder': 'Ваш телефон:'}),
            'mail': forms.TextInput(attrs={'placeholder': 'Ваш email'}),
            'question': forms.Textarea(attrs={'placeholder': 'Введити свой вопрос'}),
        }


models.py file
from django.db import models
from django.utils.html import escape
from django.utils.safestring import mark_safe

class Question(models.Model):
  name = models.CharField(max_length=100)
  phone = models.CharField(max_length=20)
  mail = models.EmailField(max_length=200)
  question = models.TextField()

  def __str__(self):
    return self.name


index.html file (form)
<div class="section mail-block">
    <div class="container">
      <div class="row">
        <div class="col-12">
          <h2 class="section-title">Отправьте свой вопрос</h2>
          <div class="line-title"></div>
        </div>
        <div class="col-12">
          <form action="" method="POST">
            {% csrf_token %}

            <div class="row">
              <div class="col-lg-6">
                <p class="input-field">
                  {{ form.name.error }}
                  {{ form.name }}
                </p>
                <p class="input-field">
                  {{ form.phone.error }}
                  {{ form.phone }}
                </p>
                <p class="input-field">
                  {{ form.mail.error }}
                  {{ form.mail }}
                </p>
              </div>
              <div class="col-lg-6">
                <p class="input-field">
                  {{ form.question.error }}
                  {{ form.question }}
                </p>
                <p class="input-field">
                  <button type="submit" class="send-qtn">Отправить <i class="far fa-paper-plane"></i></button>
                </p>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-03-06
@bacon

https://docs.djangoproject.com/en/3.0/ref/forms/va...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question