Я создаю регистрационную форму для участия в колледже. Я хочу сохранить всю информацию об участнике в базе данных.
Однако, если участник регистрируется с тем же адресом электронной почты, что и другой зарегистрированный участник, я хочу показать ошибку в моем шаблоне Html и не сохранять какую-либо информацию об участнике.
models.py
class ParticipantInfo(models.Model):
participant_name = models.CharField(max_length=50)
participant_usn = models.CharField(max_length=10)
participant_phone = models.CharField(max_length=50)
participant_email = models.EmailField(max_length=100, unique=True)
participant_branch = models.CharField(max_length=50, choices=BranchName, default='ise')
participant_dob = models.DateField(max_length=20)
forms.py
class ParticipantForm(forms.ModelForm):
class Meta:
model = ParticipantInfo
fields = "email"
def clean_email(self):
email = self.cleaned_data.get('email')
if User.objects.filter(email=email).exists():
raise forms.ValidationError(u'Email addresses must be unique.')
return email
views.py
def registered(request):
if request.method == 'POST':
name_r = request.POST.get('name')
email_r = request.POST.get('email')
usn_r = request.POST.get('usn')
phone_r = request.POST.get('phone')
branch_r = request.POST.get('branchName')
dob_r = request.POST.get('dob')
to_save = ParticipantInfo(participant_name=name_r,
participant_email=email_r, participant_usn=usn_r,
participant_phone=phone_r,
participant_branch=branch_r, participant_dob=dob_r)
to_save.save()
html форма
<form action="registration_successful/" method="POST" role="form" class="Registration">
{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-6">
<input type="text" required name="name" class="form-control" id="name" placeholder="Your Full Name as in College ID Card" data-rule="minlen:4" data-msg="Please enter at least 4 characters." />
<div class="validation"></div>
</div>
<div class="form-group col-md-6">
<input type="email" required class="form-control" name="email" id="email" placeholder="Your Email Address" data-rule="email" data-msg="Please enter a valid email." />
<div>{{ form.errors }}</div>
<div class="validation"></div>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<input type="phone" class="form-control" required name="phone" id="phone" placeholder="Your Phone Number" data-rule="minlen:10" data-msg="Please enter Your 10 digit Mobile Number." />
<div class="validation"></div>
</div>
<div class="form-group col-md-6">
<input type="usn" class="form-control" required name="usn" id="usn" placeholder="Your USN" data-rule="minlen:10" data-msg="Please enter your USN" />
<div class="validation"></div>
</div>
</div>