views:

52

answers:

1

Hello everyone, I have a small problem. I am trying to check to see if status's value already exists and make sure I do not create another instance of it, but I am having some trouble. Ex. If the project status was once "Quote" I do not want to be able make the status "Quote" again. Right now, I check to make sure if the user selects edit, then clicks submit, the status doesnt duplicate. However, if the User selected another status, like "completed" nothing stops them from going back in and selecting "quote" again.

models.py

class Status(models.Model):
   project = models.ForeignKey(Project, related_name='status')
   value = models.CharField(max_length=20, choices=STATUS_CHOICES, verbose_name='Status')
   date_created= models.DateTimeField(auto_now=True) 

class Project(models.Model):
   ...

views.py

 if form.is_valid():    
        project = form.save(commit=False)
        project.created_by = request.user  
        project.save()
        old_status = project.current_status()
        if not old_status or old_status.value != form.cleaned_data.get('status', None):
             #add status instance
            project.status.create(
                  value = form.cleaned_data.get('status', None)
            )       

        return HttpResponseRedirect('/project/')

Any help, or pointing me in the right direction would be much appreciated.

Thanks everyone!

+2  A: 
value = models.CharField(max_length=20, choices=STATUS_CHOICES, verbose_name='Status', unique=True)
awesome! that was the small thing I was missing. One other question, how do I handle this error though? Now Im just getting the django error page? Thanks again... Im still learning
Steve
Use a try/except when you try to `save`.
Thank you very much!
Steve