Opened 3 weeks ago

Closed 2 weeks ago

Last modified 2 weeks ago

#36171 closed Bug (invalid)

When saving an object(null=True, blank=True) with an empty string __str__ in the admin page.

Reported by: Antoliny Owned by: Antoliny
Component: contrib.admin Version: 5.1
Severity: Normal Keywords: blank, str
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no
Pull Requests:How to create a pull request

Description (last modified by Antoliny)

When a field that allows blank and null is used as __str__, an issue occurs when saving the object in the admin page if the value is empty.

TestCase

class Comment(models.Model):
    author = models.CharField(max_length=128, null=True, blank=True)
    content = models.CharField(max_length=128)

    def __str__(self):
        return self.author


When clicking the save-related button, the following error is returned.

Everytime an object is saved in the admin page, a LogEntry is also created. It seems that an issue occurs when LogEntry tries to use the object's __str__.

My guess is that the to_python method in the CharField(Form) performs a strip() process, causing the value entered in the admin page to be " " instead of "". As a result, it is treated as None, and an issue occurs when LogEntry tries to use __str__ on that value.

Change History (8)

by Antoliny, 3 weeks ago

Attachment: save_error.png added

by Antoliny, 3 weeks ago

Attachment: error.png added

comment:1 by Antoliny, 3 weeks ago

Owner: set to Antoliny
Status: newassigned

comment:2 by Antoliny, 3 weeks ago

Description: modified (diff)

by Antoliny, 3 weeks ago

Attachment: save_error_resize.png added

comment:3 by Antoliny, 3 weeks ago

Description: modified (diff)

comment:4 by Sarah Boyce, 2 weeks ago

Resolution: invalid
Status: assignedclosed

To me, the issue here is in the string method should always return a string (eg. return self.author or "")
If you want to keep spaces, you will need a custom form with strip=False (see https://docs.djangoproject.com/en/5.1/ref/forms/fields/#charfield)

comment:5 by Antoliny, 2 weeks ago

Replying to Sarah Boyce:

To me, the issue here is in the string method should always return a string (eg. return self.author or "")
If you want to keep spaces, you will need a custom form with strip=False (see https://docs.djangoproject.com/en/5.1/ref/forms/fields/#charfield)

sarahboyce, I have a small question. 🙋
It seems this issue occurs because even though we set blank=True in the Field(Model), but the admin Form doesn't allow empty value.
Is this how it was originally designed? Does this mean users need to manually configure Form to allow empty fields for Field(Model) where blank=True is set?

Last edited 2 weeks ago by Antoliny (previous) (diff)
Note: See TracTickets for help on using tickets.
Back to Top