0

I am using crispy forms for my Django project, and in one of the forms I am using, there is a field that needs to be unique when entered, but it should be possible to leave it blank as well.

For my student database project, each student has a student_id that is set as a primary key, and each student should also have an anonymous_id that will be added at a later point in the year. This exam ID should be unique to stop the admin from entering it for the wrong student. Very simplified, the model looks like this:

class Student(models.Model):
    student_id = models.CharField(primary_key=True)
    anonymous_id = models.CharField(null=True, blank=True, unique=True, default=None)
    ...

and the form just lists both fields in a tab. Without Crispy Forms, it was no problem to enter students with a blank field for "anonymous_id", but now it complains with the second student ("Student with this Anonymous ID already exists.") - presumaby because there is already one who has "None" as his ID.

Is there anything I can do to turn off the validation for None only or will I have to remove the unique constraint?

Thanks, Tobi

Tobi
  • 351
  • 1
  • 2
  • 20
  • Did you check this solution? http://stackoverflow.com/questions/454436/unique-fields-that-allow-nulls-in-django/1400046#1400046 – Sudip Kafle Aug 17 '14 at 10:45

1 Answers1

1

You can have multiple students with anonymous_id=None, the problem is that your form is saving anonymous_id=''. If you use a ForeignKey instead of a CharField, then Django will save None instead of empty string for you, and validate that the ids link to an object that exists.

I would be surprised if your form behaved differently with and without crispy forms. The problem is that you now have an empty string in the database, so you can't add another.

I would suggest using a ForeignKey instead of a CharField, or checking the ids and changing empty strings to None before saving your form to the db. You will also have to go through your existing students and convert any empty strings to None.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • Thanks! Will do the second idea. And I now realised that changing the forms to crispy wasn't the only thing I did - I also did not have the anonymous ID field in the previous version. So I guess you are right that crispy-forms is not to blame here. – Tobi Aug 17 '14 at 11:34