Django - 如何使用两种形式从视图中访问文件
Django - How to access files from view with two forms
我有两种形式的视图:
def CreateNewUserView(request):
if request.method == 'POST':
user_form = UserCreationForm(request.POST, prefix='user_form')
user_profile_form = UserProfileCreationForm(request.POST, request.FILES, prefix='user_profile_form')
if user_form.is_valid():
new_user = user_form.save()
if user_profile_form.is_valid():
profile_picture = request.FILES['profile_picture']
new_user_profile = UserProfile(user=new_user, profile_picture=profile_picture,
)
new_user_profile.save()
username = user_form.cleaned_data['username']
password = user_form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
return HttpResponseRedirect('/dashboard/')
else:
# Allow user to select a role
user_form = UserCreationForm(prefix='user_form')
user_profile_form = UserProfileCreationForm(prefix='user_profile_form')
return render(request, 'dashboard/create_user.html', {
'user_form':user_form,
'user_profile_form':user_profile_form,
})
现在,当我通过 request.FILES
数组访问 profile_picture
时,user_profile_form
无法验证。我将如何正确访问该文件?
谢谢!
尝试:
profile_picture = user_profile_form.cleaned_data['profile_picture']
if profile_picture:
new_user_profile = UserProfile()
new_user_profile.user=new_user
new_user_profile.profile_picture=profile_picture
new_user_profile.save()
您正在验证您的表格,您没有参加 cleaned_date
希望对您有所帮助..
我有两种形式的视图:
def CreateNewUserView(request):
if request.method == 'POST':
user_form = UserCreationForm(request.POST, prefix='user_form')
user_profile_form = UserProfileCreationForm(request.POST, request.FILES, prefix='user_profile_form')
if user_form.is_valid():
new_user = user_form.save()
if user_profile_form.is_valid():
profile_picture = request.FILES['profile_picture']
new_user_profile = UserProfile(user=new_user, profile_picture=profile_picture,
)
new_user_profile.save()
username = user_form.cleaned_data['username']
password = user_form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
return HttpResponseRedirect('/dashboard/')
else:
# Allow user to select a role
user_form = UserCreationForm(prefix='user_form')
user_profile_form = UserProfileCreationForm(prefix='user_profile_form')
return render(request, 'dashboard/create_user.html', {
'user_form':user_form,
'user_profile_form':user_profile_form,
})
现在,当我通过 request.FILES
数组访问 profile_picture
时,user_profile_form
无法验证。我将如何正确访问该文件?
谢谢!
尝试:
profile_picture = user_profile_form.cleaned_data['profile_picture']
if profile_picture:
new_user_profile = UserProfile()
new_user_profile.user=new_user
new_user_profile.profile_picture=profile_picture
new_user_profile.save()
您正在验证您的表格,您没有参加 cleaned_date
希望对您有所帮助..