2011-09-07 33 views
50

每當我在Django的Admin部分輸入新玩家時,我都會收到一條錯誤消息,指出「此字段是必需的。」。如果不創建表單,我可以在Django中創建一個不需要的管理員字段嗎?

有沒有一種方法,使不需要現場,而無需創建自定義窗體?我可以在models.py或admin.py中執行此操作嗎?

這是我在models.py中的類看起來像。

class PlayerStat(models.Model): 
    player = models.ForeignKey(Player) 

    rushing_attempts = models.CharField(
     max_length = 100, 
     verbose_name = "Rushing Attempts" 
     ) 
    rushing_yards = models.CharField(
     max_length = 100, 
     verbose_name = "Rushing Yards" 
     ) 
    rushing_touchdowns = models.CharField(
     max_length = 100, 
     verbose_name = "Rushing Touchdowns" 
     ) 
    passing_attempts = models.CharField(
     max_length = 100, 
     verbose_name = "Passing Attempts" 
     ) 

感謝

+2

最簡單的方法是使用字段選項blank = True(https://docs.djangoproject.com/en/dev/ref/models/fields/#blank)。這有什麼原因不起作用? –

回答

99

只是把

blank=True 

在模型即:

rushing_attempts = models.CharField(
     max_length = 100, 
     verbose_name = "Rushing Attempts", 
     blank=True 
     ) 
+0

請注意,如果您使用「表單」,blank = true將不起作用。例如。這裏blank = true從模型不起作用:class MusModelForm(forms.ModelForm): name = forms.CharField(widget = forms.Textarea) #〜mitglieder = forms.CharField(widget = forms.Textarea) class Meta: model =音樂人 – Timo

3

使用空白=真,空=真

class PlayerStat(models.Model): 
    player = models.ForeignKey(Player) 

    rushing_attempts = models.CharField(
     max_length = 100, 
     verbose_name = "Rushing Attempts", 
     blank=True, 
     null=True 
     ) 
    rushing_yards = models.CharField(
     max_length = 100, 
     verbose_name = "Rushing Yards", 
     blank=True, 
     null=True 
     ) 
    rushing_touchdowns = models.CharField(
     max_length = 100, 
     verbose_name = "Rushing Touchdowns", 
     blank=True, 
     null=True 
     ) 
    passing_attempts = models.CharField(
     max_length = 100, 
     verbose_name = "Passing Attempts", 
     blank=True, 
     null=True 
     ) 
+1

至少從Django 1.6開始,CharFields應該不需要「null = True」,可能更早。同樣,對於TextField,SlugField,EmailField ......以文本形式存儲的任何內容。 – jenniwren

+0

對於嚴格包含文本的字段,Django不建議使用「null = True」。 – kas

相關問題