2017-07-17 138 views
0

python中的新內容,並且很難解決錯誤代碼。'NoneType'對象沒有屬性'to_bytes'

我有一個表格,將行添加到postgresql數據庫。表單有一個autofield,它是我的models.py中的主鍵。添加行作爲這樣的作品,以及UNIQUEID領域,如inteded計數(1,2,3,...)

models.py:

class forwards(models.Model): 
    uniqueid = models.AutoField(primary_key=True) 
    user = models.CharField(max_length = 150) 
    urlA = models.CharField(max_length = 254) 
    counterA = models.DecimalField(max_digits=19, decimal_places=0,default=Decimal('0')) 
    urlB = models.CharField(max_length = 254) 
    counterB = models.DecimalField(max_digits=19, decimal_places=0,default=Decimal('0')) 
    timestamp = models.DateTimeField('date created', auto_now_add=True) 
    shortcodeurl = models.CharField(max_length = 254) 

forms.py:

class AddUrlForm(forms.ModelForm): 

    class Meta: 
     model = forwards 
     # fields = '__all__' 
     exclude = ["user", "counterA", "counterB", "shortcodeurl", "uniqueid"] 

目標是使用主鍵值(根據here應該是一個整數),將其轉換爲「字節」,然後執行從字節到base64的轉換以創建簡碼URL。我想在表格中存儲這個簡碼。我嘗試這樣做在views.py

views.py

def forwardthis(request): 
    forwardform = AddUrlForm(request.POST or None) 
    if forwardform.is_valid(): 
     forward = forwardform.save(commit=False) 
     forward.user = request.user.username 
     uniqueid_local = forward.uniqueid 
     print(uniqueid_local) 
     uniqueid_local_bytes = uniqueid_local.to_bytes(3, byteorder='big') 
     shortcodeurl_local = urlsafe_base64_encode(uniqueid_local_bytes) 
     forward.shortcodeurl = shortcodeurl_local 
     forward.save() 

我的問題:

我沒有創建這個短代碼URL成功,我得到一個 「NoneType」錯誤。我試着將models.py修改爲BigIntegerField和IntegerField,但那不起作用。添加" default=0 "uniqueid = models.AutoField(primary_key=True)產生錯誤,我第一次提交表單,但隨後,提交第二表單時,它給出了一個錯誤null value in column "timestamp" violates not-null constraint

對我來說,它看起來像uniqueid並不像一個整數認可。如何解決這個問題?

感謝您的幫助!

回答

1

AutoFields由數據庫本身設置,所以在保存之前不要獲取值。但是你還沒有保存過,因爲你通過了commit=False來保存表格;這會在內存中創建一個實例,但不會將其發送給數據庫。

如果你想這個工作,你將不得不刪除該commit=False並接受兩次保存到數據庫(微小)的成本。

+0

工程就像一個魅力!謝謝 – radzia2

相關問題