profile_update_form 未正确更新字段,打印日志表明冗余 if 语句存在问题

问题描述 投票:0回答:1

提交更新个人资料表单预计会在 localhost:8000/profile/ 的同一页面上发布并返回更新的用户名

相反,页面刷新并返回未更改的用户名。

调试步骤。

  1. 视图的设置与打印日志类似,以识别问题区域。
# users/views/profile.py

from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth import update_session_auth_hash
from ..forms import ProfileUpdateForm, CustomPasswordChangeForm
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin

import logging

logger = logging.getLogger(__name__)

class ProfileView(LoginRequiredMixin, View):
    template_name = 'my_profile.html'

    def get(self, request, *args, **kwargs):

        print('getting...')
        profile_update_form = ProfileUpdateForm(instance=request.user)
        password_form = CustomPasswordChangeForm(user=request.user)
        context = {
            'profile_update_form': profile_update_form,
            'password_form': password_form,
        }
        return render(request, self.template_name, context)

    def post(self, request, *args, **kwargs):        
        profile_update_form = ProfileUpdateForm(instance=request.user)
        password_form = CustomPasswordChangeForm(user=request.user)
        print('posting...')
        print(request.POST) # identifies correct form input...
        print('user')
        print(request.user) # identifies current username
        print('username') 
        print(request.user.username) # identifies current username
        print('saving...') # printing successfully...

        if 'update_profile' in request. POST: 
            profile_update_form = ProfileUpdateForm(request.POST, instance=request.user)
            print('profile updating...') # seems to become unresponsive around here with no print logs...
            print(profile_update_form)
            
            if profile_update_form.is_valid():
                print('profile is valid')
                profile_update_form.save()
                messages.success(request, 'Your profile has been updated.')
                print("Profile updated")
                print(request.user)
                print(request.user.username)
                return redirect('my_profile')
            else:
                print("Profile not updated")
                print(profile_update_form.errors)
                for field, errors in profile_update_form.errors.items():
                    for error in errors:
                        messages.error(request, f"{field}: {error}")

[...]

    
  1. 模板设置如下(摘录)。它以前是脆脆的形式,但我现在尝试手动渲染它:
           <form method="post" action="{% url 'my_profile' %}">
               {% csrf_token %}
               <input type="hidden" name="form_type" value="update_profile">
               <!-- Manually render each field -->
               {% for field in profile_update_form %}
                   <div>
                       <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                       {{ field }}
                       {% if field.help_text %}
                           <small style="color: grey;">{{ field.help_text }}</small>
                       {% endif %}
                       {% for error in field.errors %}
                           <div style="color: red;">{{ error }}</div>
                       {% endfor %}
                   </div>
               {% endfor %}
               <button type="submit" class="btn btn-primary">Update Profile</button>
           </form>
django-views django-forms django-templates django-crispy-forms
1个回答
0
投票

if 语句需要正确调用表单。

更改为正确的表单类型侦听器允许表单成功提交。

if request. POST.get('form_type') == 'update_profile' 
# locates the form with hidden input: <input type="hidden" name="form_type" value="update_profile"> 
# ...proceeds to save as expected 

这甚至适用于脆皮表单,它只需要通过隐藏输入来定位

<form method="post" action="{% url 'my_profile' %}">
    {% csrf_token %}

     <!-- ProfileView class finds the following hidden input with IF request line 41: if POST.get('form_type') == 'update_profile' -->
    <input type="hidden" name="form_type" value="update_profile"> 

    {{ profile_update_form|crispy }}  
    <button type="submit" class="btn btn-primary">Update Profile</button>
</form>

© www.soinside.com 2019 - 2024. All rights reserved.