Attempting to read pk from url in django, but getting error NoReverseMatch at /

Question:

I am attempting to insert a link into my navbar (header.html – which is included in my base.html) which leads to the users profile. In order to provide the profile of the user who is currently logged in, I am attempting to use a primary key via the url. However, I am receiving the following error message: Reverse for ‘url’ with keyword arguments ‘{‘pk’: ”}’ not found. 1 pattern(s) tried: [‘profiles/show/(?P[0-9]+)/Z’]

I have a Profile model defined (shown below) with a OneToOne Relationship to my User model.

I am wondering if I am trying to parse in the wrong pk reference in my header.html file. If so I think the issue will be on line 17 "Show Profile", but may also be in my view file? Something is definitely going wrong with my primary key, but am new to Django and cant work out what it is!

Model:

class Profile(models.Model): # Get access to create profile by default
    MALE = 'M'
    FEMALE = 'F'
    OTHER = 'O'
    UNSPECIFIED = "U"
    GENDER_CHOICES = [
        (MALE, 'Male'),
        (FEMALE, 'Female'), 
        (OTHER, 'Other'),
        (UNSPECIFIED, 'Prefer not to say'),
    ]

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    phone_number = models.CharField(verbose_name='Mobile Phone Number', max_length=20)
    bio = models.TextField(verbose_name='Bio', max_length=500, blank=True, null=True)
    date_of_birth = models.DateField(verbose_name='Date of Birth', blank=True, null=True)
    first_name = models.CharField(verbose_name='First Name', max_length=255, blank=True, null=True)
    surname = models.CharField(verbose_name='Surname', max_length=255, blank=True, null=True)
    gender = models.CharField(verbose_name='Gender', max_length=255, choices=GENDER_CHOICES, blank=True, null=True)
    emergency_contact_name = models.CharField(verbose_name='Emergency Contact Name', max_length=255, blank=True, null=True)
    emergency_contact_number = models.CharField(verbose_name='Emergency Contact Number', max_length=20, blank=True, null=True)
    business = models.ForeignKey(BusinessProfile, null=True, blank=True, on_delete=models.SET_NULL) # This may need to change.
    creation_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.user)

View:

class ShowProfileView(DetailView):
    model = Profile
    template_name = 'profiles/user_profile.html'

    def get_context_data(self, *args, **kwargs):
        context = super(ShowProfileView, self).get_context_data(*args, **kwargs)
        page_user = get_object_or_404(Profile, id=self.kwargs['pk'])
        context["page_user"] = page_user
        return context


urls.py:


app_name='profiles'
urlpatterns=[
    path('create/', CreateProfileView.as_view(), name='create_profile'),
    path('show/<int:pk>/', ShowProfileView.as_view(), name='show_profile'),
]

header.html:

<!DOCTYPE html>
<html lang="en">
    <head>
    <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    </head>
    <div class="header" style="background-color:grey;">
        {% block logo %}
        <a href='{% url "home" %}' class="logo" style="text-align:left;font-size:30px;">.</a>
        {% endblock %}
        {% if request.user.is_authenticated %}
        <div class="header-right" style="text-align:right;" >
            {{ user }}
            <a href='{% url "accounts:home" %}'>Account</a>
            <a href='{% url "profiles:create_profile" %}'>Create Profile</a>
            <a href='{% url "profiles:show_profile" pk=profile.id %}'>Show Profile</a>
            <a href='{% url "accounts:logout" %}'>Logout</a>
        </div>
        {% else %}
        <div class="header-right" style="text-align:right;" >
            <a href='{% url "accounts:login" %}'>Log in</a>
            <a href='{% url "accounts:register" %}'>Create Account</a>
        </div>
        {% endif %}
    </div>
</html>

I have also tried calling in my html with pk=object.id as well as a few other things.

Please let me know if any further info needed. Thanks very much in advance!

Tried to get instance of profile model for current logged in user. Received "NoReverseMatch at /" error.

Asked By: nlewis99

||

Answers:

If you add the header to all items, then that means that all views should pass profile to the context, not only the DetailView.

It might also be the case that there is no profile, for example if the user is logged out. You thus should check if the profile is indeed valid. You can however obtain the profile for request.user or user, so:

<a href='{% url "profiles:show_profile" pk=user.profile.id %}'>Show Profile</a>
Answered By: Willem Van Onsem