Python Django how i can prevent the duplicate entry of studnumber,email,username(unmae) in registration? my python file are views,URLs,models,settings.py
from django.shortcuts import redirect, render
from register.models import newacc
from django.contrib import messages
def Unreg(request):
if request.method=='POST':
studnumber=request.POST['studnumber']
fname=request.POST['fname']
age=request.POST['age']
gender=request.POST['gender']
uname=request.POST['uname']
email=request.POST['email']
pwd=request.POST['pwd']
contact=request.POST['contact']
newacc(studnumber=studnumber,fname=fname,age=age,gender=gender,uname=uname,email=email,pwd=pwd,contact=contact).save()
messages.success(request,"The New User is save !")
return render(request,'Registration.html')
else:
return render(request,'Registration.html')
First you have to define in your model the following:
class newacc(models.Model):
# Your fields here...
class Meta:
unique_together = ('studnumber','email','uname')
Doing this, if you call the method newacc.save() and that restriction is not ok it will throw an exception.
In views the best way and standard way is to use Forms
, with forms django provide an especific class called ModelForm
that help you to deal with Models.
For example to create a form to our model we can do this:
class NewACCForm(forms.ModelForm):
class Meta:
model = newacc
fields = "__all__"
It will create a form that will allow you to validate if the constraints that you defined in the model are ok and you can do things based in the validation of that form.
Now your view will be like the following code:
def Unreg(request):
if request.method=='POST':
form = NewACCForm(request.POST)
if form.is_valid():
form.save()
messages.success(request,"The New User is save !")
else:
messages.error(request, "Was not possible to save the user")
return render(request,'Registration.html')
You can of course improve it but I'm giving you the basic idea of what is the missing part that you must learn in Django in order to create apps in an easy and fast way.