Я не понимаю этот код и не знаю, как его использовать? - PullRequest
0 голосов
/ 07 ноября 2019

Я взял код из учебника, и мне нужен профессиональный взгляд и описание шаг за шагом

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
})

1 Ответ

0 голосов
/ 08 ноября 2019
    # 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
})
...