我从本教程中获取了代码,并且需要逐步获得专业的外观和描述
views.py
@login_required
@transaction.atomic
def update_profile(request):
if request.method == 'POST':
user_form = UserForm(request.POST, instance=request.user)
profile_form = ProfileForm(request.POST,instance=request.user.profile)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
messages.success(request, _('Your profile was successfully updated!'))
return redirect('settings:profile')
else:
messages.error(request, _('Please correct the error below.'))
else:
user_form = UserForm(instance=request.user)
profile_form = ProfileForm(instance=request.user.profile)
return render(request, 'profiles/profile.html', {
'user_form': user_form,
'profile_form': profile_form
})
答案 0 :(得分:0)
# login_required decorator - This decorator is used,so that only the logged in user can call this user
@login_required
# transaction.atomic decorator - This decorator is used, so that if the block of code is successfully completed,
# then only the changes are committed to the database.
@transaction.atomic
def update_profile(request):
if request.method == 'POST':
# if the request is post, then pass the request post object and user instance to the UserForm and ProfileForm class.
user_form = UserForm(request.POST, instance=request.user)
profile_form = ProfileForm(request.POST,instance=request.user.profile)
# if the post data is valid, then save both the form
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
# message after the saving the data
messages.success(request, _('Your profile was successfully updated!'))
# redirect the user to the profile page
return redirect('settings:profile')
else:
messages.error(request, _('Please correct the error below.'))
else:
# if the request is get, then only return the form classes with the user objects
user_form = UserForm(instance=request.user)
profile_form = ProfileForm(instance=request.user.profile)
return render(request, 'profiles/profile.html', {
'user_form': user_form,
'profile_form': profile_form
})