简体   繁体   English

如何从 Django 中的请求 QueryDict 中删除密钥?

[英]How to remove key from request QueryDict in Django?

Here is one of my Django views:这是我的 Django 视图之一:

def index(request):

    message = request.GET.get('message', '')

    context = RequestContext(request, {
    'message': message
    })

    return render(request, 'bets/index.html', context)

My goal is to display message in template only once, and not to display it on page reload.我的目标是只在模板中显示一次消息,而不是在页面重新加载时显示它。 I tried this:我试过这个:

request.GET['message'] = ''

but get error "This QueryDict instance is immutable".但得到错误“这个 QueryDict 实例是不可变的”。 How do I remove key from QueryDict?如何从 QueryDict 中删除密钥?

Even if you could remove that value from the querydict, that wouldn't help because it is based on the URL you've used to request that view, so when you refresh you're going to be using the same URL again with the existing parameters.即使您可以从查询字典中删除该值,这也无济于事,因为它基于您用来请求该视图的 URL,因此当您刷新时,您将再次使用现有的相同 URL参数。

Rather passing the message value in the GET parameters, put it in the session, and use request.session.pop('message') in the index view.而是在 GET 参数中传递消息值,将其放入会话中,并在索引视图中使用request.session.pop('message')

Even better, use the built-in messages framework which does all that for you.更好的是,使用为您完成所有这些的内置消息框架

@Daniel Rosemans answer is correct, in that you should use session to store value. @Daniel Rosemans 的答案是正确的,因为您应该使用 session 来存储价值。

However, to answer your original question in regards how to remove, GET and POST parameters are immutable.但是,要回答有关如何删除的原始问题,GET 和 POST 参数是不可变的。 You can not change these querydicts.您不能更改这些查询字典。 If you want to remove something from them (say, to prevent key from being iterated over) you need to make copy of the QueryDict and then pop item from it.如果您想从中删除某些内容(例如,防止密钥被迭代),您需要复制 QueryDict 然后从中弹出项目。

https://docs.djangoproject.com/en/3.1/ref/request-response/#querydict-objects https://docs.djangoproject.com/en/3.1/ref/request-response/#querydict-objects

The QueryDicts at request.POST and request.GET will be immutable when accessed in a normal request/response cycle. request.POST 和 request.GET 的 QueryDict 在正常的请求/响应周期中访问时将是不可变的。 To get a mutable version you need to use QueryDict.copy().要获得可变版本,您需要使用 QueryDict.copy()。

If you don't want to fix this problem in frontend, and still need Django's components like forms, this snippet may help.如果您不想在前端解决此问题,并且仍需要 Django 的组件(如表单),则此代码段可能会有所帮助。

fetch('', {
    "method": "POST",
    "headers": {
        "X-CSRFToken": csrfToken,
        "content-type": "application/json",
    },
    "body": JSON.stringify({
        "csrfmiddlewaretoken": "{{ csrf_token }}",
        "username": document.querySelector("#id_username").value,
        "password": document.querySelector("#id_password").value,
    })
}).then(res => res.json()).then(data => processData(data))
def fix_fetched_post(request):
    try:
        # fetch
        post_data = json.loads(request.body.decode("utf-8"))
        request.POST._mutable = True
        for key, value in post_data.items():
            request.POST[key] = value
        request.POST._mutable = False
    except:
        # form
        pass
    return request

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

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