Django models avoid duplicates

In models:

class Getdata(models.Model): title = models.CharField(max_length=255) state = models.CharField(max_length=2, choices=STATE, default="0") name = models.ForeignKey(School) created_by = models.ForeignKey(profile) def __unicode__(self): return self.id() 

In the templates:

 <form> <input type="submit" value="save the data" /> </form> 

If the user clicks the save button, and the above data is stored in the table, how to avoid duplicates, i.e. if the user clicks on the same submit button again, there should not be another record for the same values. Or is that what needs to be handled in views?

+6
python django django-models django-templates django-views
source share
3 answers

If a single field should be unique, you simply add unique=True :

 class Getdata(models.Model): title = models.CharField(max_length=255, unique=True) state = models.CharField(max_length=2, choices=STATE, default="0") name = models.ForeignKey(School) created_by = models.ForeignKey(profile) 

If you want the combination of fields to be unique, you need unique_together :

 class Getdata(models.Model): title = models.CharField(max_length=255) state = models.CharField(max_length=2, choices=STATE, default="0") name = models.ForeignKey(School) created_by = models.ForeignKey(profile) class Meta: unique_together = ["title", "state", "name"] 
+17
source share

The only option that is also offered is the best way, but if this is not suitable for your needs, you can process it in its purest form. eg,

 def clean(self): try: Getdata.objects.get(title=self.cleaned_data['title'], state=self.cleaned_data['state'], name=self.cleaned_data['name'], created_by=self.cleaned_data['created_by'] ) #if we get this far, we have an exact match for this form data raise forms.ValidationError("Exists already!") except Getdata.DoesNotExist: #because we didn't get a match pass return self.cleaned_data 
+2
source share

I think injecting Jquery / JS code to hide the save button would be a good idea.

Create the custom_validate.js file as shown below and put it in the static directory (static file directory)

 if (!$) { $ = django.jQuery; } $( document ).ready(function() { $("[name=_save]").click(function() { $("[name=_save]").css("visibility", "hidden"); }); }); 

And in admin.py add the code below.

 class CustomDataForm(forms.ModelForm): class Meta: model = GetData class GetDataAdmin(admin.ModelAdmin): # .... ..... form = CustomDataForm class Media: js = ('/static/custom_validate.js', ) 
+1
source share

All Articles