您可以为 request.get() (而不是 post.get)设置默认值吗?

发布于 2024-12-25 03:23:03 字数 494 浏览 3 评论 0原文

我在一个提交按钮下有 2 个 HTML 提交字段,其中之一是可选的。我使用“get”方法来检索提交的数据,但我希望可选字段具有默认值,以防用户提交空表单。如果我不这样做,我会收到 MultiValueDictKeyError。

if request.method == 'GET': 
        # required
        name = request.GET['name']
        # optional
        color = request.GET['color']

我认为一个可能的解决方案是尝试/除了每个字段,但是有没有更优雅的方法?我知道对于 get.post() 你可以做类似的事情

color = request.POST.get('color', False)

但这似乎不适用于 request.get()

有什么想法吗?

谢谢,

肥中微子

I have 2 HTML submission fields under one submit button, one of which is optional. I'm using the 'get' method to retrieve submitted data, but I want the optional field to have a default value just in case the user submits an empty form. If I don't do this, I get a MultiValueDictKeyError.

if request.method == 'GET': 
        # required
        name = request.GET['name']
        # optional
        color = request.GET['color']

I think a possible solution is try / except for every field, but is there a more elegant method? I know for get.post() you can do something like

color = request.POST.get('color', False)

But this doesn't seem to work for just request.get()

Any ideas?

Thanks,

fertileneutrino

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

挽手叙旧 2025-01-01 03:23:03

这里很困惑... request.get() 不起作用,但 request.GET.get() 应该起作用。您只是输入错误还是您实际上使用了 request.get()

Confused here... request.get() won't work, but request.GET.get() should. Did you just mistype or were you actually using request.get()?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文