Django占位符

时间:2014-11-10 18:10:33

标签: python django

我想插入此django模块“django.contrib.auth.models.User”提供的用户名,密码和密码2输入的占位符

from django import forms
#from .models import User
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm      

class RegistrationForm(UserCreationForm):
    email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder': 'Email'}),required = True)
    first_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'First Name'}),required = False)
    last_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Last Name'}),required = False)


    class Meta:
        model = User
        fields = ['first_name','last_name','email','username', 'password1', 'password2',]
        widgets={

                'username': forms.TextInput(attrs={'placeholder': 'User Name'}),
                'password1': forms.PasswordInput(attrs={'placeholder': 'Password'}),
                'password2': forms.PasswordInput(attrs={'placeholder': 'Confirm Password'}),
               }        

    def save(self,commit = True):   
        user = super(RegistrationForm, self).save(commit = False)
        user.email = self.cleaned_data['email']
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']


        if commit:
            user.save()


        return user

1 个答案:

答案 0 :(得分:3)

这是工作代码

from django import forms
#from .models import User
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm      

class RegistrationForm(UserCreationForm):
    email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder': 'Email'}),required = True)
    first_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'First Name'}),required = False)
    last_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Last Name'}),required = False)
    username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'User Name'}),required = True)
    password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'}),required = True)
    password2 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password'}),required = True)
    class Meta:
        model = User
        fields = ['first_name','last_name','email','username', 'password1', 'password2',]


    def save(self,commit = True):   
        user = super(RegistrationForm, self).save(commit = False)
        user.email = self.cleaned_data['email']
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']


        if commit:
            user.save()


        return user