gpt4 book ai didi

python - Django UpdateView,获取当前正在编辑的对象id?

转载 作者:太空狗 更新时间:2023-10-30 02:37:55 24 4
gpt4 key购买 nike

我正在尝试获取正在编辑的当前记录的 ID,但目前为止失败了。我的观点如下:

View .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

最佳答案

View 的对象属性在 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 方法中可用,因为它们发生在 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

关于python - Django UpdateView,获取当前正在编辑的对象id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48664895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com