Opened 11 years ago

Closed 11 years ago

#20180 closed Bug (invalid)

unique_together with DateField (auto_now_add = True) causes error in admin.

Reported by: vini.gracindo@… Owned by: Vinnicyus Gracindo
Component: contrib.admin Version: 1.5
Severity: Normal Keywords: admin, unique_together, auto_now_add
Cc: bmispelon@… Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: yes

Description

class Rating(models.Model):
    ip = models.IPAddressField()
    date = models.DateField(auto_now_add=True)
    rating = models.FloatField()

    class Meta:
        unique_together = (('ip', 'date'))

At saving time:
IntegrityError at /admin/rating/rating/add/
columns ip, date are not unique

Expected output:
Rating with this Ip and Date already exists. (In Interface)

Change History (1)

comment:1 by Baptiste Mispelon, 11 years ago

Cc: bmispelon@… added
Resolution: invalid
Status: newclosed

Hi,

I don't think this is a bug, but rather an unfortunate side-effect of using auto_add_now.

What happens is that when you use this option, then the corresponding field is not present in the form that the admin auto-generates.

Therefore, all the validation related to that field (including the uniqueness checks) is not triggered at all which in turn raises the IntegrityError that you see (instead of a nicer form error message).

A workaround for this problem is to get rid of auto_now_add and use default=django.utils.timezone.now, which will include the field in the admin form (and populate it with a default value).

Note: See TracTickets for help on using tickets.
Back to Top