Reputation: 327
I'm new to Django, and i have a form that has two fields : Client name & bill number . i've created a validator that tests if the bill number already exists in the database table (called bills). But now i need to transform this validator to another that tests in addition of the previous test, if the Client name exists in the same table line (more smiply : if client name and the bille number have the same pk). The validator :
def validate_url(value):
try:
entry=facture_ventes.objects.get(numfac=value)
except ObjectDoesNotExist:
entry = None
if entry is not None:
factexist=facture_ventes.objects.all().filter(id=entry.id).count()
if factexist is not None:
raise ValidationError("Numéro de Facture déja saisi ! ")
the form :
class SubmitUrlForm(forms.Form):
numfacture=forms.CharField(label='Submit Form', validators=[validate_url])
here is the data base table :
https://i.sstatic.net/3xmpd.png
any help please, cause i know that validators cant return a value so i'm stuck here. Thank You
Upvotes: 1
Views: 1612
Reputation: 599630
This isn't a job for a validator, but for the form's clean
method.
def clean(self):
numfac = self.cleaned_data.get('numfacture')
try:
entry=facture_ventes.objects.get(numfac=numfac)
except ObjectDoesNotExist:
entry = None
if entry is not None:
factexist=facture_ventes.objects.all().filter(id=entry.id).count()
if factexist is not None:
raise forms.ValidationError("Numéro de Facture déja saisi ! ")
if entry.client_name == self.cleaned_data.get('client_name'): # or whatever
raise forms.ValidationError("Facture avec ce numéro et cliente existe déjà")
Upvotes: 1
Reputation: 186
You can try using get_or_create() method:
obj, created = MyModel.objects.get_or_create(first_name='Angus', last_name='Young') This could return:
obj
: The object from your DB
created
: False
obj
: The new created object
created
: True
Upvotes: 1