How to create Password Field in Model Django

后端 未结 4 875
名媛妹妹
名媛妹妹 2020-12-13 00:08

I want to create password as password field in views.

models.py:

class User(models.Model):
    username = models.CharField(max_lengt         


        
相关标签:
4条回答
  • 2020-12-13 00:42

    Use widget as PasswordInput

    from django import forms
    class UserForm(forms.ModelForm):
        password = forms.CharField(widget=forms.PasswordInput)
        class Meta:
            model = User
    
    0 讨论(0)
  • 2020-12-13 00:49

    See my code which may help you. models.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')
    
    0 讨论(0)
  • 2020-12-13 00:50

    I thinks it is vary helpful way.

    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()
             }
    
    0 讨论(0)
  • 2020-12-13 00:52

    You should create a ModelForm (docs), which has a field that uses the PasswordInput widget from the forms library.

    It would look like this:

    models.py

    from django import models
    class User(models.Model):
        username = models.CharField(max_length=100)
        password = models.CharField(max_length=50)
    

    forms.py (not views.py)

    from django import forms
    class UserForm(forms.ModelForm):
        class Meta:
            model = User
            widgets = {
            'password': forms.PasswordInput(),
        }
    

    For more about using forms in a view, see this section of the docs.

    0 讨论(0)
提交回复
热议问题