Django "get() got an unexpected keyword argument 'pk'" error

Django

Django Problem Overview


I am trying to redirect to a page I intend to implement as an object's homepage after creation of one.

Below is corresponding part of my views.py

            new_station_object.save()
            return HttpResponseRedirect(reverse("home_station", 
                                                kwargs={'pk':   new_station_object.id}
            ))
        
class StationHome(View):
    def get(self, request):
        return HttpResponse("Created :)")

and corresponding part of my urls.py;

    url(r'^station/(?P<pk>\d+)$', StationHome.as_view(),    name='home_station'),

But I get the said error;

TypeError at /station/2
get() got an unexpected keyword argument 'pk'

Someone please help me out.

Django Solutions


Solution 1 - Django

The function is getting one argument more than it is supposed to. Change it to:

def get(self, request, pk):

The value of pk will be equal to the pattern that has been matched, and since you've specified that it's going to be a number, the type of pk will be int.

Solution 2 - Django

add the kwargs into the method definition:

def get(self, request, *args, **kwargs):
    return HttpResponse("Created :)")

Solution 3 - Django

Check that if your views.fun_name is same as the function name in views

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAfzal S.H.View Question on Stackoverflow
Solution 1 - DjangorohithprView Answer on Stackoverflow
Solution 2 - Djangowobbily_colView Answer on Stackoverflow
Solution 3 - DjangoShreyView Answer on Stackoverflow