【问题标题】:Django form received wrong data from request.POSTDjango 表单从 request.POST 收到错误的数据
【发布时间】:2020-06-10 12:29:18
【问题描述】:

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

Views.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']}>什么错误?任何建议或指导表示赞赏。

【问题讨论】:

    标签: python django


    【解决方案1】:

    问题来自这一行。

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

    【讨论】:

    • 如何将数据添加到 kwargs 中?我按照你说的改了代码但是kwargs里面没有user parameter,即使我在GET方法下写了profile_form = ProfileForm(instance=request.user.profile,user=request.user)
    • 您必须将userPOST 一起传递才能在表单发布时访问它。如果你只在GET 请求中传入用户,user 将在收到POST 请求时为空。
    【解决方案2】:

    在表单的 init() 中,如果用户,我不确定您要实现什么,我猜有些逻辑是错误的。您可以尝试更改此设置并再次检查。

    【讨论】:

    • 我从这里复制 link 我想这应该会阻止在 request.POST 时执行以下代码,但它现在不起作用
    • 请不要发布答案,除非它确实回答了问题。一旦您有足够的声誉,请使用 cmets 寻求澄清或建议。在此之前,请尝试找到您知道答案的答案或提出问题以提高您的声誉。
    • @DanielMorell,抱歉,我想通过显示问题所在来帮助他。从现在开始将遵循您的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    • 2021-03-03
    • 2021-01-22
    • 1970-01-01
    • 2022-01-08
    • 2018-07-22
    • 2018-10-23
    相关资源
    最近更新 更多