我在django中有一个注册表单,通过它我可以为新用户输入条目。可以使用u_form.save
方法保存数据,但是我还需要用户输入的普通密码,因为通过REST API在其他网站中创建帐户需要该密码,因此两个密码必须相同。我可以从表单中访问密码,但是当我收到密码时,Django已经对其进行了加密。如何获得原始的普通密码?
这是我尝试过的:
views.py
from users.forms import SignUpForm, ProfileForm
def create(request):
context = {}
if(request.method == 'POST'):
u_form = SignUpForm(request.POST) # fill it with user details
p_form = ProfileForm(request.POST, request.FILES)
if u_form.is_valid() and p_form.is_valid():
user = u_form.save()
email = user.email
username = user.username
first_name = user.first_name
# Accessing plain password
password = user.password
Profile.objects.filter(user=user).delete()
profile = p_form.save(commit=False)
profile.user = user
profile.save()
messages.success(request, f'Account Created')
# LOGIC TO CREATE MANTIS ACCOUNT THROUGH THE REST API WITH SAME USERNAME AND PASSWORD AS OF MY DJANGO WEBSITE
return render(request, 'mainapp/homepage.html', context)
forms.py
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User
from .models import Profile
class SignUpForm(UserCreationForm):
email = forms.EmailField(required=True,
label='Email',
error_messages={'exists': 'Oops'},
widget=forms.TextInput(attrs={'readonly':'readonly'}))
username = forms.Field(widget=forms.TextInput(attrs={'readonly':'readonly'}))
first_name = forms.Field(widget=forms.TextInput(attrs={'readonly':'readonly'}))
readonly_fields = ('username', 'first_name', 'email')
class Meta:
model = User
fields = ("username", "first_name", "email", "password1", "password2")
class ProfileForm(forms.ModelForm):
emp_type = forms.Field(widget=forms.TextInput(attrs={'readonly':'readonly'}))
pay_type = forms.Field(widget=forms.TextInput(attrs={'readonly':'readonly'}))
class Meta:
model = Profile
fields = ['pay_type', 'emp_type', 'contact', 'whatsapp', 'gender', 'avatar']
在这里的views.py password = user.password
中,我试图获取密码,但是它为我提供了加密的密码,而不是普通密码。有什么办法可以做到这一点?
注意::为了达到此目的,我了解安全威胁。我只想知道如何实现?
答案 0 :(得分:0)
以Daniel Roseman的答复为基础,是的,我们可以使用.cleaned_data attribute
访问纯密码字段。这是您的操作方式。
password = u_form.cleaned_data['password']