Reputation:
I have a curious error:
TypeError at /admin/wall/articles/
__str__ returned non-string (type Articles)
I have a model Articles. I just try to delete some articles of my database from the admin panel of Django. I said it's curious because it happens only on some objects. I can remove most of articles but for some reason, some entries in database returns an error if I'm deleting them. It doesn't happen for my other models.
This is a screenshot of phpmyadmin showing all entries in my table "Articles":
For example, I have an entry with id 70. In the Django admin pannel I can't delete it, I have an error. For testing a recreate the exact entry (see on id 75) and I can delete this entry from django admin pannel.
Why could I delete some contents but not all ?
This is my models.py :
from django.db import models
from start.models import Games
from django.contrib.auth.models import User
from tinymce.models import HTMLField
# Create your models here.
def user_directory_path_articles(instance, filename):
return 'media/user/user_{0}/articles/{1}/'.format(instance.user.id, filename)
def user_directory_path_comments(instance, filename):
return 'media/user/user_{0}/comments/{1}/'.format(instance.user.id, filename)
def validate_file_extension(value):
import os
from django.core.exceptions import ValidationError
ext = os.path.splitext(value.name)[1] # [0] returns path+filename
valid_extensions = ['.jpg', '.png']
if not ext.lower() in valid_extensions:
raise ValidationError(u'Merci d\'utiliser le format JPG ou PNG')
class Articles(models.Model):
title = models.CharField(max_length=50, null=False, verbose_name="Titre")
text = HTMLField()
image = models.FileField(upload_to='media/articles/', validators=[validate_file_extension], blank=True, null=True, verbose_name="Image de présentation")
games = models.ForeignKey(Games, verbose_name="Jeux", blank=True, null=True)
author = models.ForeignKey(User, verbose_name="Auteur")
is_statut = models.BooleanField(default=True, verbose_name="Statut")
date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création")
update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification")
def __str__(self):
return self.title
class Comments(models.Model):
text = models.CharField(max_length=300, null=False)
image = models.FileField(upload_to=user_directory_path_comments, validators=[validate_file_extension], blank=True, null=True)
articles = models.ForeignKey(Articles, verbose_name="Article", null=False, related_name='comments')
author = models.ForeignKey(User, verbose_name="Auteur")
in_answer_to = models.ForeignKey('self', verbose_name="En réponse au commentaire", blank=True, null=True, on_delete=models.CASCADE)
date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création")
update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification")
def __str__(self):
return self.text
class Like(models.Model):
articles = models.ForeignKey(Articles, verbose_name="Article", null=True, blank=True)
user = models.ForeignKey(User, verbose_name="Auteur", null=False)
def __str__(self):
return self.articles
class Up(models.Model):
comments = models.ForeignKey(Comments, verbose_name="Commentaire", null=True, blank=True)
user = models.ForeignKey(User, verbose_name="Auteur", null=False)
This my admin.py :
from django.contrib import admin
from .models import Articles, Comments
# Register your models here.
class ArticlesAdmin(admin.ModelAdmin):
list_display = ('date', 'title', 'author', 'games', 'is_statut', 'update')
fieldsets = (
('Général', {
'fields': ('title', 'author', 'is_statut')
}),
('Choisir une image de présentation', {
'fields': ('image',)}),
('Contenu de l\'article', {
'fields': ('text',)}),
('En rapport avec le jeu :', {
'fields': ('games',)}),
)
admin.site.register(Articles, ArticlesAdmin)
This is the traceback of my error page, and thanks for your help:
Environment:
Request Method: POST
Request URL: http://*******:8000/admin/wall/articles/
Django Version: 1.11.2
Python Version: 3.5.3
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'widget_tweaks',
'tinymce',
'start',
'myaccount',
'wall']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/options.py" in wrapper
551. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/sites.py" in inner
224. return view(request, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py" in _wrapper
67. return bound_func(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py" in bound_func
63. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/options.py" in changelist_view
1568. response = self.response_action(request, queryset=cl.get_queryset(request))
File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/options.py" in response_action
1286. response = func(self, request, queryset)
File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/actions.py" in delete_selected
37. queryset, opts, request.user, modeladmin.admin_site, using)
File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/utils.py" in get_deleted_objects
172. to_delete = collector.nested(format_callback)
File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/utils.py" in nested
232. roots.extend(self._nested(root, seen, format_callback))
File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/utils.py" in _nested
216. children.extend(self._nested(child, seen, format_callback))
File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/utils.py" in _nested
218. ret = [format_callback(obj)]
File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/utils.py" in format_callback
145. force_text(obj))
File "/usr/local/lib/python3.5/dist-packages/django/utils/encoding.py" in force_text
76. s = six.text_type(s)
Exception Type: TypeError at /admin/wall/articles/
Exception Value: __str__ returned non-string (type Articles)
Upvotes: 2
Views: 4220
Reputation: 599926
The problem is in your Like model. As the error says, the __str__
method on that article is not returning a string, but an instance of Articles. You should be sure to actually return a string, for instance self.articles.title
.
The reason this is a problem on deletion is because deleting an article will also delete all the objects that point to it, and Django helpfully displays all the affected objects on the confirmation page.
Note, your naming conventions are confusing. You should stick to singular names for your models: Article, Comment.
Upvotes: 3