views:

28

answers:

2

Hello, i have a ModelForm, in which i'm having a CharField, which is declared as unique in the Model. But I have 2 problems:

1.If i fill in the form with a field having the same name i don't get an error message 2.I'd like this field not to contain white spaces

Is it possible to do that using a ModelForm? Thanks a lot!

+2  A: 

To get rid of spaces, make a clean_fieldname function to strip the spaces.

http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation

As for uniqueness, also note about the meta-field unique_together. I don't know if you need it, but I didn't know about it until I dug around.

If you really need to do uniqueness checking before trying to add and failing, you can also do that in the clean_* function. However, it might be better to assume that the database will take care of it and fail in a standard way, and just set up your error messages properly. That way, if you change constraints later, it will flow through more easily. And if others have to maintain your code, it will be more standard.

Hope this helps.

eruciform
Thanks a lot, i'll try it!
dana
+2  A: 

You can do something close to this:

class MyModelForm(forms.ModelForm):
    # your field definitions go here

    def clean_myuniquefield(self):
        # strip all spaces
        data = str(self.cleaned_data['myuniquefield']).replace(' ', '')
        model = self._meta.model
        # check if entry already exists
        try:
            obj = model.objects.get(myuniquefield=data)
        except model.DoesNotExist:
            return data
        raise forms.ValidationError("Value already exists!")
lazerscience