Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django forms.py, ModelChoiceField altering the shown text
I have a form with a dropdown generated by my forms.py: asset = forms.ModelChoiceField(required=False, queryset=Asset.objects.filter(Q(is_loaned=False) & Q(may_be_loaned=True)), label="Asset", widget=forms.Select(attrs={'class': 'form-control'})) The values it output is shown like this: UN-POA-1875 (15) | Laptop | Lenovo L590 20Q7 i5-8265U 1.6 GHz 8 GB 256 SSD UN-MIL-ALL-1876 (23) | Laptop | Lenovo L590 20Q7 i5-8265U 1.6 GHz 8 GB 256 SSD <select name="asset" class="form-control" id="id_asset"> <option value="" selected="">---------</option> <option value="235">UN-POA-1875 (15) | Laptop | Lenovo L590 20Q7 i5-8265U 1.6 GHz 8 GB 256 SSD</option> <option value="236">UN-MIL-ALL-1876 (23) | Laptop | Lenovo L590 20Q7 i5-8265U 1.6 GHz 8 GB 256 SSD</option> </select> I would like to on this form only to show the 4 digit number: 1875 1876 <select name="asset" class="form-control" id="id_asset"> <option value="" selected="">---------</option> <option value="235">1875</option> <option value="236">1876</option> </select> How do I do that? -
How to get the id of a form in Django?
I am trying to develop a page in Django where there is multiple form that the user can modify. For this, I need to get the id of the form the user ask to modify. There is my code: models.py: class Order(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) date = models.DateField() forms.py: class OrderForm(ModelForm): class Meta: model = Order fields = ["date"] views.py: def order(request, identifiant): user_orders = [] form_user_orders = [] user = User.objects.get(username=identifiant) #We use identifiant from the url to get the user user_orders.append(Order.objects.filter(user=user.id)) #We get all order of the user if request.method == "POST": form = OrderForm(request.POST) if form.is_valid(): order_instance = Order( id = None, #This is where I have a problem user=User(id=user.id), date=form.cleaned_data["date"], ) order_instance.save() return HttpResponseRedirect(f"/forms/orders/{identifiant}") else: for order in user_orders[0]: #We iterate on all orders and put them in another list as form instances form_user_orders.append(OrderForm(instance=order)) return render(request, "forms/orders.html", {"identifiant": identifiant, "forms": form_user_orders}) urls.py: urlpatterns = [ path("order/<identifiant>", views.order) ] order.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Order</title> </head> <body> <form method="POST"> {% csrf_token %} <div> <label>Date</label> <div> {{ form.date }} </div> </div> </form> </body> </html> -
AWS Elasticbeanstalk Django - Error during app-deploy
I updated my website on Amazon's Elasticbeanstalk as I do regularly, but now I'm getting a 502 gateway error, even when trying to setup a completely new website. The web.stdout.log shows the following: Sep 9 09:16:28 ip-172-31-36-179 web: [2021-09-09 09:16:28 +0000] [336] [INFO] Starting gunicorn 20.1.0 Sep 9 09:16:28 ip-172-31-36-179 web: [2021-09-09 09:16:28 +0000] [336] [INFO] Listening at: http://127.0.0.1:8000 (336) Sep 9 09:16:28 ip-172-31-36-179 web: [2021-09-09 09:16:28 +0000] [336] [INFO] Using worker: gthread Sep 9 09:16:28 ip-172-31-36-179 web: [2021-09-09 09:16:28 +0000] [363] [INFO] Booting worker with pid: 363 Sep 9 09:16:28 ip-172-31-36-179 web: Failed to find attribute 'application' in 'dashboard'. Sep 9 09:16:28 ip-172-31-36-179 web: [2021-09-09 09:16:28 +0000] [363] [INFO] Worker exiting (pid: 363) Sep 9 09:16:28 ip-172-31-36-179 web: [2021-09-09 09:16:28 +0000] [336] [INFO] Shutting down: Master Sep 9 09:16:28 ip-172-31-36-179 web: [2021-09-09 09:16:28 +0000] [336] [INFO] Reason: App failed to load. I gather this is a WSGI issue, however nothing I try seems to have any effect. I've tried the following in my .ebextensions config: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: dashboard.wsgi:application WSGIPath: dashboard.wsgi:application WSGIPath: dashboard/dashboard.wsgi:application WSGIPath: dashboard.wsgi (the original that used to worked 2 days ago, doesnt anymore) the rough folder structure is: dashboard ├── dashboard │ ├── __init__.py │ ├── … -
Search for a date that has this number python
I am working on a search box type of functionality in searching for an available date in a model from a DateTimeField date in Django. Here are some sample dates, input, and desired output: Sample dates: 05/01/2022 06/04/2021 01/02/2023 08/01/2022 07/31/2025 03/05/2022 01/28/2021 Sample Input-Output: Input: 3 Output: 01/02/2023, 07/31/2025, 03/05/2022 Input: 31 Output: 07/31/2025 Input: 8 Output: 08/01/2022, 01/28/2021 Input: 6 Output: 06/04/2021 I hope the examples make it clear on what I have in mind. The purpose of this is to eliminate the use of a date picker and use a textbox instead. So if a user types in '3', all dates that have '3' in them will be the output and so on. This is strictly searching by numbers only, so it is clear that the user won't input any strings. Which means no 'February', 'Monday', and etc. inputs or outputs. Is this kind of functionality possible or should I scrap this and turn to a date picker and search in a date range instead? Currently, I'm thinking of the following ways to do this: Generate a minimum and a maximum datetime object (based from the table) that has the number input then do a range filter. … -
URL JSON Response using Django Rest Framework
can anyone tell me, what method or class from Django REST Framework I can use to get the JSON data from an online URL in a variable? Thanks in advance -
handling multiple requests in Django
i am new to Django and i am working on a rest API, my Django project is about making appointments with doctors, while each user can only make one appointment with a specific doctor, and each appointment, will have a number determine the order of the user, in a specific date, my question is there's any possible way that two or more users can make the same request,at the same time, and how i will determine the right order for them? -
How to properly add a custom field as a callable to Django admin change form?
I'm trying to add a custom field (pretty_user) to a model's admin page that displays the user info in a nice way. I'm adding the model as a callable directly in the ModelAdmin class. This works beautifully in the list_display view but it totally crashes in the change_form view. @admin.register(Model1Admin) class Model1Admin(admin.ModelAdmin): readonly_fields = [ 'id', 'configuration', 'ip_address', 'downloads', 'user', 'downloaded'] list_display = ['id','downloads','pretty_user','downloaded',] def pretty_user(self, obj): return f"{obj.user.get_full_name()} - ({obj.user.email})" pretty_user.short_description = 'User' def get_fields(self, request, obj=None): fields = ('id', 'downloads', 'pretty_user', 'downloaded') return fields The thing is that I have the same structure of adding custom fields as callables in the ModelAdmin for other models and they all work flawlessly. Here's an example of one where I add render_logo as a custom field: @admin.register(Model2Admin) class Model2Admin(admin.ModelAdmin): list_display = ('id', 'name', 'name_long', 'created', 'updated', 'render_logo') readonly_fields = ['id', 'created', 'updated', 'render_logo'] def get_fields(self, obj): fields = ('render_logo', 'id', 'name', 'name_long', 'created', 'updated') return fields def render_logo(self, m: 'Model2'): if m.logo is not None: return format_html(f'<img src="data:image/png;base64,{m.logo}" />') else: return format_html('<span>No logo</span>') I have tried everything to make it work but I can't see the problem. Any ideas? -
wkhtmltopdf and pdfkit error on heroku hosted site
I built a django app that requires downloading a pdf file, it works locally but not on heroku when hosted. urls.py path('download_resume/', DownloadResume, name='download_resume'), views.py @login_required(login_url='login') def DownloadResume(request): education = Education.objects.filter(user = request.user)[:3] template = loader.get_template('download_resume.html') html = template.render({'education':education}) options = { 'page-size':'Letter', 'encoding':'UTF-8' } pdf = pdfkit.from_string(html, False, options) response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment' filename = 'resume.pdf' return response This is the error it shows -
can't uplpoad photos in multipart form in django rest framework
I hsve a project where user can upload multiple photos when creating a announcement, when sending request from postman using form-data the announcement is added successfully but the image is not uploaded, when using raw Json with content type setting to:multipart/form-data, i got the following error: "detail": "Multipart form parse error - Invalid boundary in multipart: None" when sending the following request from browsable API: { "name": "tractor", "address": "any", "price": 100, "author": 17, "photo": [ { "name": "tractor", "image": "/C:/Users/Admin/Downloads/marteau.jpg" } ] } I got the following error: "detail": "Multipart form parse error - Invalid boundary in multipart: None" He is my code: Models.py class Photo(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to=nameFile, blank=True, null=True) class Announcement(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='announcements') name = models.CharField(max_length=100) address = models.CharField(max_length=100) price = models.FloatField(blank=True, null=True) description = models.TextField(blank=True, null=True) rating = models.FloatField(blank=True, null=True) date = models.DateTimeField(auto_now_add=True) photo = models.ManyToManyField(Photo, blank=True) Views.py class AnnouncementCreate(CreateAPIView): queryset = models.Announcement.objects.all() serializer_class = AnnouncementSerializer parser_classes = (FormParser,MultiPartParser) def perform_create(self, serializer): serializer.save(author=self.request.user) class PhotoViewSet(ListAPIView): queryset = models.Photo.objects.all() serializer_class = PhotoSerializer def post(self, request, *args, **kwargs): file = request.data.get('image') image = models.Photo.objects.create(image=file) return HttpResponse(json.dumps({'message': "Uploaded"}), status=200) Serializers.py class AnnouncementSerializer(WritableNestedModelSerializer, serializers.ModelSerializer): parameters = ParameterSerializer(many=True, required=False) photo = PhotoSerializer(many=True, required=False) class … -
How can I access join "intermediate" table using standard django filter?
How can I get a particular queryset of RecipeIngredient instances, supposing that I know the recipe and its ingredients? Have been trying to use the following code: RecipeIngredient.objects.filter(recipe=recipe, ingredient__in=recipe.ingredients.all()) But it returns me the queryset of one instance, but not multiple. class Recipe(models.Model): name = models.CharField(max_length=200, verbose_name='Name of a recipe') ingredients = models.ManyToManyField( 'Ingredient', through='RecipeIngredient', verbose_name='Ingredients of a recipe' ) class Ingredient(models.Model): name = models.CharField( max_length=256, verbose_name='Name of an ingredient' ) class RecipeIngredient(models.Model): recipe = models.ForeignKey( 'Recipe', on_delete=models.CASCADE ) ingredient = models.ForeignKey( 'Ingredient', on_delete=models.CASCADE ) amount = models.IntegerField( validators=[ MinValueValidator(1), MaxValueValidator(44640) ], verbose_name='Amount of ingredients' ) -
Redirect function not working correctly in django
When def login() function call and redirect to def index() function my url change in the browser and look like http://127.0.0.1:8000/error500index this url. But logically url look like http://127.0.0.1:8000/index this. But error500 show in the url when i use redirect function, error500 is my last url in the Project urls.py and APP urls.py. Anyone help me out what is the happening? view.py from django.shortcuts import render, redirect from django.contrib import messages from django.http import HttpResponse from .models import WebUser def index(request): return render(request, 'index.html') def login(request): if (request.method == 'POST'): login_email = request.POST['email'] login_password = request.POST['password'] # Compare with Database where input email exist! try: CheckUser = WebUser.objects.get(email=login_email) except: return HttpResponse("User Dosen't Exist!") if (login_email == CheckUser.email and login_password == CheckUser.Password): #When redirect function call my url change and pick the last url from project urls.py and this url appears in the browser http://127.0.0.1:8000/error500index return redirect(index) else: return HttpResponse("Email or Password are wrong!") else: return render(request, 'login.html') Project Urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('SIS_APP.urls')), path('index', include('SIS_APP.urls')), path('login', include('SIS_APP.urls')), path('register', include('SIS_APP.urls')), path('settings', include('SIS_APP.urls')), path('weather', include('SIS_APP.urls')), path('error404', include('SIS_APP.urls')), path('error500', include('SIS_APP.urls')), ] APP urls.py from django.contrib import admin from django.urls import path from … -
when Axios requests Http request , but url is changed and creates [object%20Object]
I would like to delete an object in my Django DB with http request with Axios to Django View. But POST url is changes being added a strange thing, [object%20Object]. It seems to be the problem of converting but I don't understand exectly why it happens. What I'm doing wrong? this is the part of axios. <script> // Delete review const deleteBtns = document.getElementsByClassName("delete"); function handleClickDelete(event){ event.preventDefault(); const deleteBtn = event.target; const pk = deleteBtn.value; const review = document.getElementById(`${pk}`); review.hidden = true axios.post({ url:"{% url 'reviews:delete' %}", data:{ "pk": pk } }) .then(res => alert("the review is deleted!")) .catch(errors => console.log(errors.response.data)); } for (const deleteBtn of deleteBtns) { deleteBtn.addEventListener("click", handleClickDelete); } </script> Django urls.py app_name = "reviews" urlpatterns = [ path( "api/<int:pk>/review/create/", review_views.create_review, name="create", ), path( "api/review/delete/", review_views.delete_review, name="delete", ), path( "api/review/update/", review_views.update_review, name="update", ), ] and view.py def delete_review(request): if request.method == "POST": pk = request.POST.get("pk") review = models.Review.objects.get(pk=pk) review.delete() return JsonResponse({"status": "Success"}) -
how to run async function in Threadpoolexecutor in python
I have an async get_forecastweather function which gives me JSON weather data, I understand that we can't execute the async function inside sync, but how do i do it inside a separate thread, need help, thanks in advance def weather_detail(request): if request.method == 'GET': city_name = 'my_city' key = 'mykey' result = None with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor: response = executor.submit(get_forecastweather,city_name,key) result = response.result() print('Result from thread ',result) return render(request,'weather/weather_detail.html') the error I am getting is RuntimeWarning: coroutine 'get_forecastweather' was never awaited response = wrapped_callback(request, *callback_args, **callback_kwargs) RuntimeWarning: Enable tracemalloc to get the object allocation traceback -
badly formed hexadecimal UUID string in DJANGO
I first created a user table in user_app where it would fill the ID of every user normally like 1,2,3,4... so on . class CustomUser(AbstractUser): user_id = models.BigAutoField(primary_key=True) Later i updated the BigAutoField to UUIDField : class CustomUser(AbstractUser): user_id = models.UUIDField(primary_key=True,default=uuid.uuid4, editable=False) now in database there are some users who has 1,2,3,4.. so on as id and remaining has id in UUID format . Everything is working fine but the issue here is whenever is click on users in ADMIN panel it shows me the error value = uuid.UUID(value) File "C:\Users\divit\AppData\Local\Programs\Python\Python38\lib\uuid.py", line 169, in __init__ raise ValueError('badly formed hexadecimal UUID string') ValueError: badly formed hexadecimal UUID string is there any way to update the ID of other users with 1,2,3..so on as id or is there a way to delete these users? as i cant delete it from admin panel because whenever i click on users it shows me badly formed hexadecimal UUID string error -
Django IP not connecting [closed]
I am creating my first Django project (Windows 10, python 3.8, Django 3.2.6), I have followed the instructions from https://docs.djangoproject.com/en/3.2/intro/tutorial01/ this is all the input and outputs in command prompt after that, I visited http://127.0.0.1:8000/ with my browser but it says: This site can’t be reached 127.0.0.1 refused to connect. I have no experience in Django but I am good at python. Please help, I am stuck for a long time. -
How change host address in DRF api root page?
My app developed by djangorestframework has API root page where posted all available API endpoints. But problem is that host has uncorrect URL (url=backend), how I can change it to actual IP-address where my app deployed? -
how to detect technology , hosting details , company profile in python [closed]
I want to create a website like builtwith in python where all the functionality will be there . I'm trying a lot . Please help me . -
Convert CBV to FBV in django
how to convert this views to Class Base View def add_user_order(request): new_order_form = UserNewOrderForm(request.POST or None) if new_order_form.is_valid(): order = Order.objects.filter(owner_id=request.user.id, is_paid=False).first() if order is None: order = Order.objects.create(owner_id=request.user.id, is_paid=False) product_id = new_order_form.cleaned_data.get('product_id') count = new_order_form.cleaned_data.get('count') if count < 0: count = 1 product = Product.objects.get_by_id(product_id=product_id) order.orderdetail_set.create(product_id=product.id, price=product.price, count=count) # todo: redirect user to user panel return redirect(f'products/{product_id}/{product.title.replace(" ", "-")}') return redirect('/') -
How to run celery-beat task under decorator?
I have "locker" decorator: def lock_task(func): def wrapper(*args, **kwargs): if redis.set(func.__name__, 'lock', nx=True): try: result = func(*args, **kwargs) finally: redis.delete(func.__name__) return result or True else: return 'Skipped' return wrapper Also I have celery-task with my decorator: @celery_app.task @lock_task def test(): call_command('test') And I have my celery-beat settings: celery_app.conf.beat_schedule = { 'test': { 'task': 'project.celery.test', 'schedule': crontab(minute='*/1') } } After starting I got KeyError Received unregistered task of type 'project.celery.test'. How to call this construct correct? -
Django query to sort by a field on the latest version of a Many to Many relationship
Let's say I have the following Django models: class Toolbox(models.Model): class Meta: constraints = [ models.UniqueConstraint( fields=["name", "version"], name="%(app_label)s_%(class)s_unique_name_version", ) ] name = models.CharField(max_length=255) version = models.PositiveIntegerField() tools = models.ManyToManyField("Tool", related_name="toolboxes") def __str__(self) -> str: return f"{self.name}" class Tool(models.Model): name = models.CharField(max_length=255) def __str__(self) -> str: return f"{self.name}" I want to write a query that fetches all Tools and returns them sorted by their latest toolbox's name. I know I can achieve this using the following code: tools = Tool.objects.all() for tool in tools: tool.latest_toolbox = tool.toolboxes.order_by("-version").first() tools = sorted(tools, key=lambda x: x.latest_toolbox.name) Here's a unit test written in pytest-django to prove this works: from pytest_django.asserts import assertQuerysetEqual def test_sort_tools_by_latest_toolbox_name(): tool1 = Tool.objects.create(name="Tool 1") tool2 = Tool.objects.create(name="Tool 2") toolbox1_v1 = Toolbox.objects.create(name="A", version=1) toolbox1_v1.tools.add(tool1) toolbox1_v2 = Toolbox.objects.create(name="Z", version=2) toolbox1_v2.tools.add(tool1) toolbox2_v1 = Toolbox.objects.create(name="B", version=1) toolbox2_v1.tools.add(tool2) tools = Tool.objects.all() for tool in tools: tool.latest_toolbox = tool.toolboxes.order_by("-version").first() tools = sorted(tools, key=lambda x: x.latest_toolbox.name) assertQuerysetEqual(tools, [tool2, tool1]) However, the Tool table has thousands of records and this is taking minutes to execute. Is there a faster query I can write? I've tried the following but it's returning duplicates and isn't sorting the tools correctly: Tool.objects.order_by("toolboxes__name") # <QuerySet [<Tool: Tool 1>, <Tool: Tool 2>, <Tool: Tool … -
Django - how to sort an Album by Track and Disc #?
I want to display a music album on my website, the Problem is that the album itself has two discs and each disc has x tracks. Now I'm wondering how I can display this split-up on my Django template as I want it to look like that: Disc 1 - Title - 1 - Title - 2 - Title - 3 - Title - 4 ... Disc 2 - Title - 1 - Title - 2 - Title - 3 - Title - 4 ... This is my View: def music_album_detail(request, pk): music_album = get_object_or_404(MusicAlbums, pk=pk) music_album_tracks = MusicTracks.objects.filter(album=music_album).order_by('track') args = { 'music_album': music_album, 'music_album_tracks': music_album_tracks, } return render(request, 'App/music_album_detail.html', args) At my Template I currently only do this: {% for music_album_track in music_album_tracks %} <td>{{ music_album_track.track }}</td> ... This is how my model looks like: class MusicAlbums(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.TextField(verbose_name=_("Title"), blank=False, null=True, editable=False, max_length=255) artist = models.ForeignKey(MusicArtists, on_delete=models.CASCADE, related_name='album_artist') cover = models.ImageField(verbose_name=_("Cover"), blank=True, null=True, upload_to=get_file_path_images) cover_tn = models.ImageField(verbose_name=_("Cover Thumbnail"), blank=True, null=True, upload_to=get_file_path_images) release_date = models.DateField(verbose_name=_("Release Date"), blank=True, null=True, editable=False) genre_relation = models.ManyToManyField(through='GenreMusicAlbum', to='Genre') total_discs = models.IntegerField(verbose_name=_("Total Discs #"), blank=True, null=True,) total_tracks = models.IntegerField(verbose_name=_("Total Tracks #"), blank=True, null=True,) copyright = models.TextField(verbose_name=_("Copyright"), blank=True, … -
Export data to Excel in Django with openpyxl
I am trying to export data to excel with openpyxl package but django throwing error 'utf-8' codec can't decode byte 0xae in position 3: invalid start byte. You passed in b'{\x1ah\xae' (<class 'bytes'>). class FeedbackExportView(View): def get(self, request): feedback_queryset = Feedback.objects.all() response = HttpResponse( content_type='application/vnd.openxmlformats- officedocument.spreadsheetml.sheet', ) response['Content-Disposition'] = 'attachment; filename={date}- feedback.xlsx'.format( date=datetime.datetime.now().strftime('%Y-%m-%d'), ) workbook = Workbook() worksheet = workbook.active worksheet.title = 'Feedback' columns = ['candidate email', 'candidate Name', 'vacancy', 'Interview Round', 'Interviewer', 'Recommendation'] row_num = 1 for col_num, column_title in enumerate(columns, 1): cell = worksheet.cell(row=row_num, column=col_num) cell.value = column_title for feedback in feedback_queryset: row_num += 1 row = [ feedback.candidate.user.email, feedback.candidate.user.full_name, feedback.candidate.vacancy.title, feedback.interview.interview_round, feedback.interview.interviewer_id.all()[0].full_name, feedback.selection_recommendation, ] for col_num, cell_value in enumerate(row, 1): cell = worksheet.cell(row=row_num, column=col_num) cell.value = cell_value workbook.save(response) return response -
CK Editor works locally but not on server
good work I have a django application running on aws ubuntu 18.04 LTS x64 architecture. The ck editor that works when I enter the local admin panel. Doesn't work on server (text box comes instead of ck editor). How can I solve this problem? -
How to minimise the django search query?
I am planning to implement a live autosearch complete function in django ! But, am belive that am over doing it, so need a suggestion: Basically this search bar is located in a page, where all at first all the available data's are displayed as a list ! And then when user types something i filter it out using jquery autocomplete. In the above, am making two queries one to get all data and another one on each user types As this takes two query, i belive its inefficient Here is my search function def search_query(request): if 'term' in request.GET: qs = University.objects.filter(name__icontains=request.GET.get('term')) names = list() for data in qs: names.append(data.name) return JsonResponse(names, safe=False) And the above is been called each time the user types in the search bar and this is my jquery autocomplete code: <script> $( function() { $( "#tags" ).autocomplete({ source: "{% url 'students:search-query' %}" // this hits the above def }); } ); </script> Apart from this, am also making this to show full list as initial data, def index(request): univesity = University.objects.filter(published=True) context = {'univesity': univesity} return render(request, 'students/search/index.html', context) is this right way or is there any effcient way ? Can both the queries … -
Django - What happens when a csrf_token is NOT re-submitted to the server?
Hello, Everybody. I was wondering about... What happens when a csrf_token is submitted by the server-side application to the browser in an HTML form, and that form was not submitted with the post by the browser? Because I was thinking... Django makes the csrf_token and relates it to the user or to the session, I am not sure, to check it when it comes back. And then I think it deletes it, right? So what if it wasn't back? Will it stay there waiting until the session ends or what? For Example, I want to make a form for Comments under the details of the object. But it is not a must to comment. You can comment if you need, and you can do not so. So I put a form like this under those details : <div class="container"> <!-- Here is the object data --> </div> <div class="container comments"> <ul> <li> <form action="{% url 'ads:newcomment' %}" method="POST"> {% csrf_token %} <input id="comment_txt" name="comment" type="text" value="Type a comment..." class="comment_txt"/> </form> </li> {% for comment in comments %} <li class="comment">{{comment}}</li> {% endfor %} </ul> </div>