Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django UpdateView, get the current object being edit id?

I am trying to get the current record being edited's id, but am failing thus far. my view is as per the below:

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

and the error:

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'

ive tried:

self.object.pk
object.pk
self.pk
like image 473
AlexW Avatar asked Feb 07 '18 13:02

AlexW


1 Answers

The view's object attribute is set during get/post by 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)

So it is not yet available in the dispatch method. But it will be available in the get_success_url and get_context_data methods as those happen after get/post. So you could do:

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
like image 64
CoffeeBasedLifeform Avatar answered Nov 17 '22 11:11

CoffeeBasedLifeform