我有以下 2 个模型 - User 和 PhoneProfile。
我可以成功为用户创建记录。当我使用管理控制台浏览 PhoneProfile 时,我可以看到存在外键。在选择一个条目并完成其余字段时,我收到以下错误。
class User(AbstractBaseUser):
phone_regex = RegexValidator(regex = r'^\+?1?\d{2,14}$', message = "Phone number must be in the format: '+xxxxxxxxxx'.")
phone = models.CharField(validators = [phone_regex], max_length = 15, unique = True)
first_name = models.CharField(max_length = 50, blank = False, null = False)
last_name = models.CharField(max_length = 50, blank = False, null = False)
email = models.CharField(max_length = 100, blank = True, null = True)
first_login = models.BooleanField(default = False)
active = models.BooleanField(default = True)
staff = models.BooleanField(default = True)
admin = models.BooleanField(default = False)
timestamp = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'phone'
REQUIRED_FIELDS = []
objects = UserManager()
Run Code Online (Sandbox Code Playgroud)
class PhoneProfile(models.Model):
registered_phone = models.ForeignKey(User, on_delete=models.CASCADE, related_name='registered_phone')
notify_enable_low_bal = models.BooleanField()
notify_amount_low_bal = models.DecimalField(decimal_places=2, max_digits=10000, default='50', null=True)
Run Code Online (Sandbox Code Playgroud)
当我尝试在 PhoneProfile 模型中创建条目时出现错误消息
__str__ returned non-string (type User)
Request Method: POST
Request URL: http://localhost:8000/admin/smartrecharge/phoneprofile/add/
Django Version: 3.0.7
Exception Type: TypeError
Exception Value:
__str__ returned non-string (type User)
Exception Location: /Users/django-backend/venv/lib/python3.7/site-packages/django/contrib/admin/options.py in log_addition, line 807
Python Executable: /Users/django-backend/venv/bin/python
Python Version: 3.7.7
Python Path:
Run Code Online (Sandbox Code Playgroud)
任何指导将不胜感激。谢谢
小智 5
您在类字符串表示形式中获得的值不是字符串,因此您必须更改 def str (self) 方法并将返回数据转换为字符串,如果没有数据,则按如下所示制作一个
class User(AbstractBaseUser):
phone_regex = RegexValidator(regex = r'^\+?1?\d{2,14}$', message = "Phone number must be in the format: '+xxxxxxxxxx'.")
phone = models.CharField(validators = [phone_regex], max_length = 15, unique = True)
first_name = models.CharField(max_length = 50, blank = False, null = False)
last_name = models.CharField(max_length = 50, blank = False, null = False)
email = models.CharField(max_length = 100, blank = True, null = True)
first_login = models.BooleanField(default = False)
active = models.BooleanField(default = True)
staff = models.BooleanField(default = True)
admin = models.BooleanField(default = False)
timestamp = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'phone'
REQUIRED_FIELDS = []
objects = UserManager()
def __str__(self):
return str(self.phone_regex)
Run Code Online (Sandbox Code Playgroud)
在问题中指定的其他课程中进行相同的更改
| 归档时间: |
|
| 查看次数: |
2536 次 |
| 最近记录: |