gpt4 book ai didi

python - 如何在 ModelForm 中添加密码占位符?

转载 作者:行者123 更新时间:2023-12-01 06:35:10 26 4
gpt4 key购买 nike

Django 1.11
我想在我拥有的所有表单中添加一个占位符,
我想知道为什么密码字段有(无值)?这是一张用于澄清的图片。 enter image description here我需要知道如何通过 forms.PasswordInput 添加密码占位符

表单.py

from django.contrib.auth.forms import User
from django import forms


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

class Meta:
model = User
fields = ['username', 'email', 'password']


class EditForm(UserForm):
def __init__(self, form):
super(EditForm, self).__init__(form)
for key, field in self.fields.items():
if isinstance(field.widget, forms.TextInput) or \
isinstance(field.widget, forms.EmailInput) or \
isinstance(field.widget, forms.PasswordInput):
field.widget.attrs.update({'placeholder': field.label})

注册.html

{% extends 'base.html' %}

{% block title %} Register {% endblock %}

{% block body %}
<div class="register">
<div class="container">
<h1>Register</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Registier</button>
</form>
</div>
</div>

{% endblock %}

View .py

from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from django.views import View
from .forms import UserForm, EditForm
from django.contrib.auth import authenticate



def index(request):
return render(request, 'account/index.html')


class UserRegister(View):
form_class = EditForm
template_name = 'account/register.html'

def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})

def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
username = form.cleaned_data['username']
password = form.cleaned_data['password']
email = form.cleaned_data['email']
user.set_password(password)
user.save()

user = authenticate(username=username, email=email, password=password)
return redirect('account:home')
return render(request, self.template_name, {'form': form})

最佳答案

尝试

class UserForm(forms.ModelForm):
password = forms.CharField(label='password',widget=forms.PasswordInput((attrs={'placeholder': 'Password'})))

关于python - 如何在 ModelForm 中添加密码占位符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59703110/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com