Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django UpdateView without pk in url

Is it possible eliminate pk from url related to UpdateView?

For example, if I have

url(r'^myobj/update/(?P<pk>\d+)/$', views.UpdateMyObj.as_view(), name="update")

is there any way to write it like

url(r'^myobj/update/$', views.UpdateMyObj.as_view(), name="update")

and then send pk as a parameter in POST or GET request?

like image 669
cansadadeserfeliz Avatar asked Jul 10 '13 02:07

cansadadeserfeliz


2 Answers

Yes it is possible you just need to override the get_object method:

from django.views.generic.edit import UpdateView

class UpdateMyObj(UpdateView):
    # .....

    def get_object(self):
        return MyModel.objects.get(pk=self.request.GET.get('pk')) # or request.POST
like image 192
Aamir Rind Avatar answered Oct 19 '22 15:10

Aamir Rind


Sometimes it works like this

class MyViewUpdate(UpdateView):
    def get_object(self, queryset=None):
        obj = self.model.objects.get(my_id_or_name_of_field=self.kwargs['pk_or_field_name']) # instead of self.request.GET or self.request.POST
        return obj
like image 27
AlexKh Avatar answered Oct 19 '22 13:10

AlexKh