在 Django 中处理请求变量的最佳方法

发布于 2024-07-29 03:37:51 字数 386 浏览 1 评论 0原文

我有一个“野外”表单,它采用许多不同的变量 - 可能会或可能不会填充。

   try:
        app_version = request.REQUEST["appVersion"]
    except:
        app_version = ''

    try:
        app_name = request.REQUEST["appName"]
    except:
        app_name = ''

    try:
        app_code_name = request.REQUEST["appCodeName"]
    except:
        app_code_name = ''

有没有更严格的方法来实现这一点?

I have a form 'in the wild' that takes many different variables - which may or may not be populated.

   try:
        app_version = request.REQUEST["appVersion"]
    except:
        app_version = ''

    try:
        app_name = request.REQUEST["appName"]
    except:
        app_name = ''

    try:
        app_code_name = request.REQUEST["appCodeName"]
    except:
        app_code_name = ''

Is there a tighter way to accomplish this?

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

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

发布评论

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

评论(3

云朵有点甜 2024-08-05 03:37:51
app_version = request.REQUEST.get("appVersion", "")

get(key, default) 是在 Python dicts 上实现的方法。 如果字典中存在该键,则返回其值; 如果键不存在,则返回指定的默认值。 在Django中,request对象是类似字典的对象,因此也以相同的方式为它们定义了get

app_version = request.REQUEST.get("appVersion", "")

get(key, default) is a method implemented on Python dicts. If the key exists in the dictionary, its value is returned; if the key does not exist, the specified default value is returned. In Django, request objects are dictionary-like objects, so get is also defined for them in the same manner.

最近可好 2024-08-05 03:37:51

如果这些变量旨在填充表单,那么您可以安全地将 request.POST 对象直接传递到表单构造函数中。

if request.method == 'POST':
    form = MyForm(request.POST)

表单将自动将正确的值传递到正确的表单字段并对不存在的键使用默认值,并且仍将为缺失的键创建空白字段(请参阅附录)。

如果您尝试处理表单,最好还是像上面那样创建一个表单对象,并从该对象中读取值。

if request.method == 'POST':
    form = MyForm(request.POST)
    if form.is_valid():
        # You may process these variables here
        print form.appVersion
        print form.appName
        print form.appCodeName

请记住,验证代码最好也放置在表单类中。 这样,如果 form.is_valid() 返回 True,那么您就知道您有一个干净的数据集可供使用。

注意:Django 文档建议直接使用 request.POSTrequest.GET 而不是合并变量 request.REQUEST,因为它更明确。

附录:

在这种情况下,了解绑定表单和非绑定表单之间的区别非常重要。 如果您使用 form = MyForm() 创建未绑定表单,那么当实例化表单时,它将使用每个字段的 initial 属性填充所有字段(如果存在)。 例如,使用以下代码:

from django import forms

class MyForm(forms.Form):
    appVersion = forms.CharField(initial='1.0')
    appName = forms.CharField()
    appCodeName = forms.CharField()

表单将使用值为“1.0”的 appVersion 进行初始化。 但是,如果将 POST 请求绑定到如下形式的表单:form = MyForm(request.POST),则初始属性将被忽略。 这意味着如果 POST 字典不包含 appVersion 键,则该字段将留空。 只要该字段不是必填字段,您的表单仍然会验证,您可以在验证后在视图中修改 form.appVersion

If these variables are intended to populate a form, then you can safely pass the request.POST object directly into the form constructor.

if request.method == 'POST':
    form = MyForm(request.POST)

The form will automatically pass the correct values to the correct form fields and use defaults for keys that don't exist and will still create blank fields for missing keys (see addendum).

If you are trying to process a form, it is still better to create a form object as above, and read out the values from that object.

if request.method == 'POST':
    form = MyForm(request.POST)
    if form.is_valid():
        # You may process these variables here
        print form.appVersion
        print form.appName
        print form.appCodeName

Remember, validation code is best placed in the form class as well. That way, if form.is_valid() returns True, then you know you have a clean dataset to work with.

Note: Django docs recommend using request.POST or request.GET directly rather than the amalgamated variable request.REQUEST, as it is more explicit.

Addendum:

It is important to understand the difference between bound and unbound forms in this case. If you create an unbound form with form = MyForm(), then when the form is instantiated, it will fill in all fields with the initial property of each field (if it exists). For example, with this code:

from django import forms

class MyForm(forms.Form):
    appVersion = forms.CharField(initial='1.0')
    appName = forms.CharField()
    appCodeName = forms.CharField()

the form will be initialized with appVersion having a value of '1.0'. However, if you bind a POST request to a form like this: form = MyForm(request.POST), then the initial properties are ignored. That means if the POST dict does not include an appVersion key, then that field will be left blank. As long as the field is not required, your form will still validate, and you can modify form.appVersion in the view after validation.

小清晰的声音 2024-08-05 03:37:51

如果您有很多字段,更紧凑的版本可能是:

defaults = { 'field1' : 'val1', 'field2' : 'val2', ...}
defaults.update(request.POST)

If you have many fields, a more compact version might be:

defaults = { 'field1' : 'val1', 'field2' : 'val2', ...}
defaults.update(request.POST)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文