Django unique, null and blank CharField giving 'already exists' error on Admin page

前端 未结 7 2100
旧巷少年郎
旧巷少年郎 2021-01-01 13:30

I\'ve been getting the most weird error ever. I have a Person model

class Person(models.Model):
    user = models.OneToOneField(User, primary_key=True)
    f         


        
7条回答
  •  猫巷女王i
    2021-01-01 14:02

    This is an old one but I had a similar issue just now and though I would provide an alternative solution.

    I am in a situation where I need to be able to have a CharField with null=True, blank=True and unique=True. If I submit an empty string in the admin panel it will not submit because the blank string is not unique.

    To fix this, I override the 'clean' function in the ModelForm, and in there I check if it's a blank string and return the result accordinly.

    class MyModelChangeForm(forms.ModelForm):
    
        class Meta:
            model = models.MyModel
            fields = ['email', 'name', 'something_unique_or_null',]
    
        def clean_something_unique_or_null(self):
            if self.cleaned_data['something_unique_or_null'] == "":
                return None
            else:
                return self.cleaned_data['something_unique_or_null']
    

    This fixed the problem for me without having to sacrifice the unique attribute on the model field.

    Hope this helps.

    EDIT: You need to change where I have put "something_unique_or_null" to the name of your field. For example "clean_twitter_id".

提交回复
热议问题