user9629702
user9629702

Reputation: 65

How to pass pk argument from url into view in Django?

I am having issues passing the pk from the URL into my view. I had this working before when all the URL's paths were situated in the same file but due to poor structure of files I had to re-organise things. I cannot figure out why this is no longer working. Details do exist as I've hard-coded the PK in the view and everything was displayed. It is probably something simple but would really appreciate some help.

URL - http://127.0.0.1:8000/club_home/1/

index.html

    <h2>Our Clubs</h2>
    {% for club in all_clubs %}
    <a href="{% url 'clubs:club_home_with_pk' pk=club.pk %}">
        <li>{{ club.club_name }}</li>
    </a>
  {% endfor %}

urls.py:

urlpatterns = [
url(r'^', views.club_home, name='club_home'),
url(r'^(?P<pk>\d+)/', views.club_home, name='club_home_with_pk'),
url(r'^edit/$', views.edit_club, name='edit_club'),

]

views.py:

def club_home(request, pk=None):
if pk:
    club = ClubInfo.objects.filter(pk=pk)
elif request.user.is_authenticated:
    club = ClubInfo.objects.filter(user=request.user)
# photo = model.club_logo.ImageField(storage=profile_pics)
args = {'club': club,
        }
return render(request, 'club_home_page.html', args)

club_home_page.html

     <h3>Club Details</h3>
<p>
    {% csrf_token %}
    {% for info in club %}
<li>{{ info.club_name }}</li>
<li><img src="{{ info.club_logo }}" height="50px" width="50px"/></li>
<li>{{ info.club_address1 }}</li>
<li>{{ info.club_address2 }}</li>
<li>{{ info.club_address3 }}</li>
<li>{{ info.club_town }}</li>
<li>{{ info.club_county }}</li>
<li>{{ info.club_country }}</li>
</p>

View for player registration:

class RegisterPlayer(APIView):
renderer_classes = [TemplateHTMLRenderer]
template_name = 'player_registration.html'

def get(self, request):
    serializer = PlayerRegistrationSerializer()
    return Response({'serializer': serializer,
                     })

def post(self, request):
    serializer = PlayerRegistrationSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(template_name='player_registration_complete.html')

Upvotes: 2

Views: 13106

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

The problem is in your URL patterns. Specifically, your "club_home" pattern is too generic; it matches everything, including the case when a PK is provided.

You should always terminate your patterns if you are using the url() form:

urlpatterns = [
    url(r'^$', views.club_home, name='club_home'),
    url(r'^(?P<pk>\d+)/$', views.club_home, name='club_home_with_pk'),
    url(r'^edit/$', views.edit_club, name='edit_club'),
]

If you are using a recent version of Django, you could use path instead:

urlpatterns = [
    path('', views.club_home, name='club_home'),
    path('<int:pk>/', views.club_home, name='club_home_with_pk'),
    path('edit/', views.edit_club, name='edit_club'),
]

Upvotes: 5

Related Questions