簡體   English   中英

Django UpdateView,獲取當前對象的編輯ID?

[英]Django UpdateView, get the current object being edit id?

我試圖讓當前記錄被編輯的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

視圖的對象屬性在getUpdateView的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM