Django UpdateView,获取当前对象的编辑ID?

时间:2018-02-07 13:19:56

标签: python django

我正在尝试将当前记录编辑为id,但到目前为止还没有失败。我的观点如下:

views.py

class EditSite(UpdateView):
    model = SiteData
    form_class = SiteForm
    template_name = "sites/site_form.html"

    @method_decorator(user_passes_test(lambda u: u.has_perm('config.edit_subnet')))
    def dispatch(self, *args, **kwargs):
        self.site_id = self.object.pk
        return super(EditSite, self).dispatch(*args, **kwargs)

    def get_success_url(self, **kwargs):         
            return reverse_lazy("sites:site_overview", args=(self.site_id,))

    def get_form_kwargs(self, *args, **kwargs):
        kwargs = super().get_form_kwargs()
        return kwargs

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['SiteID']=self.site_id
        context['SiteName']=self.location
        context['FormType']='Edit'

        return context

和错误:

File "/itapp/itapp/sites/views.py" in dispatch
  890.         self.site_id = self.object.pk

Exception Type: AttributeError at /sites/site/edit/7
Exception Value: 'EditSite' object has no attribute 'object'

我试过了:

self.object.pk
object.pk
self.pk

1 个答案:

答案 0 :(得分:4)

视图的对象属性在获取/发布期间由BaseUpdateView设置:

def get(self, request, *args, **kwargs):
    self.object = self.get_object()
    return super(BaseUpdateView, self).get(request, *args, **kwargs)

def post(self, request, *args, **kwargs):
    self.object = self.get_object()
    return super(BaseUpdateView, self).post(request, *args, **kwargs)

因此dispatch方法尚未提供。 但是它将在get_success_urlget_context_data方法中提供,因为这些方法在获取/发布后发生。所以你可以这样做:

from django.contrib.auth.mixins import PermissionRequiredMixin

class EditSite(PermissionRequiredMixin, UpdateView):
    model = SiteData
    form_class = SiteForm
    template_name = "sites/site_form.html"
    permission_required = 'config.edit_subnet'

    def get_success_url(self, **kwargs):         
        return reverse_lazy("sites:site_overview", args=(self.object.site_id,))

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['SiteID']=self.object.site_id
        context['SiteName']=self.location # <--- where does self.location come from? self.object.location perhaps?
        context['FormType']='Edit'
        return context