22

The admin returns this error when trying to add an instance to one of my models. The model itself has a correct str() method and contains no instances yet. Also tried replacing the str() method with a static method or removing it altogether. No luck.

The error seems to point towards something going wrong in the history part of the admin. Stacktrace points to line 33.

Error during template rendering

In template /Users/snirp/juis/snirpdrive/glotto/venv/lib/python3.6/site-packages/django/contrib/admin/templates/admin/change_form.html, error at line 33
__str__ returned non-string (type NoneType)
23  {% endblock %}
24  {% endif %}
25  
26  {% block content %}<div id="content-main">
27  {% block object-tools %}
28  {% if change %}{% if not is_popup %}
29    <ul class="object-tools">
30      {% block object-tools-items %}
31      <li>
32          {% url opts|admin_urlname:'history' original.pk|admin_urlquote as history_url %}
33          <a href="{% add_preserved_filters history_url %}" class="historylink">{% trans "History" %}</a>
34      </li>
35      {% if has_absolute_url %}<li><a href="{{ absolute_url }}" class="viewsitelink">{% trans "View on site" %}</a></li>{% endif %}
36      {% endblock %}
37    </ul>
38  {% endif %}{% endif %}
39  {% endblock %}
40  <form {% if has_file_field %}enctype="multipart/form-data" {% endif %}action="{{ form_url }}" method="post" id="{{ opts.model_name }}_form" novalidate>{% csrf_token %}{% block form_top %}{% endblock %}
41  <div>
42  {% if is_popup %}<input type="hidden" name="{{ is_popup_var }}" value="1" />{% endif %}
43  {% if to_field %}<input type="hidden" name="{{ to_field_var }}" value="{{ to_field }}" />{% endif %}

These are the relevant parts of my models.py and admin.py

class UserContent(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    created_by = models.ForeignKey(User, related_name='%(class)s_creator')
    updated_by = models.ForeignKey(User, related_name='%(class)s_updater')

    class Meta:
        abstract = True


class Linetrans(UserContent):
    line = models.ForeignKey(Line)
    translation = models.ForeignKey(Translation)
    text = models.CharField(max_length=400)

    def __str__(self):
        return self.text

    class Meta:
        ordering = ['line']

and

admin.site.register(Linetrans)

Other model classes are very similar and do not return an error. The error also occurs when the Linetrans is added as an inline to another admin class.

edit / update: I commented out all other str() methods in my model and sure enough the error seems to go away. Now trying to pinpoint the issue.

12 Answers 12

85

Turns out that there was an unexpected empty CharField in a related model. Leaving this an an answer, because it might help others.

Troubleshoot the issue by systematically commenting out the __str__() methods of your models until you find the offending model. Work from there to identify the offending record(s).

8
  • 15
    I had a str method that returned self.title instead of self.title or ''.
    – Seth
    Aug 16, 2017 at 4:51
  • 2
    I just spent an hour on irc just to get to Seth's solution. +1 You should still try to find the offending object, I think. Apr 18, 2018 at 1:17
  • 1
    That was so helpful. Didn't know where the error was, saw this answer and changed self.name to self.name or ' ' and totally worked. Thanks a lot. Feb 17, 2021 at 15:43
  • 1
    Had a similar problem--modified a model with on_delete=models.SET_DEFAULT, default=None, null=True, and that broke the __str__ for the admin interface. Used @seth method: return self.NAME or '' and solved the mystery.
    – YCode
    Jul 16, 2021 at 14:31
  • I had __str__ return self.data (JSON information) instead of str(self.data)
    – sebtheiler
    Sep 9, 2021 at 17:39
16

I had a similar issue. The problem was that the primary key for one row was null ( I dont know how that happened). I couldnt delete the row because of cascade issues. so I had to change the str mmethod to somthing like this.

def __str__(self):
    if self.customerName==None:
        return "ERROR-CUSTOMER NAME IS NULL"
    return self.customerName
1
  • Thanks. I added a test row with NULL in one of the columns which was being referenced elsewhere. Deleting the test row fixed the problem.
    – bibek
    Dec 3, 2018 at 2:02
10

Check out the class that you have referred to in

        models.ForeignKey 

The problem lies in the

        __str__() 

method of one of those classes. Then, add

                             or ''

in the return statement of that class like this.

        def __str__(self):
            return self.title or ''
1
  • Thanks for pointing this. I completely forgot this. My model list was showing perfectly but whenever I try to update the data it shows the str error. Oct 15, 2022 at 5:56
6
def __str__(self):
        return str(self.topic)

Use str to make it type string. Then it's not not-string type.

3

For this error you can use two solutions

first solution: you can comment it out below code

 def __str__(self):
    return self.id

to

 #def __str__(self):
 #  return self.id

secound solution: you can return the string from the object

 def __str__(self):
    return str(self.id)
0
2

that's works for me:

    def __str__(self):
    return f"{self.category}"

Just use "f" string

1

You can also delete the instances in the model causing this problem from the django shell python manage.py shell . This helps when you are dealing with a model with lots of related models like mine.

Typically this problem is caused by altering model fields and migrating, such that the instances are incompatible with each other and related fields

1

If you are trying to use __str__() to return the value of a ForeignKey or a OneToOneField this would return error

Example:

def __str__():
    return self.user  # where user is a key to other model class

It should be:

def __str__():
    return self.user.__str__() 
    # Or basically any other way that would explicitly unbox the value inside the related model class.
1

In my case I had the same issue and its origin was that: for the field used in the __str__ functions, has null values saved in the data base.

So I can solve the issue doing somethings like this:

update table
set field_for_STR_use = 'any value'
where field_for_STR_use is null or field_for_STR_use = ''

after that, I only refreshed my view and the problem had disappeared.

1

There was one of the foreign reference which was returning non string field. I changed it to string field or you can change to str(foreign-key-return-element) name = models.CharField(max_length=200, unique=True) # name of the article parent = models.ForeignKey('self',on_delete=models.DO_NOTHING,related_name='category_parent_item', default=None, null=True) # Store child items created_at = models.DateTimeField(auto_now=True) # Creation date updated_at = models.DateTimeField(auto_now=True) # Updation Date user = models.ForeignKey(get_user_model(),

on_delete=models.DO_NOTHING,related_name='category_update_user', default=None, null=True) #User who updated the Article

def __str__(self):
    return self.name ----------> this was an integer field initially in foreign reference
0
0

In my case, I had a different model that was called by another one that had the default snippet from VSCode as:

def __str__(self):
    return

This was causing the error, even when it was showing in the log another place.

0

Toto_tico is right, although the above error can also occur when you fail to return a str property of your django model within the str(self) method:

Class model and(models.Model):
    Class Meta:
       verbose_name = "something"

    title = models.CharField(max_length=100)
    email = models.CharField(max_length=100)

    #Error instance:
    def __str__(self):
       self.title

    #Right way
    def __str__(self):
       return self.title

So it is highly advised to return the str property within the

def str(self)

method to avoid errors in the Django admin panel when trying to make changes to a particular data within a model table:

    def __str__(self):
       return self.property

I hope this will help someone.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.