【问题标题】:Django response - if POST = None leave blank key, value pair from jsonresponseDjango 响应 - 如果 POST = None 留下空白键,来自 jsonresponse 的值对
【发布时间】:2021-12-31 02:15:45
【问题描述】:

下面的表单+视图可以正常工作

forms.py

class FormGlobalSettings(forms.Form):
global_font_family = forms.TypedChoiceField(required=False, label='Font Family', choices=choices_font_family, empty_value=None)

views.py

def main_view(request):
    if request.method != 'POST':
        form_global_settings = FormGlobalSettings()
    else:
    form_global_settings = FormGlobalSettings(data=request.POST)

    if all([form_global_settings.is_valid()]):
        cleaned_data = form_global_settings.cleaned_data

        nested_data = {"fontFamily": cleaned_data3['global_font_family']}

        return JsonResponse(nested_data)

    return render(request, 'pbi_theme_app/index.html', {'form_global_settings': form_global_settings})

输出是:

{"fontFamily": "Arial"}

但是,我想要实现的是,有时 POST 请求是空白/空/空,因为用户不希望在此字段中有任何值。 global_font_family 的选项以这种方式设置:

choices_font_family = [(None, ""), ("Arial", "Arial"), etc..]

这意味着如果用户将该字段留空,则结果为无。这导致它在 json 中为 null:

{"fontFamily": null}

现在我要实现的目标是,因为我已将“fontFamily”硬编码到 jsonresponse 中,如果用户决定将该字段为空,我希望整个键值对消失,这意味着整个键,值对 "fontFamily: null 从 jsonresponse 中消失了。

总结一下:我需要以某种方式使 json 中的键动态化,当 POST 请求为空时,我想保留整个键、值对,以免输入到 json 中。

在以下网页上可以看到预期的行为,当您下载主题并且您没有输入任何内容时,它会使整个 json 代码为空:

https://powerbi.tips/tools/report-theme-generator-v3/

谢谢你:)

【问题讨论】:

    标签: python json django


    【解决方案1】:

    首先,您不需要在选择列表中包含none。您可以简单地在 model.py 类字段中声明 null=True

    您可以通过在保存输入之前覆盖 model.py 类中的预期字段来实现预期行为

    假设我有以下课程。

    choices_font_family = [
        ("c1", "choice1"),
        ("c2", "choice2"),
        ("c3", "choice3"),
        ("c4", "choice4")
    ]
    class Post(models.Model):
        theme_type = models.CharField(null=True, max_length=255, verbose_name="some text", choices=choices_font_family )
        ....
        ....
    
        def save(self, force_insert=False, force_update=False, *args, **kwargs):
            if theme_type is None:
                theme_type = '<some font>' # overwriting none to whatever you want it to be
            super().save(force_insert, force_update, *args, **kwargs)
    

    编辑

    forms.py

    from django import forms
    from .models import FormGlobalSettings
    
    
    class UserdataModelForm(forms.ModelForm):
        class Meta:
            model = FormGlobalSettings
    
        def clean(self):
            return self.clean()
    
        def __init__(self, *args, **kwargs):
            self.request = kwargs.pop('request', None)
            super(UserdataModelForm, self).__init__(*args, **kwargs)
    

    models.py

     from django.db import models
    
     choices_font_family = [
            ("c1", "choice1"),
            ("c2", "choice2"),
            ("c3", "choice3"),
            ("c4", "choice4")
        ]
    class FormGlobalSettings(models.Model):
        theme_type = models.CharField(null=True, max_length=255, verbose_name="some text", choices=choices_font_family )
            ....
            ....
        
        def save(self, force_insert=False, force_update=False, *args, **kwargs):
            if theme_type is None:
                theme_type = '<some font>' # overwriting none to whatever you want it to be
            super().save(force_insert, force_update, *args, **kwargs)
    

    这里是 Django docs 保存和覆盖保存的链接。 here 是 Django 文档中有关如何使用表单和模型的示例。

    如果这解决了你的问题,别忘了接受这个作为正确答案。

    【讨论】:

    • 感谢您的回答,但是我没有使用任何模型,我的 model.py 是空的,我只在表单和视图中运行所有内容。 Bcs 我不完全理解我应该在哪里实现“保存”功能,以及如何调用它?
    • 我现在修改我的答案
    • 再次感谢您,但正如我所说,我根本没有使用模型,也不想使用它们,因为它们给我带来了一些问题。我只使用表单和视图。因此,我没有在仅使用 forms.Form 的表单中保存任何内容,就像在我发送的帖子中一样。
    • 所以我一直在尝试实施您的解决方案,但它的功能与我之前编写的完全相同。 models.Model 没有 save() 方法,似乎只有 ModelForm 。所以我不明白我们要保存什么。另外(如果 theme_type 为 None:theme_type = '')没有做任何事情,如果没有,我希望删除 theme_type(整个键、值对)。
    • 所以如果没有提供字体系列,我们将字体系列保存为等于默认字体值。所以你想要做的是,如果用户没有选择一种字体,你会用相同的字体覆盖默认字体。所以基本上如果你有一个包含字体系列的变量theme_type,你想说theme_type = default_font_family if font_family None else whatever the font family is given,我已经在上面展示了如何使用它。看到这个 [docs.djangoproject.com/en/3.2/ref/models/instances/… 覆盖保存
    猜你喜欢
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 2012-05-11
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    相关资源
    最近更新 更多