0

I have a model that takes in a listname. I only want the list name to disable duplicates per user. Currently, a user cannot enter "recipes" twice, but if another user doesn't have a "recipe" list name, they can't enter it either because the field is unique. Is it possible to make the listname only unique to the currently logged in user?

MODEL

class newlist(models.Model):

    user = models.ForeignKey(User)
    list_name = models.CharField(max_length = 100, unique = True)
    picture = models.ImageField(upload_to='profiles/', default = "/media/profiles/default.jpg")
    slug = AutoSlugField(populate_from='list_name', default = '')

    def __str__(self):
        return self.list_name
Community
  • 1
  • 1
ryan
  • 625
  • 3
  • 10
  • 23

1 Answers1

1

Use the models Meta class unique_together. You can find the excellent documentation here.

class newlist(models.Model):
    class Meta:
        unique_together=('user','list_name')
    user = models.ForeignKey(User)
    list_name = models.CharField(max_length = 100)
    picture = models.ImageField(upload_to='profiles/', default = "/media/profiles/default.jpg")
    slug = AutoSlugField(populate_from='list_name', default = '')

    def __str__(self):
        return self.list_name
    def save(self,*args,**kwargs):
        try:
            return super(newlist,self).save(*args,**kwargs)
        except IntegrityError: # This is raised if the object can't be saved.
            # Your error handling code
            from django.core.exceptions import PermissionDenied
            raise PermissionDenied()
Sebastian Wozny
  • 16,943
  • 7
  • 52
  • 69
  • fantastic! Is there a way to render a form error for duplicates instead of a django error page? – ryan May 25 '15 at 07:31