2017-05-23 31 views
1

我想創造我的模型Account時間戳,但我不希望我的兩個時間戳(created_atmodified_at)指定爲可編輯或甚至用戶可查看。一切工作正常,並按預期,直到我editable=Falsecreated_atmodified_at字段。這裏是我的模型:FieldError:未知領域(S)(created_at,modified_at)的帳戶

class Account(models.Model): 
    account_name = models.CharField(max_length=25) 
    active = models.BooleanField(default=True) 
    created_at = models.DateTimeField(null=True, blank=True, editable=False) 
    modified_at = models.DateTimeField(null=True, blank=True, editable=False) 

    def save(self): 
     if self.id: 
      self.modified_at = datetime.datetime.now() 
     else: 
      self.created_at = datetime.datetime.now() 
     super(Account, self).save() 

    class Meta: 
     ordering = ('id',) 

這裏是令人費解的錯誤我收到的時候我嘗試做任何事情(遷移的runserver等):

django.core.exception.FieldError: Unknown field(s) (created_at, modified_at) specified for Account

當我從兩個刪除editable=False領域,一切工作正常。這是一個Django的錯誤?有沒有更好的方法使該字段不可見並且不可編輯?

我使用的是Django 1.9和Python 3.6.1。感謝您的幫助,讓我知道您是否需要我發佈其他任何內容(視圖,序列化器等)。

編輯

完全回溯:https://pastebin.com/YEQACX5z

賬戶形式:

class AccountForm(ModelForm): 
    class Meta: 
     model = Account 
     fields = ['account_name', 'active', 'created_at', 'modified_at'] 
+0

請顯示完整的回溯。 – Alasdair

+0

增加了完整的追溯。 – Logicman

+0

回溯顯示錯誤發生在您的'AccountForm'中,您沒有顯示。 – Alasdair

回答

2

你可能只是這樣做,

created_at = models.DateTimeField(auto_now_add=True) 

modified_at = models.DateTimeField(auto_now=True) 

從文檔

DateField.auto_now¶

Automatically set the field to now every time the object is saved. Useful for 「last-modified」 timestamps. Note that the current date is always used; it’s not just a default value that you can override.

The field is only automatically updated when calling Model.save(). The field isn’t updated when making updates to other fields in other ways such as QuerySet.update(), though you can specify a custom value for the field in an update like that.

DateField.auto_now_add¶

Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it’s not just a default value that you can override. So even if you set a value for this field when creating the object, it will be ignored.

所以,沒有必要添加編輯=假,它已經不可編輯。

此外,請記住刪除您的save()方法覆蓋,因爲它試圖修改這些字段。

如果你希望能夠修改這一領域,設置以下的,而不是auto_now_add =真:對於本場

For DateField: default=date.today - from datetime.date.today() 
For DateTimeField: default=timezone.now - from django.utils.timezone.now() 

默認表單控件是一個TextInput。管理員添加了JavaScript日曆和「今日」的快捷方式。包含一個額外的invalid_date錯誤消息密鑰。

+0

這兩個都會引發與我添加editable = False時相同的錯誤:爲帳戶指定的'django.core.exception.FieldError:未知字段(created_at,modified_at) – Logicman

+0

@Logicman確保您刪除了'save( )'方法重寫。 – Soviut

+0

希望你有你在找什麼! – zaidfazil