我有一个使用注册表单创建用户的模型。表单工作正常,用户创建并使用正确的值。但是,当我使用Django Admin界面更改值并保存或保存并创建另一个时,我收到如下错误消息(注意:我刚刚为模型添加了2个新值 - 预先批准并激活。我已经进行了迁移) :
ValueError at /admin/app_users/profileteacher/4/change/
invalid literal for int() with base 10: ''
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/app_users/profileteacher/4/change/
Django Version: 1.10.5
Exception Type: ValueError
Exception Value:
invalid literal for int() with base 10: ''
Exception Location: /home/fungai/pythonicness/mildev/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py in get_prep_value, line 1832
Python Executable: /home/fungai/pythonicness/mildev/bin/python
Python Version: 2.7.12
Python Path:
['/home/fungai/pythonicness/milingual_api',
'/home/fungai/pythonicness/mildev/lib/python2.7',
'/home/fungai/pythonicness/mildev/lib/python2.7/plat-x86_64-linux-gnu',
'/home/fungai/pythonicness/mildev/lib/python2.7/lib-tk',
'/home/fungai/pythonicness/mildev/lib/python2.7/lib-old',
'/home/fungai/pythonicness/mildev/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/home/fungai/pythonicness/mildev/local/lib/python2.7/site-packages',
'/home/fungai/pythonicness/mildev/lib/python2.7/site-packages',
'/home/fungai/pythonicness/milingual_api']
Server time: Fri, 6 Apr 2018 14:55:54 +0000
错误可以追溯到这一行:
super(ProfileTeacher, self).save(*args, **kwargs)
并且模型是(在那里有一个保存功能):
class ProfileTeacher(models.Model):
created = models.DateTimeField(auto_now=False, auto_now_add=True, blank = False, null = False, verbose_name = 'Creation Date')
user = models.OneToOneField(app_settings.USER_MODEL,blank=True, null=False)
first_name = models.CharField(max_length = 400, null=True, blank = True, verbose_name = 'First Name')
last_name = models.CharField(max_length = 400, null=True, blank = True, verbose_name = 'Surname')
phone_number = models.CharField(max_length = 15, null=True, blank = True, verbose_name = 'Phone Number')
city = models.ForeignKey(City, null=True, blank = True, verbose_name = 'City')
postal_code = models.CharField(max_length = 400, null=True, blank = True, verbose_name = 'Postal Code')
adress = models.CharField(max_length = 400, null=True, blank = True, verbose_name = 'Address')
nationality = CountryField(blank_label='(select country)', null=True, blank = True)
id_number = models.CharField(max_length = 400, null=True, blank = True, verbose_name = 'ID Number(NIF/NIE)')
bank_account = IBANField(verbose_name='IBAN', blank = True, null=True)
date_of_birth = models.DateField(auto_now=False, auto_now_add=False, blank = True, null = True, verbose_name='Date of birth')
#To enable them showing up in search. Only active teachers are shown and preapproved needs to be true to be active
preapproved = models.BooleanField(default=False, verbose_name='Pre-Approved')
active = models.BooleanField(default=False, verbose_name='Active')
#Braintree and Milingual Terms of Service Acceptance
tos = models.BooleanField(default=False, blank=True)
#If true will receive classes email notifications
email_notification = models.BooleanField(default=False, blank=True, verbose_name="Recibir Notificaciones")
GENDER = (
('male','Male'),
('female','Female'),
)
gender = models.CharField(max_length=20, choices=GENDER, blank = True, null=True, verbose_name = 'Gender' )
language = models.ForeignKey(Language, null = True, blank=True)
teacher_type = models.ForeignKey(TeacherType, null = True, blank=True, verbose_name='Type')
cvv = models.FileField(upload_to=teacher_directory_path, null=True, blank = True, verbose_name="CV")
profile_image = models.ImageField(upload_to=teacher_directory_path,
null = True,
blank=True,
default='/perfil.png',
)
RATINGS = (
(1, '1'),
(2, '2'),
(3, '3'),
(4, '4'),
(5, '5'),
)
rating = models.IntegerField(default=0, choices=RATINGS, blank=True, verbose_name="RATINGS", null=False)
#True if the profile will appear on milingual site as Public
published = models.BooleanField(null=False, blank=False, default=True)
#Url: Teacher's Url
url = models.SlugField(max_length=400, null=True, blank = True, verbose_name='Url')
# True if teacher is legacy
legacy = models.BooleanField(default=False, blank=True)
legacy_id = models.IntegerField(default=0, null=True, blank=True)
class Meta:
verbose_name_plural = 'Teachers'
verbose_name = 'Teacher'
@property
def absolute_rating(self):
return int(float(self.rating)/5 * 100)
def save(self, *args, **kwargs):
# Check how the current values differ from ._loaded_values. For example,
# prevent changing the creator_id of the model. (This example doesn't
# support cases where 'creator_id' is deferred).
#Building_unique_url
url = str(self.first_name).lower() + '_' + str(self.last_name).lower() + '_' + str(int(self.user.id))
self.url = url
super(ProfileTeacher, self).save(*args, **kwargs)
def __unicode__(self):
return "%s %s" % (self.first_name, self.last_name)
我在这里做错了什么?
答案 0 :(得分:1)
问题是您已在null=False
rating
上设置了IntegerField
。这意味着当您通过管理表单传递空值时,Django会尝试将空字符串保存到IntegerField
,然后失败,因为它无法将其转换为整数。
在字段上设置default=0
对您没有帮助 - 这仅适用于创建新模型实例且未为该字段提供值的情况(即使该值为空字符串)。
您有两个选择:在字段上允许null
值,或者在save()
方法中添加一些逻辑来检查空值并在保存之前对其进行操作,例如:
def save(self, *args, **kwargs):
if self.rating == '':
self.rating = 0
super(ProfileTeacher, self).save(*args, **kwargs)