python - Django UpdateView 的内联表单集

标签 python django django-generic-views inline-formset

我的 Django 应用程序中有以下表单:

class SurveyAreaForm(ModelForm):
    class Media(object):
        js = formset_media_js

    class Meta:
        model = SurveyArea
        exclude = ['survey', ]
        widgets = {
            'action_by': CustomDateInput(),
        }


AreaFormSet = inlineformset_factory(Survey, SurveyArea, form=SurveyAreaForm)

class SurveyForm(ModelForm):
    class Meta:
        model = Survey
        exclude = ['tech', 'operator', ]
        widgets = {
            'date': CustomDateInput(),
            'client': FilteredJQMRadioSelectWithAdd(),
            'assessorSignature': SignatureInput(attrs={'id': 'assessorSignature'}),
        }

    def __init__(self, *args, **kwargs):
        super(SurveyForm, self).__init__(*args, **kwargs)
        self.fields['client'].empty_label = None

我正在使用https://pypi.python.org/pypi/django-formset-js/0.3.0提供 JavaScript 添加附加表单。

每个 Survey 对象都可以有一个或多个与其关联的 SurveyArea,我希望使用相同的表单使它们可编辑。但是,我在渲染初始数据时遇到了问题。这是我的观点:

class SurveyUpdateView(SurveyValidateMixin, UpdateViewWithTech):
    model = Survey
    form_class = SurveyForm
    success_url="/forms/survey/updated/"
    template_name="my_django_app/survey_update.html"

    def get(self, request, *args, **kwargs):
        """
        Handles GET requests and instantiates blank version of the form
        and its inline formsets.
        """
        self.object = self.get_object()
        form_class = self.get_form_class()
        form = self.get_form(form_class)

        # Get areas
        areas = SurveyArea.objects.filter(survey=self.object).order_by('name').values()

        # Render form
        area_form = AreaFormSet(initial=areas)
        return self.render_to_response(
            self.get_context_data(form=form,
                                area_form = area_form))

    def post(self, request, *args, **kwargs):
        """
        Handles POST requests, instantiating a form instance and its inline
        formsets with the passed POST variables and them checking them for
        validity.
        """
        self.object = self.get_object()
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        area_form = AreaFormSet(self.request.POST)
        if (form.is_valid() and area_form.is_valid()):
            return self.form_valid(form, area_form)
        else:
            return self.form_invalid(form, area_form)

我还有一个 SurveyCreateView,它工作得很好,并且使用 SurveyValidateMixin 在这些 View 之间共享验证。 SurveyUpdateView 也继承自 UpdateViewWithTech,它基本上只是限制用户的查询集并自动设置代表用户的字段。

我遇到的问题是渲染初始数据。在 SurveyUpdateViewget() 方法中,我正在获取当前与该调查关联的所有区域,并使用 PDB 我已经能够在当我获取与本次调查相关的区域(在可变区域中)时,数据似乎是正确的。以下是 8 个项目的外观:

[{'description': u'A', 'photo': u'', 'action_required': u'A', 'action_by': datetime.date(2013, 11, 14), 'survey_id': 12L, u'id': 21L, 'action_taken': True, 'name': u'A'}, {'description': u'A', 'photo': u'', 'action_required': u'A', 'action_by': datetime.date(2013, 11, 14), 'survey_id': 12L, u'id': 19L, 'action_taken': True, 'name': u'A'}, {'description': u'A', 'photo': u'', 'action_required': u'A', 'action_by': datetime.date(2013, 11, 14), 'survey_id': 12L, u'id': 29L, 'action_taken': True, 'name': u'A'}, {'description': u'A', 'photo': u'', 'action_required': u'A', 'action_by': datetime.date(2013, 11, 14), 'survey_id': 12L, u'id': 30L, 'action_taken': True, 'name': u'A'}, {'description': u'B', 'photo': u'', 'action_required': u'B', 'action_by': datetime.date(2013, 11, 14), 'survey_id': 12L, u'id': 22L, 'action_taken': True, 'name': u'B'}, {'description': u'B', 'photo': u'', 'action_required': u'B', 'action_by': datetime.date(2013, 11, 14), 'survey_id': 12L, u'id': 20L, 'action_taken': True, 'name': u'B'}, {'description': u'B', 'photo': u'', 'action_required': u'B', 'action_by': datetime.date(2013, 11, 14), 'survey_id': 12L, u'id': 31L, 'action_taken': True, 'name': u'B'}, {'description': u'C', 'photo': u'', 'action_required': u'C', 'action_by': datetime.date(2013, 11, 14), 'survey_id': 12L, u'id': 23L, 'action_taken': True, 'name': u'C'}, {'description': u'X', 'photo': u'', 'action_required': u'X', 'action_by': datetime.date(2013, 11, 14), 'survey_id': 12L, u'id': 24L, 'action_taken': True, 'name': u'X'}, {'description': u'Y', 'photo': u'', 'action_required': u'Y', 'action_by': datetime.date(2013, 11, 14), 'survey_id': 12L, u'id': 25L, 'action_taken': True, 'name': u'Y'}, {'description': u'Z', 'photo': u'', 'action_required': u'Z', 'action_by': datetime.date(2013, 11, 14), 'survey_id': 12L, u'id': 26L, 'action_taken': True, 'name': u'Z'}]

但是,在实例化 AreaFormSet 时将该数据作为 initial 的值传递不会正确呈现数据。如果在 AreaFormSet 的定义中,我设置了 extra 的值,我会得到渲染的区域数量(如果未定义,则显示三个,我认为这是默认值额外的)。我希望看到的行为是以自己的形式呈现每个现有区域。

再次使用PDB,如果我在用area_form.as_table()设置之后转储area_form的值,我只能得到extra中设置的表单数量,所以问题似乎确实在于传递初始数据。

我是否正确传递了initial 的值?我知道 initial 的值应该是一个字典列表,它对我来说看起来是正确的,但我没有得到正确的渲染区域数量。

最佳答案

你试过吗

area_form = AreaFormSet(instance=self.object)

而不是

area_form = AreaFormSet(initial=areas)

关于python - Django UpdateView 的内联表单集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19765214/

相关文章:

python - Django:链接 'startswith' 和 'iexact' 查询过滤器?

python - 如何正确删除特定的 ManyToMany 关系?

python - 权限混入 Django REST ListCreateAPIView

python - Sucess_url 基于来自 urls.py 的 GenericView 中的 pk

python - Django:向模型类对象添加附加属性

django - 使用 get_queryset() 方法或设置查询集变量?

python - 如何编写符合 PEP8 的超长字符串并防止 E501

java - 从 pubchem 中提取与单同位素质量匹配的 sdf 文件

python selenium 远程 webdriver safari 驱动程序

Django 找不到重定向页面