2017-05-27 17 views
1

django定義,我們怎麼設置都沒有class Meta定義字段`如何設置場模型,這不是在元類

我有這樣的模式:

class User(models.Model): 
    user_name = models.CharField(max_length=32, unique=True) 
    email = models.EmailField(unique=True) 
    first_name = models.CharField(max_length=32) 
    last_name = models.CharField(max_length=32) 
    password_hash = models.CharField(max_length=64) 
    password_salt = models.CharField(max_length=64) 

這形式:

class ContactForm(ModelForm): 
    password = forms.CharField(widget=forms.PasswordInput()) 
    repeat_password = forms.CharField(widget=forms.PasswordInput()) 

    class Meta: 
     model = User 
     fields = ['user_name', 'email', 'first_name', 'last_name'] 

    def clean(self): 
     cleaned_data = super(ContactForm, self).clean() 
     password = cleaned_data.get('password') 
     repeat_password = cleaned_data.get('repeat_password') 

     if password is not None and repeat_password is not None: 
      if password != repeat_password: 
       raise forms.ValidationError("Passwords do not match.") 

      password_validate = password_validate = password_validation.validate_password(password) 
      if password_validate is not None: 
       raise password_validate 

我只希望用戶能夠設置user_nameemailfirst_namelast_name領域。在clean(self)我檢查輸入的密碼是否相符,以及它們是否有效。

我現在想要做的是設置我的模型Userpassword_hashpassword_salt。如何才能做到這一點?

回答

1

在的ModelForm的清潔方法只驗證在一個表格中的字段。 它不會爲模型設置任何數據。你在乾淨的方法中所做的是,你正在檢查發佈的數據是否是你想要或預期的格式。你可以看看更進這裏in the docs..

對於「設置」字段,你說你可能需要重寫形式保存方法。 Here in the docs..

的保存()method¶

每個的ModelForm還具有保存()方法。此方法從綁定到表單的數據創建並保存數據庫對象。 ModelForm的子類可以接受現有的模型實例作爲關鍵字參數實例;如果提供了,save()將更新該實例。

據我瞭解,你可以做這樣的事情,

def save(self, commit=True): 
    instance = super(ContactForm, self).save(commit=False) 
    instance.password_hash = #...How you want to do your password_hash is here. 
    instance.save() 

如果您正在尋找手動創建/管理密碼,我想這也許你正在尋找的東西:

Setting passwords manually

make_password(password [,salt,hashers])

創建在由本申請中使用的格式的哈希密碼。它需要一個強制參數:以純文本形式輸入密碼。或者,你可以提供一個鹽和散列算法來使用,如果你不想使用默認設置(的PASSWORD_HASHERS設置第一個條目)。目前支持的算法是: 'pbkdf2_sha256', 'pbkdf2_sha1', 'bcrypt_sha256'(請參閱使用bcrypt使用Django), 'bcrypt', 'SHA-1', 'MD5',(僅適用於向後兼容) 'unsalted_md5' 和 '地穴' 如果你已經安裝了crypt庫。如果密碼參數是None,則返回一個不可用的密碼(一個將不會被check_password()接受的密碼)。

+0

在點。謝謝@Fazil。 – arminb

相關問題