Django表单从request.POST接收到错误数据

2024-10-01 15:29:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我在表单中添加了一个过滤器,以便在请求时只显示属于用户的选项。GET,开始一切正常,但下次运行时,会出现问题。它显示了'QueryDict' object has no attribute 'id'错误,因此通过检查,我发现表单中的user变量接收了request.POST发送的数据。我想这不应该发生吧?这是我的密码

视图.py

@login_required
@transaction.atomic
def update_profile(request):
    if request.method == 'POST':
        profile_form = ProfileForm(request.POST,instance=request.user.profile)
        if profile_form.is_valid():
            profile_form.save()
            messages.success(request,_('success!'))
            return redirect('character-manage')
        else:
            messages.error(request,_('something is wrong.'))
    else:
        profile_form = ProfileForm(instance=request.user.profile,user=request.user)
    return render(request,'corp/profile.html',{
        'profile_form':profile_form
    })

Forms.py

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('pcharacter',)
    def __init__(self,user=None,**kwargs):
        super(ProfileForm,self).__init__(**kwargs)
        if user:
            self.fields['pcharacter'].queryset = EveCharacter.objects.filter(bounduser=user)

当我在__init__函数下添加print(user)时,刷新表单页面,我将获得一个用户对象,但当我提交表单时,它将显示类似这样的内容<QueryDict: {'csrfmiddlewaretoken': ['*****'], 'pcharacter': ['2']}>出了什么问题?如有任何建议或指导,我们将不胜感激


Tags: 用户pyselfform表单ifinitrequest
2条回答

在表单的init()中,如果是用户,我不确定您想要实现什么,我猜某些逻辑是错误的。你能试着改变这个然后再检查一下吗

问题来自这一行

profile_form = ProfileForm(request.POST,instance=request.user.profile)

您正在传递request.POST作为第一个参数。这被解释为,如果你写了这个

profile_form = ProfileForm(user=request.POST,instance=request.user.profile)

ModelForm中的第一个位置参数是data。这就是为什么您可以将request.POST作为位置参数传递,而无需写入data=request.POST

要解决此问题,您需要将__init__()函数更改为可与表单类继承自的__init__()函数一起操作

我想推荐这样的东西

def __init__(self, *args, **kwargs):
    super(ProfileForm,self).__init__(**kwargs)
    if 'user' in kwargs:
       self.fields['pcharacter'].queryset = EveCharacter.objects.filter(
           bounduser=kwargs.get('user')
       )

相关问题 更多 >

    热门问题