2

What I have been trying is to click the post's author(the user that created the post) I want it to redirect me to that user's profile, for example in Instagram when you click the user that is on top of the post-it redirects you to their profile. Every time I do that instead of seeing the post's author profile I see the logged in user profile. I think there is something wrong in the views.py file or in the base.html.

views.py

    def profile(request, pk=None):
        if pk:
            user = get_object_or_404(User, pk=pk)
        else:
            user = request.user
        args = {'user': user}
        return render(request, 'profile.html', args)

    def home(request):
        created_posts = Create.objects.all().order_by("-added_date")
        return render(request, 'base.html', {"created_posts": created_posts})

    def create(request):
        if request.method == 'POST':
            created_date = timezone.now()
            header1 = request.POST['header']
            content1 = request.POST['content']
            user = request.user
            created_obj = Create.objects.create(added_date=created_date, title=header1, content=content1, user=user)
            created_obj.save()
            print('create created')
            return redirect('home')
        else:
            print('create not created')
            return render(request, 'create.html')

models.py

    class Create(models.Model):
        added_date = models.DateTimeField()
        title = models.CharField(max_length=200)
        content = models.CharField(max_length=200)
        user = models.ForeignKey(User, related_name='user', on_delete=models.CASCADE, default=1)

    class Profile(models.Model):
        user = models.OneToOneField(User, on_delete=models.CASCADE)
        image = models.ImageField(default='default.jpg', upload_to='profile_pics')

    def __str__(self):
        return f'{self.user.username} Profile'

urls.py

    urlpatterns = [
        path('', views.home, name='home'),
        path('profile', views.profile, name='profile'),
        path('profile/<int:pk>/', views.profile, name='profile_pk'),
        path('create', views.create, name='create'),
    ]

profile.html (shows user's profile)

    {% extends 'home.html' %}
    {% block body%}
    <div class="content-section">
      <div class="media">
        <img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
        <div class="media-body">
          <h2 class="account-heading">{{ user.username }}</h2>
          <p class="text-secondary">{{ user.email }}</p>
        </div>
      </div>
    </div>
    {% endblock %}

base.html (shows all user's post with the user's username)

    {% extends 'home.html' %}
    {% block body %}
      <ul action="{% url 'create' %}" class="container-sm list-group" style="margin-top: 200px;">
        {% for created_post in created_posts %}
        <li class="list-group-item">{{ created_post.title }}
          <a href="{% url 'profile_pk' pk=user.pk %}">{{ created_post.user }}</a>
          <p>{{ created_post.content }}</p>
          <div class="float-right">
            <form action="delete_create/{{ created_post.id }}/" action="post">
              <button type="submit" class="btn btn-outline-danger btn-sm">Delete</button>
            </form>
          </div>
          <div class="float-right">
            <a href="{% url 'edit' created_post.id %}" class="btn btn-outline-warning btn-sm" style="margin-right: 5px;" role="button">Edit</a>
          </div>
        </li>     
       {% endfor %}            
     </ul>
     {% endblock %}

home.html (navbar that shows the loged in user)

    <body>
<nav class="navbar navbar-expand-md fixed-top navbar-dark" style="background-color: rgba(0, 0, 0, 0.712);">
    <div class="container">
      <a class="navbar-brand" href="/">
        <img src="static/style/images/logowebdev-png.png" alt="logo" style="width: 60px; height: auto;">
      </a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample07" aria-controls="navbarsExample07" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarsExample07">
        <ul class="navbar-nav mr-auto mt-2 mt-lg-0">
          <li class="nav-item">
            <a class="nav-link"  style="margin-left: 30px;" href="/">Home <span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item">
            <a class="nav-link"  style="margin-left: 30px;" href="/profile">profile</a>
          </li>
          <li class="nav-item">
            <a class="nav-link"  style="margin-left: 30px;" href="#">Pricing</a>
          </li>
        </ul>
        <ul class="navbar-nav ml-auto">
          {% if user.is_authenticated %}
          <div class="float-right">
              <li class="nav-item active">
                  <a class="nav-link" href="#">New post</a>
              </li>
          </div>
          <div class="float-right">
            <li class="nav-item active">
              <a class="nav-link" href="">{{ user.username }}</a>
            </li>
          </div>
          <div class="float-right">
            <li class="nav-item">
              <a class="nav-link" href="/logout">Logout</a>
            </li>
          </div>
          {% else %}
          <div class="float-right">
            <li class="nav-item">
              <a class="nav-link" href="/login">Login</a>
            </li>
          </div>
          <div class="float-right">
            <li class="nav-item">
              <a class="nav-link" href="/register">Register</a>
            </li>
          </div>
          {% endif %}
        </ul>
      </div>
    </div>
  </nav>
  {% block body %}

  {% endblock %}
</body>
Juan Martin Zabala
  • 743
  • 2
  • 9
  • 29
  • a simple way to find solution would be to use a debugger to see what value of `pk` you receive in your `views.py`. – Ansuman Apr 26 '20 at 01:09
  • @ansuman how can I use debugger? – Juan Martin Zabala Apr 26 '20 at 01:18
  • insert `import pdb; pdb.set_trace()` where you want to pause execution, check your terminal there should be something like this `-> (Pdb) ` enter `pk`. it should show you what value of pk is received. – Ansuman Apr 26 '20 at 01:22
  • note this is python debugger will work only with python files, where as there are multiple ways to debug, e,g using a IDE : https://stackoverflow.com/questions/1118183/how-to-debug-in-django-the-good-way – Ansuman Apr 26 '20 at 01:24
  • @ansuman When I put pk it gives me this error *** NameError: name 'pk' is not defined – Juan Martin Zabala Apr 26 '20 at 01:42

1 Answers1

2

In your base.html file change

<a href="{% url 'profile_pk' pk=user.pk %}">{{ created_post.user }}</a>

with

<a href="{% url 'profile_pk' pk=created_post.user.pk %}">{{ created_post.user }}</a>

Because, you must pass id of post owner to your view. When you use only user, django detect authenticated user object.

kamilyrb
  • 2,502
  • 3
  • 10
  • 25
  • Hey your code helped me fix my problem but now on the home.html in wich I have a navbar that shows the loged in user username when I click on a username of a post, the username in the navbar also changes but the loged in user is still the one that was loged in at the begining so what can I do to fix that?. If you didn't understand my question let me know. – Juan Martin Zabala Apr 26 '20 at 15:01
  • Sorry, I think I didn't understand corrrectly, can you explain with a sample? – kamilyrb Apr 26 '20 at 18:37
  • sure, lets say that you are on facebook and you are logged in, you can see your profile image at the right top corner of the navbar, when you go to other user's profile you can still see your profile image in the navbar and the user's profile you selected in the body right? – Juan Martin Zabala Apr 26 '20 at 20:28
  • lets say that your profile image on my navbar changes to the user that you are seeing in the body, but take in consideration that your user is still loged in meaning that what you are seeing in the navbar when you are checking other user's profile is the other user username – Juan Martin Zabala Apr 26 '20 at 20:32
  • 1
    The goal here is that in the navbar shows only the user that is loged in not the user that it is beeing checked. – Juan Martin Zabala Apr 26 '20 at 20:34
  • Ok, I understood now, thanks for explanation. Actually your problem is very basic, I hope I can explain you basically. In your view, you can pass your `profile.html` a variable which named `user`. But it is a special name for django. Django detect it as authenticated user. With this way you can show authenticated user with `{{user.userrname}}` like. But in your view you dominate `user` variable with post owner. Please use another variable like `post_owner` in `profile` view. – kamilyrb Apr 26 '20 at 21:04
  • Thank you! I really appreciate your help. I changed the variables as you said and profile.html user.username to post_owner.html and worked. – Juan Martin Zabala Apr 26 '20 at 22:13