Djitter - how to build a twitter clone using Django 2.0 - Part five

Djitter - how to build a twitter clone using Django 2.0 - Part five

Published 11. jun 2018 11:41 by Stein Ove Helset

Today we're going to create the profile. We need to add some more files and set up the views and templates.

This will be s short part, but we will finally be able to see our profile now. The first this we do is to add the function that will get the user from the database and render the template.

Creating the files for the profile

Inside the djeeterprofile/views.py add the following view to the bottom.


def profile(request, username):
  user = User.objects.get(username=username)
  return render(request, 'profile.html', {'user': user})

Open profile.html in your editor and write the following code.


{% extends 'templates/base.html' %}
{% block main %} <div class="row">   <!-- Feed -->   <div class="col-9">     <h3>@{{ user.username }}</h3>     {% if user.djeets.all %}       {% for djeet in user.djeets.all %}         <div class="card" style="margin-bottom: 20px;">           <div class="card-body">             <h5 class="card-title">@{{ djeet.user.username }}</h5>             <p class="card-text"><b>{{ djeet.created_at }}</b> - {{ djeet.body }}</p>           </div>           </div>       {% endfor %}     {% else %}       <p>No djeets yet!</p>     {% endif %}   </div>   <!-- Sidebar -->   <div class="col-3">     <h3>Add djeet</h3>   </div> </div> {% endblock %}

In this template the most crucial thing is the {% for %} loop. The first thing we do is to check if the users has any djeets at all, if not we print a message telling that to the user.

If there are any djeets we use a {% for %} loop to loop through them. user.djeets.all get all the djeets the current users has posted. We print the username and the djeets body.

Setting the urls

We need to change the djitter/urls.py.


from django.urls import path

from djeeterprofile.views import frontpage, signout, profile # Change this, add ", profile" to the end

urlpatterns = [
  path('', frontpage, name='frontpage'),
  path('signout/', signout, name='signout'),
  path('<str:username>/', profile, name='profile'), # Add this line
]

We import the profile view and at the bottom we add a new path to the url schema. <str:username> tells Django that we want a string and it's called username.

If you've got any questions your are more than welcome to leave a comment and I'll answer as soon as possible.

Next part

Share this post

Comments

No comments yet

Add comment