Reverse for 'profile' with arguments '(None,)' not found. 1 pattern(s) tried: ['profile/(?P<user_id>[0-9]+)\\Z']

I’m getting the above error and I’ve tweaked my code based on answers I saw online but still getting the same error

VIEWS.PY
`

def profile(request, user_id):
    profile_user = User.objects.get(pk = user_id)
    # user_profile = Profile.objects.get(user=user_object)
    profile_post = NewTweet.objects.filter(user = user_id)
    post_count = len(profile_post)
    follower = request.user.id
    user = user_id

    if Followers.objects.filter(follower=follower, user=user).first():
        button_text = "Unfollow"
    else:
        button_text = "Follow"

    context = {
        "profile_user": profile_user,
        "post_count": post_count,
        "profile_post": profile_post,
        "button_text": button_text,
    }
    return render(request, "network/profile.html", context)

`

URL.PY

    path("profile/<int:user_id>", views.profile, name="profile"),

LAYOUT.HTML
`

                                <li class="nav-item">
                                    <a class="nav-link" href="{% url 'profile' user.id %}">
                                        <img src= {% static 'network/images/profile.svg' %} alt="Profile" class="left-sidebar-menu-icon">
                                        Profile
                                    </a>
                                    
                                    <img src= {% static 'network/images/profile.svg' %} alt="Profile" class="left-sidebar-menu-icon">
                                        Profile
                                </li>

`

MODELS.PY


class Profile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    id_user = models.IntegerField()
    bio = models.TextField(blank=True)

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

class Followers(models.Model):
    follower = models.CharField(max_length=100)
    user = models.CharField(max_length=100)
    # follower = models.ForeignKey('User', on_delete=models.CASCADE, related_name='targets')
    # target = models.ForeignKey('User', on_delete=models.CASCADE, related_name='followers')

    def __str__(self):
        return self.user

In Layout.html, I try ‘{{ user.id }}’ to see what is reflecting and it shows ‘None’.

I also adjusted this as adviced in a different thread but same error message

<a class="nav-link" href="{% url 'profile' user_id=user.id %}">

I expect that it would show me a button text of ‘Follow’ or 'Unfollow depending on if the user is currently following the current user

Please advise

This is happening, because this is your context

There’s no user key in the context.

1 Like

Hello,

I passed the user in here

profile_user = User.objects.get(pk = user_id)

context = {
    "profile_user": profile_user,

Or am I to include the user_id in the context like this

context = {
    "profile_user": profile_user,
    "user_id": user_id,

You passed profile_user not user, your template has access to the context you gave it.

ok, I think what you meant is to pass in this “user = user_id” into the context

context = {
“profile_user”: profile_user,
“user”: user}

But I am still getting ‘None’

Further to lean’s comments, try this in your template?

<a href="{% url 'profile' user_id=user.id %}"></a>

or

<a href="{% url 'profile' user_id=profile_user.id %}"></a>

(depending on the name of the context’s “user”.

I suspect this is a kwargs versus args case… ?

I receive this errror - Reverse for ‘profile’ with keyword arguments ‘{‘user_id’: None}’ not found. 1 pattern(s) tried: [‘profile/(?P<user_id>[0-9]+)\Z’]

This error shows - Reverse for ‘profile’ with keyword arguments ‘{‘user_id’: ‘’}’ not found. 1 pattern(s) tried: [‘profile/(?P<user_id>[0-9]+)\Z’]

In the traceback, I see on the last line a reference to my index view but I have nothing there related to id, please see below;

NoReverseMatch at /
Reverse for 'profile' with keyword arguments '{'user_id': None}' not found. 1 pattern(s) tried: ['profile/(?P<user_id>[0-9]+)\\Z']
Request Method:	GET
Request URL:	http://127.0.0.1:8000/
Django Version:	4.0.2
Exception Type:	NoReverseMatch
Exception Value:	
Reverse for 'profile' with keyword arguments '{'user_id': None}' not found. 1 pattern(s) tried: ['profile/(?P<user_id>[0-9]+)\\Z']

Traceback Switch to copy-and-paste view
C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py, line 47, in inner
                response = get_response(request) …
Local vars
C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response
                response = wrapped_callback(request, *callback_args, **callback_kwargs) …
Local vars
C:\Users\USER\Desktop\CS50\project4\network\views.py, line 17, in index
    return render(request, "network/index.html", context) 

This is the views for my INDEX

def index(request):
    all_post = NewTweet.objects.all()
    context = {
        "all_post": all_post,
    }
    return render(request, "network/index.html", context)
type or paste code here

What if you pass the argument to the url function positionally?

I also changed the id to pk since not all models may have the id field (The ones who defines a field with primary_key=True).
<a href="{% url 'profile' profile_user.pk %}"></a>

Reverse for ‘profile’ with arguments ‘(’‘,)’ not found. 1 pattern(s) tried: [‘profile/(?P<user_id>[0-9]+)\Z’]

I’m thinking of changing my user_id to pk in my views, url and layout.html

Could you please explain what you meant here?

When django renders the template, it will use the context you provided, and some other global variables. It does not have any access to others variables that we’re not provided in the context.
So in your templates you we’re using an user variable, but that variable was not defined in the context, so django won’t be able to use that.

The name of the argument on the views does not to be changed because of the appointment i did. The point of using some_object.pk instead of some_object.id is because not all objects may have the id field.

def profile(request, user_id):
    profile_user = User.objects.get(pk = user_id)
    # user_profile = Profile.objects.get(user=user_object)
    profile_post = NewTweet.objects.filter(user = user_id)
    post_count = len(profile_post)
    follower = request.user.id
    user = user_id

    if Followers.objects.filter(follower=follower, user=user).first():
        button_text = "Unfollow"
    else:
        button_text = "Follow"

    context = {
        "profile_user": profile_user,
        "post_count": post_count,
        "profile_post": profile_post,
        "button_text": button_text,
        "user": user,
    }

    return render(request, "network/profile.html", context)

[quote="leandrodesouzadev, post:10, topic:17953"]
The name of the argument on the views does not to be changed because of the appointment i did. The point of using `some_object.pk` instead of `some_object.id` is because not all objects may have the `id` field.
[/quote]

I tried “profile_user.id” and “profile_user.pk” - Reverse for ‘profile’ with arguments ‘(’‘,)’ not found
But if I use this “user.id” - Reverse for ‘profile’ with arguments ‘(None,)’ not found.

Which URL are you on your browser when you see this error?

http://127.0.0.1:8000/ and http://127.0.0.1:8000/profile/4

Alright, let’s start with this view.
This is the view that’s rendered when you go to “/”

Can you show the template for this view? Note that in this view you don’t have an user, profile_user on your context!

This is the index.html

{% extends "network/layout.html" %}

{% block body %}
                <div class="col-5">
                    <div class="main-page-header mt-3 sticky-top">Home</div>
                    <div class="main-page-input">
                        <!-- <form class="d-flex flex-column"> -->
                            <div class="row">
                                <div class="col-2 main-page-header-profile-picture">
                                    <img src="https://i.pinimg.com/originals/a6/58/32/a65832155622ac173337874f02b218fb.png" class="main-page-header-profile-picture" alt="profile-picture"/>
                                </div>
                                <div class="col-10">
                                    <div class="main-page-input-box">
                                        <form method="POST" action="new_post">
                                        {% csrf_token %}
                                            {{ form.as_p }}
                                            <div>
                                                <textarea name="caption" id="tweet-box" class="form-control main-page-tweet-box text-wrap" cols="30" rows="10" placeholder="What's happening">
                                                </textarea>
                                                    <!-- <input type="text" class="form-control main-page-tweet-box text-wrap" id="exampleFormControlInput1" placeholder="What's happening"> -->
                                            </div>
                                                <div class="main-page-input-privacy pb-2 mt-3">
                                                    <i class="fas fa-globe-americas main-page-input-privacy-icon"></i>
                                                    <span class="ain-page-input-privacy-text ml-2">Everyone can reply</span>
                                                </div>
                                            </div>
                                            <div class="main-page-input-icons mt-3">
                                                <ul class="main-page-input-icons-ul">
                                                    <li><i class="fa-solid fa-image"></i></li>
                                                    <li><i class="fa-solid fa-square-poll-horizontal"></i></li>
                                                    <li><i class="fa-solid fa-face-grin"></i></li>
                                                    <li><i class="fa-regular fa-calendar"></i></li>
                                                    <li><i class="fa-solid fa-location-dot"></i></li>
                                                </ul>
                                                <button type="submit" class="btn btn-primary rounded-pill px-4 main-page-tweet-button"><strong>Tweet</strong></button>
                                            </div>
                                        </form>
                                    
                                </div>
                            </div>
                    <!-- </form> -->
                    </div>
                    <div class="tweet-feed">
                        {% for post in all_post%}
                            <div class="tweet">
                                <img src="http://placeimg.com/140/140/people" alt="author profile picture" class="tweet-author-image"/>
                                <div class="tweet-feed-content">
                                    <div class="tweet-header">
                                        <a href="#" class="tweet-author-username">{{post.user}}</a>
                                        <div class="tweet-author-handle">@ {{post.user}</div>
                                        <div class="tweet-dot">.</div>
                                        <div class="tweeted-time">{{post.created_at}}</div>
                                    </div>
                                    <div class="tweet-content">
                                        <div class="tweet-created-content">{{post.caption}}</div>
                                    </div>
                                    <div class="engagement-icons">
                                        <ul class="engagement-icons-ul mt-1">
                                            <li><i class="fa-regular fa-comment"></i></li>
                                            <li><i class="fa-solid fa-retweet"></i></li>
                                            <li><i class="fa-regular fa-heart"></i></li>
                                            <li><i class="fa-solid fa-arrow-up-from-bracket"></i></li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        {% endfor %}
                            <div class="tweet">
                                <img src="http://placeimg.com/140/140/people" alt="author profile picture" class="tweet-author-image"/>
                                <div class="tweet-feed-content">
                                    <div class="tweet-header">
                                        <a href="#" class="tweet-author-username">Nick Huber</a>
                                        <div class="tweet-author-handle">@sweatystartup</div>
                                        <div class="tweet-dot">.</div>
                                        <div class="tweeted-time">8h</div>
                                    </div>
                                    <div class="tweet-content">
                                        <div class="tweet-created-content">It is a wonderful day</div>
                                    </div>
                                    <div class="engagement-icons">
                                        <ul class="engagement-icons-ul mt-1">
                                            <li><i class="fa-regular fa-comment"></i></li>
                                            <li><i class="fa-solid fa-retweet"></i></li>
                                            <li><i class="fa-regular fa-heart"></i></li>
                                            <li><i class="fa-solid fa-arrow-up-from-bracket"></i></li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                            <div class="tweet">
                                <img src="http://placeimg.com/140/140/animals" alt="author profile picture" class="tweet-author-image"/>
                                <div class="tweet-feed-content">
                                    <div class="tweet-header">
                                        <a href="#" class="tweet-author-username">Randall</a>
                                        <div class="tweet-author-handle">@RandallKanna</div>
                                        <div class="tweeted-time"><span class="tweet-dot">.</span> 18h</div>
                                    </div>
                                    <div class="tweet-content">
                                        <div class="tweet-created-content">Hey friends</div>
                                        <img src="http://placeimg.com/300/300/tech" class="tweeted-image" alt="tweeter feed"/>
                                    </div>    
                                    <div class="engagement-icons">
                                        <ul class="engagement-icons-ul m-1">
                                            <li><i class="fa-regular fa-comment"></i></li>
                                            <li><i class="fa-solid fa-retweet"></i></li>
                                            <li><i class="fa-regular fa-heart"></i></li>
                                            <li><i class="fa-solid fa-arrow-up-from-bracket"></i></li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
{% endblock %}

For me to add this, i would have to add

def index(request, user_id):

But the index should show every post available without needing a user id

You’re already passing the id to the context, not the user object.

Therefore, this:

Should actually be this:
<a class="nav-link" href="{% url 'profile' user %}">

This gave this error when I changed it - Reverse for ‘profile’ with arguments ‘(<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x000001971F7AE380>>,)’ not found. 1 pattern(s) tried: [‘profile/(?P<user_id>[0-9]+)\Z’]

Ok, I must have missed something in one of the edits along the way - but at least we have an answer to the original issue.

Notice that it’s making a reference to AnonymousUser. This means that the person issuing the request for this page is not logged in. Therefore, there’s no id to retrieve and therefore would not have a profile page to link to.

I logged in via the Admin, its now showing the user name - Reverse for ‘profile’ with arguments ‘(<SimpleLazyObject: <User: Noble>>,)’ not found. 1 pattern(s) tried: [‘profile/(?P<user_id>[0-9]+)\Z’]

And showing 4 as {{ user.id }} so the ID is now seen.

`
<a class="nav-link" href="{% url 'profile' user %}">
    <img src= {% static 'network/images/profile.svg' %} alt="Profile" class="left-sidebar-menu-icon">
     Profile
<
/a>

It works (shows as expected) on the url path (http://127.0.0.1:8000/profile/4) but I don’t know why when I go back to the index path (http://127.0.0.1:8000) I get this error

Reverse for ‘profile’ with arguments ‘(<SimpleLazyObject: <User: Noble>>,)’ not found. 1 pattern(s) tried: [‘profile/(?P<user_id>[0-9]+)\Z’]

Since you are passing the user object into the context (I missed something along the way in the thread of messages), you would use user.id in the template line below and not user.