Russell Hertel
Russell Hertel

Reputation: 129

Check if a field is left empty - Django

Is there a way in Django to detect if a field is empty, and by this I mean detect if a field is left empty for every entry of a model submitted?

EDIT:

model.py

    def save(self, *args, **kwargs):
        if self.date1 is None:
            self.date1 = None
        if self.date2 is None:
            self.date2 = None

        super().save(*args, **kwargs)  # Call the "real" save() method.

views.py

if self.date1 is None:
    print('DID IT')

HTML

{% if date1 == None %}
    <h1>1 </h1>
{% endif %}

Upvotes: 0

Views: 2222

Answers (1)

Niel Godfrey P. Ponciano
Niel Godfrey P. Ponciano

Reputation: 10699

You can intercept/override the save() functionality to check if your target fields are empty before they are saved:

class MyModel(models.Model):
    ...
    def save(self, *args, **kwargs):
        if self.some_field1 is None:
            # Do something
        if self.some_field2 is None:
            # Do something
        ...
        super().save(*args, **kwargs)  # Call the "real" save() method.
...

Note though that if you are using bulk_create, the save() wouldn't be called so you might want to handle such case differently.

Upvotes: 1

Related Questions