views:

32

answers:

2

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 templates

     <form>

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

If the user clicks on the save button and the above data is saved in the table how to avoid the duplicates,i.e, if the user again clicks on the same submit button there should not be another entry for the same values.Or is it some this that has to be handeled in views

Thanks..

+1  A: 

If an individual field needs to be unique, then you just 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 a 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"]
Mike DeSimone
thanks.......................
Hulk
Also when getdata is called in views for the second example by default this will return "title", "state" and "name" is it?
Hulk
When you reference a Getdata object in a view, you get a Getdata object, with all its fields.
Mike DeSimone
K thanks........
Hulk
A: 

The unique_together also suggested is the best way, but if that's not appropriate for your needs, you can handle it in your form's clean method. 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's data
      raise.forms.ValidationError("Exists already!")
   except Getdata.DoesNotExist:
      #because we didn't get a match
      pass

   return self.cleaned_data
stevejalim
Thanks,,good explanation..
Hulk
I've also seen, for the multiple-submit case, people put in JavaScript that disables the Submit button when it is clicked and the form is submitted. The best solution is probably a combination of all of these.
Mike DeSimone
In my code i have done the same thing for the time being..but this was inconsistent from others..so i had to know about this..Next time i can use a proper code instead of hacks..
Hulk