[Django]-Global name 'pk' is not defined django

5👍

Of course, the error cannot be anymore obvious, in your function delete_country you don’t have pk as a parameter, but you did:

def delete_country(request, world_pk, country_pk):
    world = get_object_or_404(World, pk=pk)

Maybe you try to do world = get_object_or_404(World, pk=world_pk)

Edit::

You are using the wrong way to return redirect. redirect is expecting a url that it can redirect to, but you are giving it a function name. If your my_world function is also have a url name as my_world, you should use reverse to derive the url from that:

from django.core.urlresolvers import reverse

def delete_country(request, world_pk, country_pk):
    world = get_object_or_404(World, pk=pk)
    country = get_object_or_404(Country, pk=pk)
    world.country.remove(country)
    return redirect(reverse('my_world', args=(world.pk,)))

Check out the redirect documentation and reverse documentation. It might/might not make sense immediately, but if they don’t, try to slow down and read/search for some examples as well.

2👍

There is no variable named pk that’s why it is throwing the error. Those methods are called in url. Only world_pk and and country_pk are defined.

Use world = get_object_or_404(World, pk=world_pk)

or world = get_object_or_404(World, pk=country_pk)

Leave a comment