如何在模型 Django 中创建密码字段
Posted
技术标签:
【中文标题】如何在模型 Django 中创建密码字段【英文标题】:How to create Password Field in Model Django 【发布时间】:2013-07-05 14:04:09 【问题描述】:我想在视图中创建密码作为密码字段。
models.py:
class User(models.Model):
username = models.CharField(max_length=100)
password = models.CharField(max_length=50)
forms.py:
class UserForm(ModelForm):
class Meta:
model = User
【问题讨论】:
这里,这将回答你的问题***.com/a/3715382/997562 How to create password input field in django的可能重复 50 对于现代散列算法和长盐来说太小了。我认为您需要至少 256 个 【参考方案1】:使用小部件作为PasswordInput
from django import forms
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
【讨论】:
我试过了,但密码不再显示在字段中。该字段看起来总是空的【参考方案2】:您应该创建一个ModelForm
(docs),它有一个使用表单库中的PasswordInput
小部件的字段。
看起来像这样:
models.py
>from django import models
class User(models.Model):
username = models.CharField(max_length=100)
password = models.CharField(max_length=50)
forms.py(不是views.py)
from django import forms
class UserForm(forms.ModelForm):
class Meta:
model = User
widgets =
'password': forms.PasswordInput(),
有关在视图中使用表单的更多信息,请参阅this section of the docs。
【讨论】:
【参考方案3】:查看我的代码,这可能会对您有所帮助。 模型.py
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(max_length=100)
password = models.CharField(max_length=100)
instrument_purchase = models.CharField(max_length=100)
house_no = models.CharField(max_length=100)
address_line1 = models.CharField(max_length=100)
address_line2 = models.CharField(max_length=100)
telephone = models.CharField(max_length=100)
zip_code = models.CharField(max_length=20)
state = models.CharField(max_length=100)
country = models.CharField(max_length=100)
def __str__(self):
return self.name
forms.py
from django import forms
from models import *
class CustomerForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = Customer
fields = ('name', 'email', 'password', 'instrument_purchase', 'house_no', 'address_line1', 'address_line2', 'telephone', 'zip_code', 'state', 'country')
【讨论】:
【参考方案4】:我认为这是一种很有帮助的方式。
models.py
from django.db import models
class User(models.Model):
user_name = models.CharField(max_length=100)
password = models.CharField(max_length=32)
forms.py
from django import forms
from Admin.models import *
class User_forms(forms.ModelForm):
class Meta:
model= User
fields=[
'user_name',
'password'
]
widgets =
'password': forms.PasswordInput()
【讨论】:
以上是关于如何在模型 Django 中创建密码字段的主要内容,如果未能解决你的问题,请参考以下文章