NameError 'unicode'未定义,当我在django模型中使用保存函数时会发生此错误

6l7fqoea  于 2023-05-30  发布在  Go
关注(0)|答案(3)|浏览(117)

输出中的错误日志:

NameError at /admin/todo/todomodel/add/
name 'unicode' is not defined
Request Method: POST
Request URL:    http://127.0.0.1:8000/admin/todo/todomodel/add/
Django Version: 2.2
Exception Type: NameError
Exception Value:    
name 'unicode' is not defined

关于系统和异常的更多细节:
异常位置:C:\Users\PEE TEE\Desktop\ToDoApp\lib\site-packages\slugify.py in slugify, line 24
Python可执行文件:C:\Users\PEE TEE\Desktop\ToDoApp\Scripts\python.exe
Python版本:3.7.6
Python路径:
['C:\\Users\\PEE TEE\\Desktop\\ToDoApp\\src', 'C:\\Users\\PEE TEE\\Desktop\\ToDoApp\\Scripts\\python37.zip', 'C:\\Users\\PEE TEE\\Desktop\\ToDoApp\\DLLs', 'C:\\Users\\PEE TEE\\Desktop\\ToDoApp\\lib', 'C:\\Users\\PEE TEE\\Desktop\\ToDoApp\\Scripts', 'c:\\users\\pee tee\\appdata\\local\\programs\\python\\python37\\Lib', 'c:\\users\\pee tee\\appdata\\local\\programs\\python\\python37\\DLLs', 'C:\\Users\\PEE TEE\\Desktop\\ToDoApp', 'C:\\Users\\PEE TEE\\Desktop\\ToDoApp\\lib\\site-packages']
服务器时间:电话:+86-021 - 88888888传真:+86-021 - 88888888
这是我的模型:

from django.db import models
from django.db.models.signals import post_save
from slugify import slugify
# Create your models here.

class ToDoModel(models.Model):
   author = models.ForeignKey('auth.User', on_delete=models.CASCADE) 
   what_todo = models.CharField(max_length=255, default="Event to be done")
   date_todo = models.DateField(auto_now=False,auto_now_add=False) 
   slug = models.SlugField(null=True, blank=True) 

    def save(self, *args, **kwargs):
        if self.what_todo and not self.slug:
            self.slug = slugify(self.what_todo)
        return super(ToDoModel, self).save(*args, **kwargs)

    def __str__(self):
        return str(self.what_todo)
50pmv0ei

50pmv0ei1#

你正在使用一些与Python 2相关的代码,Python 3将unicode类型重命名为str。详见https://docs.python.org/3/howto/unicode.html

mkshixfv

mkshixfv2#

纠正你的slugify代码

def save(self, *args, **kwargs):
    if not self.slug:
        self.slug = slugify(self.what_todo)
    return super(ToDoModel, self).save(*args, **kwargs)
30byixjq

30byixjq3#

您安装了错误的软件包...你安装了slugify,而相关的包名为python-slugify。它与Python 3不兼容。

pip3 uninstall slugify
pip3 install python-slugify

相关问题