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

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

Published 15. jun 2018 12:12 by Stein Ove Helset

In the seventh part of this Django tutorial series we're making it possible to view a feed.

We've come a long way in building our twitter clone. But an important part of this clone is to view other users profiles and the public feed. We'll start with the feed now and make it possible to link to other users profiles.

Create a new file called feed.html inside the templates folder and write the following code.

{% extends 'templates/base.html' %}

{% block main %}
<div class="row">
  <div class="col-12">

    {% for djeet in djeets %}
      <div class="card" style="margin-bottom: 20px;">
        <div class="card-body">
          <h5 class="card-title"><a href="/{{ djeet.user.username }}/">@{{ djeet.user.username }}</a></h5>
          <p class="card-text"><b>{{ djeet.created_at }}</b> - {{ djeet.body }}</p>
    {% endfor %}
{% endblock %}

As you can see it's very similar to your own profile page, but it does not have the sidebar.

Next we need to create the view that will get this data from the database. Open up djeet/ in your editor and write the following code.

from django.shortcuts import render

from .models import Djeet

def feed(request):
  userids = []
  for id in request.user.djeeterprofile.follows.all():

  djeets = Djeet.objects.filter(user_id__in=userids)[0:25]

  return render(request, 'feed.html', {'djeets': djeets})

Not very much code. We import our Djeet model and create the feed view. We get all objects from the database but limits the results to 25 djeets. Next we'll just render the template with the djeets.

One last thing we need to do is to change the djitter/ file.

from django.urls import path

from djeet.views import feed # Add this line
from djeeterprofile.views import frontpage, signout, profile

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

And that's all. You can now got to /feed on your site and you should see the last 25 djeets that has been posted to Djitter from users you follow.

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

Buy me a coffee

Buy me a coffeeBuy me a coffee

Share this post


Add comment