Django UpdateView,如何获取正在编辑对象的ID?

10

我试图获取当前正在编辑的记录的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

使用 get_object().id 代替 object.id - mohammedgqudah
我现在得到了一个错误,名称get_object()未定义。 - AlexW
1个回答

17

BaseUpdateView 在执行 get/post 期间设置视图的对象属性:

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方法中将可用,因为它们在get/post之后发生。所以你可以这样做:

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

我得到了错误信息:“通用详细视图EditSite必须使用对象pk或slug之一来调用。” - AlexW
你的url conf必须包含捕获pk或slug参数,因为这些参数是视图所期望的:如何实现 - CoffeeBasedLifeform
例如 self.get_object - Chalist
有人能帮我吗?我认为这个问题与https://stackoverflow.com/questions/61387712/how-to-createview-updateview-using-foreign-key-in-nested-model有关。 - h_vm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接