[英]This field is required error in django
在我設置的模型中:
class Task(models.Model):
EstimateEffort = models.PositiveIntegerField('Estimate hours',max_length=200)
Finished = models.IntegerField('Finished percentage',blank=True)
但是在網頁中,如果我沒有為Finished
字段設置值,則會顯示錯誤This field is required
。 我試過null=True
和blank=True
。 但他們都沒有工作。 所以你能告訴我如何讓一個字段允許為空。
我發現有一個屬性empty_strings_allowed
,我將它設置為 True,但仍然相同,並且我將empty_strings_allowed
子類化。 它仍然無法工作
class IntegerNullField(models.IntegerField):
description = "Stores NULL but returns empty string"
empty_strings_allowed =True
log.getlog().debug("asas")
def to_python(self, value):
log.getlog().debug("asas")
# this may be the value right out of the db, or an instance
if isinstance(value, models.IntegerField):
# if an instance, return the instance
return value
if value == None:
# if db has NULL (==None in Python), return empty string
return ""
try:
return int(value)
except (TypeError, ValueError):
msg = self.error_messages['invalid'] % str(value)
raise exceptions.ValidationError(msg)
def get_prep_value(self, value):
# catches value right before sending to db
if value == "":
# if Django tries to save an empty string, send to db None (NULL)
return None
else:
return int(value) # otherwise, just pass the value
采用
Finished = models.IntegerField('Finished percentage', blank=True, null=True)
閱讀https://docs.djangoproject.com/en/1.4/ref/models/fields/#blank :
null is purely database-related, whereas blank is validation-related.
您可能首先定義了沒有null=True
的字段。 現在在代碼中更改它不會更改數據庫的初始布局。 使用South進行數據庫遷移或手動更改數據庫。
在表單上,您可以在字段上設置required=False
:
Finished = forms.IntegerField(required=False)
或者為了避免重新定義 ModelForm 上的字段,
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['Finished'].required = False
#self.fields['Finished'].empty_label = 'Nothing' #optionally change the name
也許需要一個默認值
finished = models.IntegerField(default=None,blank=True, null=True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.