简体   繁体   English

在POST和CBV中处理kwarg

[英]handling kwargs in POST and CBV

In my last question , I had trouble displaying imported choices in a select widget because I was missing a (should have been) obvious bit of code. 在我的最后一个问题中 ,我在选择小部件中显示导入的选择时遇到了麻烦,因为我缺少了(应该是)明显的一些代码。 Now, my GET (seems to) work just fine. 现在,我的GET(似乎可以正常工作)。 The problem is I am doing something wrong in my POST. 问题是我在POST中做错了什么。

What I can't figure out is how the kwargs should be handled in POST. 我不知道如何在POST中处理kwarg。 If I include kwargs in my post method in the line 如果我在行的post方法中包含kwargs

form = Enter_SW_Room(request.POST, **kwargs)

I receive the error __init__() got multiple values for argument 'data' . 我收到错误__init__() got multiple values for argument 'data' Looking around stack overflow, I find most of the problems with this error stem from calling self in super (or other calling errors). 环顾堆栈溢出,我发现此错误的大多数问题源于在super中调用self(或其他调用错误)。 Eg this problem / solution . 例如这个问题/解决方案 If I try to work around this problem by NOT passing kwargs, the validation fails. 如果我尝试通过不传递kwargs来解决此问题,则验证失败。 (I think because there is now a value for the appropriate field, but the choices are gone.) (我认为这是因为适当的字段现在有一个值,但是选择已经消失了。)

So, what I figure is that either I'm doing something simple but importantly wrong again, or I need to modify the form validation. 因此,我认为是我正在做一些简单但又很重要的错误,或者我需要修改表单验证。 (or ???) (要么 ???)

Here's all the code (snipped for brevity): 这是所有代码(为简洁起见,略):

''' views.py '''
class DockingBay(FormMixin, TemplateView):
    form_class = Enter_SW_Room

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        # snip; create my_avatar_choices, which is more than just a queryset
        kwargs['avatar_list'] = my_avatars_choices
        return kwargs

    def get(self, request, *args, **kwargs):
        kwargs = self.get_form_kwargs()
        # snip
        my_rooms_list = []  # used in the template
        form = Enter_SW_Room(**kwargs)
        args = {'form': form, 'my_rooms_list': my_rooms_list}

        return render(request, self.template_name, args)

    def post(self, request, **kwargs):
        print(request.POST)
        kwargs = self.get_form_kwargs()
        form = Enter_SW_Room(request.POST, **kwargs)
        if form.is_valid():
            # snip - logic to enter the room with correct passcode
            return redirect('swdice:swroom', swroom_id)
        else:
            # snip - error handling will go here


'''forms.py'''
class Enter_SW_Room(forms.ModelForm):
    class Meta:
        model = EnterSWroom
        widgets = {'default_avatar': forms.Select()}
        fields = ('room_number', 'passcode', 'default_avatar')

    def __init__(self, *args, **kwargs):
        imported_list = kwargs.pop('avatar_list')
        super().__init__(*args, **kwargs) 
        self.fields['default_avatar'].choices = imported_list

    default_avatar = forms.ChoiceField(choices=[])


'''template'''
<h4>Enter a room using passcode</h4>
    <form method="post">
        {% csrf_token %}
        <table>
            <col width="240">
            <col width="120">
            <tr>
                <td><strong>Room ID:</strong>
                <br>This will be a number.</td>
                <td>{{form.room_number}} <br>
                    <strong>{{ form.room_number.errors }}</strong>
                </td>
            </tr>
            <tr>
                <td><strong>Passcode:</strong>
                <br>If the room is open, or you have been in it before, leave this  blank.</td>
                <td>{{form.passcode}} <br>
                    <strong>{{ form.passcode.errors }}</strong>
                </td>
            </tr>
            <tr>
                <td><strong>Avatar:</strong>
                <br>Select your avatar.</td>
                <td>{{form.default_avatar}} <br>
                    <strong>{{ form.default_avatar.errors }}</strong>
                </td>
            </tr>
        </table>
        <button type="submit">Enter Room</button>
    </form>
    <hr>

You can prevent the error by changing the code to: 您可以通过将代码更改为以下内容来防止错误:

form = Enter_SW_Room(**kwargs)

Your current code is equivalent to 您当前的代码等效于

form = Enter_SW_Room(data=request.POST, **kwargs)

Since kwargs already contains 'data' , you get the multiple argument error. 由于kwargs已经包含'data' ,因此您会收到多参数错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM