[Answer]-Django – checking for model field format

1👍

Both your valid and modify functions should probably be replaced with a clean method.

Have a look at the docs on model validation

UPDATE 1

You could probably drop the valid method altogether and simply call self.clean_feilds() instead. That will validate the fields –

def modify(self, **kwargs):
    try:
        self.clean_fields()
        for k,v in kwargs.iteritems():
            setattr(self, k, v)
        self.save()
    except:
        pass

UPDATE 2

It sounds from your comments that you don’t need to call any validation yourself at all. Just call save and then catch the ValidationError thrown if your changes are invalid.

def modify(self, **kwargs):
    try:
        for k,v in kwargs.iteritems():
            setattr(self, k, v)
        self.save()
    except ValidationError:
        #... do something?

It’s worth noting that many python programmers prefer the try / except pattern to if valid / then. It’s known as the ‘better to ask forgiveness than permission’ principle (amongst other things it provides protection against race conditions – probably not relevant in this case)

0👍

Use s or self as needed.

def valid(self, kwargs):
    for k, v in kwargs:
        old_v = self.__dict__[k]
        self.__dict__[k] = v
        try:
            self.save()
            self.__dict__[k] = old_v
            self.save()
        except:
            return False

        return True

There is likely a more direct way to perform your test than an actual ‘self.save()’ failure, but its a good place to begin.

Alternatively:

field_list = ['s_name', 's_gpa', 's_year', 's_registered']
def valid(self, kwargs):
    for k, v in kwargs:
        exclude_list = [f for f in field_list if f != k]
        try:
            self.clean_fields(exclude=exclude_list)
        except ValidationError:
            return False

        return True

With list comprehension, eliminate the exclude_list line and change the self.clean_fields line to:

self.clean_fields(exclude=[f for f in field_list if f != k])
👤Cole

Leave a comment