【问题标题】:Django CreateView validate field not in fieldsDjango CreateView 验证字段不在字段中
【发布时间】:2013-10-21 01:47:12
【问题描述】:

所以,我有一个 Django 通用视图:

class Foobaz(models.Model):
    name = models.CharField(max_length=140)
    organisation = models.ForeignKey(Organisation)


class FoobazForm(forms.ModelForm):
    class Meta:
        model = Foobaz
        fields = ('name')


class FoobazCreate(CreateView):
    form_class = FoobazForm

    @login_required
    def dispatch(self, *args, **kwargs):
        return super(FoobazCreate, self).dispatch(*args, **kwargs)

我要做的是从 URL 中获取组织 ID:

/organisation/1/foobaz/create/

并将其添加回创建的对象。我意识到我可以在 CreateView.form_valid() 中执行此操作,但据我了解,这完全没有经过验证。

我已尝试将其添加到 get_form_kwargs() 但这并不指望组织 kwarg,因为它不在包含的字段中。

理想情况下,我想做的是将它添加到表单的实例中以与其余部分一起验证它 - 确保它是一个有效的组织,并且相关用户具有添加新 foobaz 的正确权限给它。

如果这是最好的方法,我很乐意发表自己的看法,但我可能只是错过了一个技巧。

谢谢!

【问题讨论】:

    标签: django django-forms django-generic-views


    【解决方案1】:

    我认为最好包含 organisation 字段并将其定义为隐藏和只读,这样 django 将为您验证它。

    然后您可以像这样覆盖get_queryset 方法:

    def get_queryset(self):
        return Foobaz.objects.filter(
            organisation__id=self.kwargs['organisation_id'])
    

    organisation_id 是 url 模式中的关键字。

    【讨论】:

      【解决方案2】:

      您可以覆盖 View 的 get_kwargs() 方法和 Form 的 save() 方法。在get_kwargs() 中,我将organization_id“注入”到表单的初始数据中,在save() 中,我使用提供的初始数据检索缺失的信息:

      在 urls.py 中:

      urlpatterns('',
          #... Capture the organization_id
          url(r'^/organisation/(?P<organization_id>\d+)/foobaz/create/',
              FoobazCreate.as_view()),
          #...
      )
      

      在views.py中:

      class FoobazCreate(CreateView):
          # Override get_kwargs() so you can pass
          # extra info to the form (via 'initial')
          # ...(all your other code remains the same)
          def get_form_kwargs(self):
              # get CreateView kwargs
              kw = super(CreateComment, self).get_form_kwargs()
              # Add any kwargs you need:
              kw['initial']['organiztion_id'] = self.kwargs['organization_id']
              # Or, altenatively, pass any View kwarg to the Form:
              # kw['initial'].update(self.kwargs)
              return kw
      

      在forms.py中:

      class FoobazForm(forms.ModelForm):
          # Override save() so that you can add any
          # missing field in the form to the model
          # ...(Idem)
          def save(self, commit=True):
              org_id = self.initial['organization_id']
              self.instance.organization = Organization.objects.get(pk=org_id)
              return super(FoobazForm, self).save(commit=commit)
      

      【讨论】:

        猜你喜欢
        • 2017-03-21
        • 2017-08-16
        • 2017-05-04
        • 2011-10-17
        • 2020-02-18
        • 2014-08-19
        • 2017-07-11
        • 2010-12-10
        • 1970-01-01
        相关资源
        最近更新 更多