2016-04-14 78 views
0

我想用高清/功能異常值:失蹤1人需要的位置參數

獲得默認值以在代碼段一看:

models.py

from django.http import HttpRequest 

class Contacts(Model): 
    def get_client_ip(ip): 
     x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') 
     if x_forwarded_for: 
      ip = x_forwarded_for.split(',')[0] 
     else: 
      ip = request.META.get('REMOTE_ADDR') 
     return ip 

    ipaddress = CharField(default=get_client_ip, max_length=20, verbose_name='your IP Address') 

makemigrations和migrate執行它沒有錯誤或警告。

當我跑了,我得到了以下內容: 異常值:get_client_ip()失蹤1個人需要的位置參數:「IP」

能否請你幫助我嗎?

+3

不應該是'def get_client_ip(self,ip):' –

+1

你的'get_client_ip'不知道'request' – ilse2005

+0

@JacquesGaudin,我做了你告訴我的,並得到了以下結果:「異常值:get_client_ip()缺少2個必需的位置參數:'self'和'ip'「 – Marcos

回答

1

您的代碼有多個錯誤。

Value: get_client_ip() missing 1 required positional argument:

這是因爲default=get_client_ip調用不帶參數的功能。另外我不明白爲什麼get_client_ip需要ip?只是刪除,並使用@staticmethod

@staticmethod 
def get_client_ip(): 
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') 
    if x_forwarded_for: 
     ip = x_forwarded_for.split(',')[0] 
    else: 
     ip = request.META.get('REMOTE_ADDR') 
    return ip 

但是,這也將無法正常工作,因爲requestget_client_ip定義。請求對模型不可見。解決此問題的最簡單方法是刪除默認設置並將get_client_ip邏輯移至您的視圖,並在模型創建時設置ip字段。

+0

能否請你解釋一下:「在模型創建時設置ip字段」? – Marcos

0

我不認爲你可以傳遞參數到默認字段。我能想到的實現你想要的最好的方式是覆蓋模型的保存功能。

如:

class Contacts(models.Model): 
    ipaddress = CharField(max_length=20, verbose_name='your IP Address') 
    ... 
    def save(self): 
     if not self.id: #first time saving the model 
     self.ip = self.get_client_ip(self.ip) 
     super(Contacts, self).save(*args, **kwargs) 

編輯:

對不起只是意識到你解析HTTP頭獲取字段值。您應該直接從控制器中爲您的型號設置此選項,並使用save函數來執行您可能需要的任何清理。

+0

我做了你告訴我和我保存它時得到的:異常值:'聯繫人'對象沒有屬性'id' 與此行相關:if not self.id:#first first saving the model。模型def仍然是這樣的:def get_client_ip():你能幫我嗎? – Marcos

+0

通過'id'我指的是你的模型的主要領域。你是否將任何字段定義爲「primary」或「OneToOneField」?使用它來代替'id' – sudshekhar

相關問題