Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
default=True is not reflected in django admin BooleanField
I have added a field this_field in django models but in admin its False. My model. this_field = models.BooleanField(default=True) My migration: migrations.AlterField( model_name='a', name='this_field', field=models.BooleanField(default=True), ), Default value should be true of the field but its not working default is shown as false. When I add a new field that_field as models.BooleanField(default=True) its default is true but this_field is an old field and its its values is not being reflected in django admin . -
How to catch CSRF errors in Django
How would I go about catching CSRF errors in Django? For example, I would like to catch this: Forbidden (CSRF token missing or incorrect.): /asdjasdjk/asdhriheiof I want to do this because I want to ban people who tamper with CSRF codes for my particular case. Any help is appreciated. -
How to Upload image or select from sample images in Django?
I am working on a website where I want to give an option to the customer to Upload the image by him/her or he/she can select images from given samples. Can you help me, how can I provide these options? And also explain to me how should I create a pop-up to display sample images. I am a newbie and working on Django 2.2 with MySQL. -
python requests json api problem. it only returns 1000 enteries
i want to pull this api data https://data.ct.gov/resource/6tja-6vdt.json. There is 19k entries in the website but when I pull through requests.get it returns only 1000. HOw to get all data at once? how to use limits and offsets and loops to get all at once -
ValueError at /save_data/
ValueError at /save_data/ Cannot assign "'IT'": "ProfileModel.itype" must be a "IndustriesModel" instance this is the error i am getting when saving the data to profilemodel could this is my models: def save_data(request): ed=request.POST.get("p1") ph=request.POST.get("p2") re=request.POST.get("p3") ty=request.POST.get("p4") ProfileModel(education=ed,photo=ph,resume=re,itype=ty).save() return render(request,"process_templates/login.html") and the views.py : ''' class IndustriesModel(models.Model): ino=models.AutoField(primary_key=True) type=models.CharField(max_length=100) def __str__(self): return self.type class ProfileModel(models.Model): pno=models.AutoField(primary_key=True) person=models.OneToOneField(RegistrationModel,on_delete=models.CASCADE) education=models.CharField(max_length=100) photo=models.ImageField(upload_to='user_images/') resume=models.FileField(upload_to='user_resumes/') itype=models.OneToOneField(IndustriesModel,on_delete=models.CASCADE) ''' could anyone help me solving the issue i am using html to not the forms. -
how to create related object while uploading csv in django
I am trying to create a foreignkey object when uploading csv as follows, def user_upload(request): data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): if len(column) > 9: try: users = User( username=column[0], first_name=column[1], last_name=column[2], email=column[3], add_1=column[4], add_2=column[5], suburb=column[6], state=column[7], postcode=column[8], country=column[9], ) users.set_password('password') users.save() pricing = Pricing.objects.get(name='Free Trial') for user in users: subscription = Subscription.objects.create(user=user, pricing=pricing) stripe_customer = stripe.Customer.create( email=user.email ) stripe_subscription = stripe.Subscription.create( customer=stripe_customer["id"], items=[{'price': 'price_1HkPcpOS8'}], trial_period_days=7 ) subscription.status = stripe_subscription["status"] subscription.stripe_subscription_id = stripe_subscription["id"] subscription.save() except IntegrityError as e: return render_to_response('snippets/message.html') context = {} return render(request, template, context) User part is working but the related object Subscription is not getting updated as it throws error User is not iterable, how I can upload to related tables, thanks -
Django For Loop Creating Empty Divs
I am trying to loop through a list of items that are associated with a list of orders within my template and the loop is generating empty rows in my html because its looping through ALL OrderItems in my database. div class="container"> {% for order in orders %} <div class="col-lg-6"> <h3>{{order.topic}}, {{order.entry}} - Order #{{order.id}}</h3> <div class="box-element"> <div class="cart-row"> <div style="flex: 2;"></div> <div style="flex: 2;"><strong>Item</strong></div> <div style="flex: 1;"><strong>Price</strong></div> <div style="flex: 1;"><strong>Quantity</strong></div> <div style="flex: 1;"><strong>Total</strong></div> </div> {% for item in items %} <div class="cart-row"> {% if item.order.id == order.id %} <div style="flex: 2"><img class="row-image" src="{{ item.menu_item.image.url }}"></div> <div style="flex: 2">{{item.menu_item.title}}</div> <div style="flex: 1">{{item.menu_item.price}}</div> <div style="flex: 1"> <p class="quantity">{{order.get_cart_items}}</p> </div> <div style="flex: 1">${{order.get_cart_total}}</div> {% else %} {% endif %} </div> {% empty %} {% endfor %} </div> </div> {% empty %} <p>No Orders exist</p> {% endfor %} </div> I think the problem is that the items Queryset (shown in my view below) is returning all Orderitems in my DB and then i am looping through them in the template. How can I perform this loop in my view so i don't run into this problem (and future performance bottleneck) in my template? def orders(request): """View open orders for a customer""" if request.user.is_authenticated: … -
count total object in foreign key - drf
i want to count comments for every single Post in models.py: class Post(models.Model): body = models.TextField(max_length=10000) date = models.DateTimeField(auto_now_add=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) liked_by = models.ManyToManyField(User, blank=True, related_name='liked_by') class Meta: ordering = ['-date'] class Comment(models.Model): body = models.TextField(max_length=1000) date = models.DateTimeField(auto_now_add=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) class Meta: ordering = ['-date'] in serializers.py: class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = '__all__' class PostSerializer(serializers.ModelSerializer): #comments = CommentSerializer() user = UserSerializers() total_likes = serializers.SerializerMethodField() liked_by = SimpleUserSerializer(many=True, read_only=True) total_comments = serializers.SerializerMethodField() class Meta: model = Post fields = ('body','date','user', 'total_likes', 'liked_by','total_comments') def get_total_likes(self, instance): return instance.liked_by.count() def get_total_comments(self, instance): return instance.comments.count() when i run this code, it shows, AttributeError: 'Post' object has no attribute 'comments'. how do i count comments of a post? -
Create a 'post' object and initialize a m2m attribute with post id and author id
I am trying to accomplish the following in Django: An app that allows users to create image posts. They can view any post that is in the system and add those posts to their bookmarks. When a user creates a post, the post is automatically added to their bookmarks. Model class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) post_image = models.ImageField(max_length=255, upload_to='images/content/', blank=False, null=False) author = models.ForeignKey(User, on_delete=models.PROTECT, related_name='authors') tags = TaggableManager(through=UUIDTaggedItem, help_text=_('Maximum of 5 tags allowed')) created = models.DateTimeField(auto_now_add=True) bookmarks = models.ManyToManyField(User, related_name='bookmarked', blank=True) bookmark_count = models.IntegerField(default=0) def get_create_date(self): return self.created.strftime("%B %Y") ordering = ['-created'] View @login_required def post_add_view(request, *args, **kwargs): context = {} user = request.user if request.method == 'POST': form = PostAddForm(request.POST, request.FILES) if form.is_valid(): new_post = form.save(commit=False) new_post.author = user new_post.save() form.save_m2m() context['form'] = form messages.add_message(request, messages.SUCCESS, 'Image uploaded successfuly!') return redirect('library:posts') context['form'] = form return render(request, 'library/post_add.html', context) else: form = PostAddForm() context['form'] = form return render(request, 'library/post_add.html', context) When a user creates a new post, that post will be associated with an additional attribute in the Post object called 'bookmarks'. The 'bookmarks' attribute has a many-to-many relationship with author and post. I can easily create the post object, associate it with the author and save … -
Django: Javascript error with alert box displaying values
I am creating a web application that will serve as a grocery store. The way I set it up is so the customer can come onto the website, click on the items that they would like to purchase, and then click a submit button to purchase those items. The problem I am running into is that my Javascript is not printing the correct values. In both spots, it says undefined. I will put a picture below for reference. views.py def inventory(request): products = request.POST.getlist('products') for product in products: a = Post.objects.get(title=product) a.quantity = a.quantity -1 a.save() print(products) return redirect('blog-home') home.html {% extends "blog/base.html" %} {% load static %} {% block content %} <form action="{% url 'js' %}" method="POST" id="menuForm"> {% for post in posts %} {% if post.quantity > 0 %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2">{{ post.category }}</a> </div> <h2><a class="article-title" >{{ post.title }}</a></h2> <p class="article-content"> Price: ${{ post.Price }}</p> <p class="article-content"> Sale: ${{ post.Sale }}</p> <input type="checkbox" id="product_{{ post.id }}" value="{{ post.title }}" form="menuForm" name="products" > Inventory count: {{ post.quantity }} </input> </div> </article> {% else %} {% endif %} {% endfor %} <button id="btn" type="submit" form="menuForm">Confirm Purchase</button> </form> <script src="{% static "JS/javascript.js" %}" type="text/javascript"></script> … -
How do I solve this error of Pymongo? cursor id not found pymongo
I'm getting the whole data of some collection in MongoDB and after a while (like 30 or 60 minutes), the script raises the following error: pymongo.errors.CursorNotFound: cursor id 1801580172063793986 not found, full error: {'ok': 0.0, 'errmsg': 'cursor id 1801580172063793986 not found', 'code': 43, 'codeName': 'CursorNotFound'} This error occurs after the 24k documents. I'm using Django and Pymongo connected to the database in the local server. The collection has like 60k documents. This is how I'm getting the data: client = MongoClient(settings.MONGO_HOST, settings.MONGO_PORT) collection = client[settings.MONGO_DB].users cursor = users.find(no_cursor_timeout=True) for user in cursor: # getting the data from the user Just in case, I'm using: Python 3.8 Django 3.1.4 Pymongo 3.11.0 Mongod 4.4.2 (for the local server) Ubuntu 20.04 -
Django: preserving GET parameters in URL template tag
I'm using a GET parameter in my Django app to pass in information, that I want to be preserved in future links using Django's {% url %} template tag. In my case, this is to allow view-only access within the app. Example URL: https://my.app/entry/123?key=abcdef An example link on that page is already created like this: <a href="{% url 'entry_detail' entry.id %}">View more details</a> Desired result: I would like Django's URL template tag to automatically preserve any GET parameters named key throughout the app. In this case, it would generate new URLs with that same parameter applied. For example: https://my.app/entry/123/details?key=abcdef Workarounds This blog post and this gist solve the problem by creating a new template tag and using that instead of Django's url template tag. Is that really the best solution? I'd end up having to replace every instance of {% url %} throughout my app with my own tag. It also wouldn't fix the use of reverse(). -
Set the min attribute HTML form value of a field in views.py
I was looking through this article to figure out how to set a field's value after a form is initialized. I don't see this in Django's docs, or maybe I'm putting in the wrong query, but is there a way to set the 'min' attribute value of a field in views.py? I'm asking because the min value can change constantly since it's a bid amount that is set each time a user bids above the highest_bid variable value in the view_listing function. models.py class Bid(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) listing = models.ForeignKey(Listing, on_delete=models.CASCADE, null=True) bid_amount = models.DecimalField(decimal_places=2, max_digits=10) def __str__(self): return f"{self.user}'s bid on {self.listing} is {self.bid_amount}" forms.py class BidForm(ModelForm): class Meta: model = Bid fields = ('bid_amount',) labels = { 'bid_amount': ('Your Bid'), } widgets = { 'bid_amount': forms.NumberInput(attrs={'step': 00.50, 'class': 'form-control', 'style': 'width:50%', 'min': 0, 'title': '', 'placeholder': '' }) } views.py @login_required def view_listing(request, listing_id): listing = get_object_or_404(Listing, pk=listing_id) bids = Bid.objects.filter(listing=listing) all_bids = [] # Set an empty bid list to get all bids if any exist highest_bid = listing.starting_price # Set highest bid to 0 in case there are no bids if bids: bid_list = list(bids) # Convert Queryset to a list for index … -
How to restrict users from seeing swagger endpoint docs but not using them?
We want users to be able to see only a few swagger docs based a django permission given to them, but we don't want to restrict them from using other endpoints that they don't have permission to view. Swagger docs don't provide a way to do this (or at least I haven't seen). Has anyone done this? -
Django DataError index out of range with postrgresql
Good evening, I realise that this question may have been asked in the past, but I am getting the following errors "psycopg2.errors.NumericValueOutOfRange: integer out of range" and "django.db.utils.DataError: integer out of range" when using postgresql with Django. Other responses to similar queries all seem to suggest that I am reaching very large id's or pk's. This is not the case. My database is very small, and I am just trying to save objects to it, and I cannot possibly be reaching 2^31-1 id's. Some objects save ok, others do not and raise the error. There seems to be no pattern to it, and its infuriating. I have until recently been using sqlite for this, and I have never ever had this problem. I am new to postgresql but the database exists, is migrated to successfully and I can see the fields inside pgAdmin. The project is quite complex and I am unable to provide a minimum reproducible example without posting much code, but I am happy to elaborate. What could possibly by the reason for the above? Portion of models.py as requested: class Requirement(models.Model): module = models.ForeignKey(Module, on_delete=models.CASCADE, null=False) signups = models.ManyToManyField('Student', through='SignUp', blank=True) etc. class Student(models.Model): first_name = models.CharField(max_length=50, … -
When adding a new member to an existing Enum class used by a Model field, is a new Django migration necessary?
Let's say I have a model Pie, and I add a field flavor, which is an EnumTextField. class FlavorType(Enum): APPLE = 'apple' BANANA = 'banana' Django auto-generates the migration: operations = [ migrations.AddField( model_name='pie', name='flavor', field=django_apps.core.fields.EnumTextField( choices=[(django_apps.bakery.constants.FlavorType('apple'), 'apple'), (django_apps.bakery.constants.FlavorType('banana'), 'banana')], enum_cls=django_apps.bakery.constants.FlavorType ), ), ] Let's say that later on, I add a new member, such as FlavorType.CHERRY: class FlavorType(Enum): APPLE = 'apple' BANANA = 'banana' CHERRY = 'cherry' Question: Does a new AlterField migration need to be made to update field.choices? My guess is no, because we've already specified the enum_cls. I notice that makemigrations doesn't create a new migration file when this enum member is added. Additionally, I can save a new pie of flavor cherry to the database with no problem. If this is the case, then 1) I find it a little misleading that choices is even in the original migration and 2) I couldn't find any documentation about it. Any insight is appreciated! -
django: Javascript pop up alert not working
I am creating a web application that will serve as a grocery store. The way I set it up is so the customer can come onto the website, click on the items that they would like to purchase, and then click a submit button to purchase those items. The problem I am running into is grabbing the info from the values and setting up a Javascript alert to show which boxes were selected. And to add up all the corresponding prices of each value, and displaying it. views.py def inventory(request): products = request.POST.getlist('products') for product in products: a = Post.objects.get(title=product) a.quantity = a.quantity -1 a.save() print(products) return redirect('blog-home') home.html {% extends "blog/base.html" %} {% block content %} <form action="{% url 'js' %}" method="POST" id="menuForm"> {% for post in posts %} {% if post.quantity > 0 %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2">{{ post.category }}</a> </div> <h2><a class="article-title" >{{ post.title }}</a></h2> <p class="article-content"> Price: ${{ post.Price }}</p> <p class="article-content"> Sale: ${{ post.Sale }}</p> <input type="checkbox" id="product_{{ post.id }}" value="{{ post.title }}" form="menuForm" name="products" > Inventory count: {{ post.quantity }} </input> </div> </article> {% else %} {% endif %} {% endfor %} <button type="submit" form="menuForm">Confirm Purchase</button> </form> {% endblock … -
Exporting user to db followed by creating subscription object throws the error 'User' object is not iterable'
I am exporting data to db using the following code, now I want to create subscription also to be created for uploaded users. Export part is working, but subscription throw the above error. def user_upload(request): template = "client_admin/user_upload.html" csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'THIS IS NOT A CSV FILE') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): if len(column) > 9: try: users = User( username=column[0], first_name=column[1], last_name=column[2], email=column[3], add_1=column[4], add_2=column[5], suburb=column[6], state=column[7], postcode=column[8], country=column[9], ) users.set_password('password') users.save() pricing = Pricing.objects.get(name='Free Trial') for user in users: subscription = Subscription.objects.create(user=user, pricing=pricing) stripe_customer = stripe.Customer.create( email=user.email ) stripe_subscription = stripe.Subscription.create( customer=stripe_customer["id"], items=[{'price': 'price_1HkPckwjpOS8'}], trial_period_days=7 ) subscription.status = stripe_subscription["status"] subscription.stripe_subscription_id = stripe_subscription["id"] subscription.save() except IntegrityError as e: return render_to_response('snippets/message.html') context = {} How I can get the list of just uploaded users and loop through it to create subscription object, any help will be appreciated. -
On django heroku deployment with postgres database getting error: DATABASES is improperly configured. Please supply the NAME value
Hi I am new to Heroku and I am trying to deploy my django app on the site. The issue I am running into is in the title. It seems to have an issue connecting to my postgres database. In my local environment, the database works perfectly fine this issue only seems to come up with the heroku deployment. I have added the DATABASE_URL already as a config var on Heroku. The app deploys but just says Internal Server Error, Here is the error logs heroku is giving me: raise ImproperlyConfigured( 2020-12-14T23:41:58.543920+00:00 app[web.1]: django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value. 2020-12-14T23:41:58.544131+00:00 app[web.1]: 10.148.121.8 - - [14/Dec/2020:23:41:58 +0000] "GET / HTTP/1.1" 500 0 "-" "-" 2020-12-14T23:41:58.545021+00:00 heroku[router]: at=info method=GET path="/" host=premtablelive.herokuapp.com request_id=aa3e9556-0490-4690-8b0b-d414e69a0305 fwd="24.190.19.51" dyno=web.1 connect=1ms service=5ms status=500 bytes=244 protocol=https I'm not sure what is causing this issue I am not spelling the name value for my database wrong in my code as it works in my local environment. here is my settings: from pathlib import Path import django_heroku import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: … -
Error: Request Entity Too Large, Your client issued a request that was too large
I am using google cloud engine to run django application and cloud storage to save media files. Looks like I can save files upto 2 Mega Bytes. But if I try to save large file I get this error Error: Request Entity Too Large, Your client issued a request that was too large. I am using django-storages library to save files to google cloud. This is how I save it from django.core.files.storage import default_storage obj.file.save('file_name', ContentFile('more content')) In my settings.py file I played with GS_BLOB_CHUNK_SIZE = 256K as explained here. Though it takes time to save, but works on my local server, but doesn't on cloud engine. Any help on this issue is much appreciated. -
{"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"}
I keep getting the {"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"} error. I print the json it's receiving and it seems correct {'order_package': {'package': 1, 'package_quantity': 1}} Here's all the code I think is related. The post method: @permission_classes((AllowAny,)) def post(self, request): print(request.data) data = JSONParser().parse(request) serializer = serializers.CartSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=200) else: return Response.status_code(500) Cart model: class Cart(models.Model): order_package = models.ForeignKey(OrderPackage, on_delete=models.CASCADE, null=True, blank=True) order_item = models.ForeignKey(OrderItem, on_delete=models.CASCADE, null=True, blank=True) and the order package: class OrderPackage(models.Model): package = models.ForeignKey(Package, on_delete=models.CASCADE) package_quantity = models.IntegerField() I also tried not using json parser and passing request.data right into the data= in the serializer which gives the same error. Any help is appreciated. -
Django: Why won't my video display in template? (Error "No video with supported format and MIME type found")
I have a page in which a user can do several things and that should display a video the user uploaded, but I get this error ("No video with supported format and MIME type found"), even though—I think—I am doing exactly what I have found online in several places. These are my MEDIA_ROOT and MEDIA_URL in settings.py: MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Inside the media directory, I have subdirectories for each user, which are created—if they don't exist already—when a user creates a project and uploads a video. Inside the user subdirectories, there is one directory for each project the user creates. Inside these, several files exist, including the video. So, for the test I'm doing right now, this is the structure: |— media |— user_3 |— Test_project |— video_file.mp4 |— irrelevant_file |— irrelevant _file ... The video is a FileField in a model I called Project. In my view, I get the video url and pass it to the template in the following way: (I am omitting any part of the code that is irrelevant to this issue) def sample_view(request, project_id): video = Project.objects.get(pk=project_id).video_file.url # ... some irrelevant code # The formset has always worked. I am … -
problem with celery state when launching several tasks together
I have a celery task to upload videos to a server. It goes like this: x=asynchronousupload.delay(idcf,i,info['recording_files'][ijk]['download_url']+"?access_token="+utils.generateToken(),uuids,tit,descr,who,info['recording_files'][ijk]['recording_start'],info['recording_files'][ijk]['recording_end']) I call that for 10 videos in parallel. I store the task numbers and then I'm able to check periodically the state of each task doing like so: res = AsyncResult(taskid[ij]) res.ready() res.state The problem is that all tasks succeed (I see that the videos are uploaded where I want and the task functions execute themselves and return the right value) but it is only one task that returns SUCCESS in res.state. When this one task (I suppose the first one that finished) is finished I then stop everything and load the page but sometimes it is just too early and not everything is finished. I'd like to get the other tasks to show SUCCESS as well but even though I wait (and they executed everything they had to and returned the right value), it never ends up SUCCESS and remains PENDING. What is happening? -
POSTMAN -> DJANGO -- Upload Binary file (jpeg). Can't get it to work no matter what I do
to simplify: curl --location --request PUT 'https://myserver.com/upload' \ --form 'file=@/Users/myname/Desktop/bond.jpg' \ --form 'test=test' It gets to my Django App: class MyUploadView(APIView): parser_classes = [FormParser, MultiPartParser] def put(self, request, **kwargs): print(request.FILES) but gives out: <MultiValueDict: {}> nothing I do work, file is always empty. when I use Content-Type: multipart/form-data it doesn't work as well, and sometimes django would complain there is no boundary -- but any value there gives out the same error. MY GOAL IS SIMPLE: all I want it to upload a file to django and save it to disk on the backend. I cannot believe this i taking all day long with zero results and zero examples online that actually work. -
Django images don't fill height
I am currently working on a django blog. However, I am experiencing some difficulties with the size of the post thumbnails. Here's a picture: What I marked in yellow is how the image should be filling the space. The width is fine, but the heigh isn't working well as you can see. Here's the code: {% extends 'base.html' %} {% load static %} {% block content %} <style> img { height: 100%; width: 100%; } </style> <!-- Post--> {% for obj in object_list %} <div class="row d-flex align-items-stretch"> {% if not forloop.first and not forloop.last %} <div class="image col-lg-5"><img src="{{ obj.thumbnail.url }}" alt="..."></div> #Here's the image {% endif %} <div class="text col-lg-7"> <div class="text-inner d-flex align-items-center"> <div class="content"> <header class="post-header"> <div class="category"> {% for cat in obj.categories.all %} <a href="#">{{ cat }}</a> {% endfor %} </div> <a href="{{ obj.get_absolute_url }}"> <h2 class="h4">{{ obj.title }}</h2> </a> </header> <p>{{ obj.overview|linebreaks|truncatechars:200 }}</p> <footer class="post-footer d-flex align-items-center"><a href="#" class="author d-flex align-items-center flex-wrap"> <div class="avatar"><img src="{{ obj.author.profile_picture.url }}" alt="..." class="img-fluid"></div> <div class="title"><span>{{ obj.author }}</span></div></a> <div class="date"><i class="icon-clock"></i> {{ obj.timestamp|timesince }} ago</div> <div class="comments"><i class="icon-comment"></i>{{ obj.comment_count }}</div> </footer> </div> </div> </div> {% if forloop.first or forloop.last %} <div class="image col-lg-5"><img src="{{ obj.thumbnail.url }}" alt="..."></div> #Here's the …