Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
not getting updated fields using django signals
I am trying to fetch the updated fields using django signals.when i update the model using update view and call the post_save i get the update_fields as None in the kwargs. How to get the updated fields using django signals ?? signals.py from .models import Department from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender=Department) def department_history(sender, created, **kwargs): update = kwargs['update_fields'] views.py class DepartmentEditView(LoginRequiredMixin, SuccessMessageMixin,PermissionRequiredMixin, UpdateView): model = Department form_class = DepartmentForm success_url = reverse_lazy('departments:departments') success_message ="%(department_name)s was Updated Sucessfully " template_name_suffix = '_update' permission_required = ('departments.change_department',) -
Is there a function that can compare one user's a week ago database and today's database?
I'm now making a "Score checker" site, that can analyze the one user's increase and decrease of score. But the problem is, I think there's no function that I can use. Where do I need to compare before score and after score, and show result on the site? I'm now running Django on macOS 10.14.2, Safari browser, and SQLite (Django stock database). I've already tried registering custom templates, getting variables from HTML and calculate on views, but every methods gave me a syntax error. *Score is same with contribution point. **Models.py (shows line 5-10, line 31-34) class CharacterMain(models.Model): name = models.CharField(verbose_name = '닉네임', max_length = 10, default = ' ') characterPicture = models.URLField(max_length = 500) job = models.ForeignKey('Job', on_delete = models.CASCADE) guildHierarchy = models.ForeignKey('GuildHierarchy', on_delete = models.CASCADE) guildName = models.ForeignKey('GuildName', on_delete = models.CASCADE) class ContributionPoint(models.Model): name = models.ForeignKey('CharacterMain', on_delete = models.CASCADE) point = models.IntegerField(default = 0) createdTime = models.DateTimeField(blank=True, null=True) **views.py (shows line 12-16) def characterMain_detail(request, pk): characterMain = get_object_or_404(CharacterMain, pk=pk) characterSubs = CharacterSub.objects.filter(mainCharacter__exact=characterMain.id) contributions = ContributionPoint.objects.filter(createdTime__month=timezone.now().month, name__exact=characterMain.id) return render(request, 'contribution/characterMain_detail.html', {'characterMain':characterMain, 'characterSubs':characterSubs, 'contributions':contributions}) **characterMain_detail.html (shows line 31-52), using Bootstrap 4 <div class="col-md-6"> <h4>Changes of contribution point</h4> <table class="table"> <thead class="thead-dark"> <tr> <th scope="col">Date</th> <th scope="col">Point</th> <th scope="col">Inc/Dec</th> </tr> </thead> … -
Within a specific view function Regardless of the login status, request.user = AnonymousUser. Is there a way to fix it?
Feed view works normally so request.user = allieus (login user) class Feed(APIView): def get(self, request, format=None): user = request.user following_users = user.following.all() print("following_users , ", following_users) image_list = [] for following_user in following_users: user_images = following_user.images.all()[:2] for image in user_images: print("image : ", image) image_list.append(image) # 본인 이미지도 추가 my_images = user.images.all()[:2] for image in my_images: image_list.append(image) print("image_list : ", image_list) sorted_list = sorted(image_list, key=get_key, reverse=True) serializer = serializers.ImageSerializer(sorted_list, many=True) # return Response(status=200) return Response(serializer.data) def get_key(image): return image.created_at but request.user of ChangePassword is always printed for AnonymousUser so An error occurred when trying to change the password. If you know why and If you know how to fix it Thank you very much! github : https://github.com/hyunsokstar/hyun4/blob/master/nomadgram/nomadgram/users/views.py class ChangePassword(APIView): def put(self, request, username, format=None): print("함수 실행 확인(ChangePassword) ") user = request.user print('user : ', user) current_password = request.data.get('current_password',None) if current_password is not None: # request로 넘어온 비밀번호와 db의 비밀번호를 비교 passwords_match = user.check_password(current_password) # 비밀번호가 정확할 경우 새로운 비밀번호를 request로부터 가져와서 user 객체에 save if passwords_match: new_password = request.data.get('new_password',None) if new_password is not None: user.set_password(new_password) user.save() return Response(status=status.HTTP_200_OK) # None일 경우 400 응답 else: return Response(status=status.HTTP_400_BAD_REQUEST) # false일 경우 400 응답 else: return Response(status=status.HTTP_400_BAD_REQUEST) # None일 경우 400 응답 else: … -
Django use intranet server for uploaded huge media files
I have a Django project and I have a server on the internet (with Nginx and Gunicorn). I also have an intranet server (on the local network). I want to upload user uploaded files (media) in the intranet server. Is it possible? How? I know users can't upload files when they are not connected to the intranet network, there's no problem this way. -
Django 2.1 Create Profile on User creation
I'm working on a project using Python(3.7) and Django(2.1) in which I need to create user's profile on user creation. Here what I have tried: From models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.CharField(max_length=500, null=True) about = models.CharField(max_length=1000, null=True) slogan = models.CharField(max_length=500, null=True) profile_pic = models.FileField(upload_to='media/profile_pics', null=True) def __str__(self): return self.user.username From signals.py: @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, created, **kwargs): instance.profile.save() From urls.py: path('register/', views.RegisterUser.as_view(), name='register'), From views.py: def post(self, request, *args, **kwargs): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') messages.success(request, f'Account has been created for {username}!') form.save() return HttpResponseRedirect(reverse_lazy('login')) else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) From forms.py: class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'password1', 'password2') When I create a new account via signup page, it creates the user but not the profile. Also, couldn't find any error on the console on user creation. What can be wrong here? Thanks in advance! -
Why doesn't saving queryset element at index work in django?
I am trying to save an object at a particular index of my queryset but it doesn't seem to work. I have a model called Customer and I wish to change a field called first_name from None to something, say 'aa' and I want to do this for index 0. code 1 customers = Customer.objects.filter(first_name=None) customers[0].first_name = 'aa' customers[0].save() code 2 customers = Customer.objects.filter(first_name=None) customer = customers[0] customer.first_name = 'aa' customer.save() Code 1 doesn't work but Code 2 works. Why doesn't the code 1 work? -
How to remove this error 'No application configured for scope type 'websocket''
I am trying to build a chat app with Django but when I am trying to run it I am getting this error 'No application configured for scope type 'websocket'' my routing.py file is from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter , URLRouter import chat.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket':AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) my settings.py is ASGI_APPLICATION = 'mychat.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } when I open my URL in 2 tabs I should be able to see the messages that I posted in the first tab appeared in the 2nd tab but I am getting an error [Failure instance: Traceback: <class 'ValueError'>: No application configured for scope type 'websocket' /home/vaibhav/.local/lib/python3.6/site-packages/autobahn/websocket/protocol.py:2801:processHandshake /home/vaibhav/.local/lib/python3.6/site-packages/txaio/tx.py:429:as_future /home/vaibhav/.local/lib/python3.6/site-packages/twisted/internet/defer.py:151:maybeDeferred /home/vaibhav/.local/lib/python3.6/site-packages/daphne/ws_protocol.py:82:onConnect --- <exception caught here> --- /home/vaibhav/.local/lib/python3.6/site-packages/twisted/internet/defer.py:151:maybeDeferred /home/vaibhav/.local/lib/python3.6/site-packages/daphne/server.py:198:create_application /home/vaibhav/.local/lib/python3.6/site-packages/channels/staticfiles.py:41:__call__ /home/vaibhav/.local/lib/python3.6/site-packages/channels/routing.py:61:__call__ ] WebSocket DISCONNECT /ws/chat/lobby/ [127.0.0.1:34724] -
Django container - serving static files
I'm trying to put my API made with django-rest-framework into a docker container. Everything seems to works except that I can't access to my static files. Here is my settings.py: MEDIA_URL = '/uploads/' MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads') STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') My urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), path('api/bookmakers/', include('bookmakers.urls')), path('api/pronostics/', include('pronostics.urls')), path('api/', include('authentication.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My Dockerfile FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN apt-get update && apt-get install -y locales && rm -rf /var/lib/apt/lists/* \ && localedef -i fr_FR -c -f UTF-8 -A /usr/share/locale/locale.alias fr_FR.UTF-8 ENV LANG fr_FR.UTF-8 ENV LANGUAGE fr_FR ENV LC_ALL fr_FR.UTF-8 RUN python --version RUN pip install --upgrade pip RUN pip install -r requirements.txt ADD . /code/ COPY docker-entrypoint.sh /code/ ENTRYPOINT ["/code/docker-entrypoint.sh"] And finally my docker-compose.yml version: '3.1' services: db: image: postgres container_name: nyl2pronos-db restart: always environment: POSTGRES_PASSWORD: password POSTGRES_DB: nyl2pronos website: container_name: nyl2pronos-website image: nyl2pronos-website build: context: nyl2pronos_webapp dockerfile: Dockerfile ports: - 3000:80 api: container_name: nyl2pronos-api build: context: nyl2pronos_api dockerfile: Dockerfile image: nyl2pronos-api restart: always ports: - 8000:8000 depends_on: - db environment: - DJANGO_PRODUCTION=1 So once I go to the url: http://localhost:8000/admin/, I can login but there is … -
how can i get all records of filter id in django
the code i've done showing only one first save record in database whether the id data consists more than once. @login_required(login_url='/login/') def lab_check_pats_list(request): if request.user.is_lab: lab=UserProfile.objects.get(id=request.user.id) labs=Lab.objects.get(user=lab.id) labt=Lab_Test.objects.filter(lab_id=labs.id) print(labt) pt = [] for x in labt: pt.append(x.patient_id) pts= Patient.objects.filter(id__in=pt) context={ 'ab':zip(pts,labt) } print(pts) return render(request,'lab_check_pats_list.html',context) i want to grab all the record of the filter id but it is only showing once For.exe-: Name Contact Test-Name Status Test_Date ID mr.x 123 sugar pending 12/28/2019 1 mr.x 123 blood pending 10/28/2019 1 mr.x 123 thyroid done 8/28/2019 1 -
How can I mark button as active based on the page I am at?
when a user clicks a tab I want that tab to show as active in blue. I can do it using if statements like the one I show on the code, but I would be repeating the code a LOT, so there has to be another way, could someone let me a hand please? The current if statement shows the profile page which is active <!-- This is saying: inherit everything from __base.html --> {% extends "storePage/partials/__base.html" %} <!-- Main base template which contains header and footer too --> {% load crispy_forms_tags %} <!-- To beautify the form at signup --> {% block body %} <div class="container bootstrap snippet"> <div class="row"> <div class="col-md-3"> <div class="list-group "> <label class="card-header">Personal Settings</label> {% if request.get_full_path == "/settings/profile/" %} <a href="{% url 'profile-settings' %}" class="list-group-item list-group-item-action active"><span class="fa fa-user"></span> Profile</a> {% endif %} <a href="{% url 'account-settings' %}" class="list-group-item list-group-item-action"><span class="fa fa-cog"></span> Account</a> <a href="{% url 'emails-settings' %}" class="list-group-item list-group-item-action"><i class="fas fa-envelope"></i> Emails</a> <a href="{% url 'billing-settings' %}" class="list-group-item list-group-item-action"><span class="fa fa-credit-card"></span> Billing</a> </div> </div> <!-- Center-right navBar--> <div class="col-md-9"> {% block settingsPageInfo %} {% endblock %} <!-- Here goes the user information on the profile page --> </div> </div> </div> {% endblock %} … -
Django refresh template with new values
I am trying to save checkbox inputs on a form, and when the user goes back to that page, they only view what checkboxes they viewed. Basically want one page to act as a form and display the new retrieved values. HTML <div class="checkbox"> {{ form.schedule }} {{ notifications.schedule }} <label>When you schedule a lesson</label> </div> <div class="checkbox"> {{ form.cancel }} {{ notifications.cancel }} <label>When a lesson is cancelled</label> </div> views.py @login_required def account_notifications(request): if request.method == 'POST': form = NotificationsForm(request.POST, instance=request.user.notifications) if form.is_valid(): notifications = form.save(commit=False) notifications.user = request.user notifications.save() return redirect('/student/dashboard') else: form = ProfileForm() form = NotificationsForm() context = {'form': form} return render(request, 'student/account_notifications.html', context) I am trying to submit the data on that form, and also retrieve it whenever the user goes back to it. -
How to get the image id via a button to use it in views.py?
I'm pretty new to django and coding in generall, I'm trying to build an Instagram clone.. so my question is.. how can I comment on a post that is on the newsfeed(list of all uploaded images by every user), without leaving the newsfeed? So my approach is to give every send button an id? or name? and somehow use it inside my views.py #views.py def newsfeed(request): images = Image.objects.all().order_by('-pub_date') if request.method == 'POST': c_form = CommentForm(request.POST) if c_form.is_valid(): new_comment = c_form.save(commit=False) new_comment.owner = request.user new_comment.image = #here should be something that points to the image i'm commenting on c_form.save() return redirect('upload_img:newsfeed') else: c_form = CommentForm() context = {'images_temp': images, 'c_form': c_form} return render(request, 'newsfeed.html', context) #models.py class Comment(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, default=1) image = models.ForeignKey(Image, on_delete=models.CASCADE, default=1) text = models.CharField(max_length=225) pub_date = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s comments on %s image' % (self.owner, self.image.owner) #newsfeed.html {% for image in images_temp %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ c_form|crispy }} <button name="{{ image.image }}" type="submit" class="btn btn-primary"><i class="fas fa-paper-plane"></i></button> </form> {% endfor %} -
Google API django
i want to use google calendar API for chatbot. I've searching in google API for using google calendar, but i still not understand. My question is, how can we give some link that refers to "Accept" My chatbot calendar, and after somebody "Accept", their calendar can syncronize with My chatbot calendar Thank you! -
Bad gateway error when loading large sklearn model. Django/Ubuntu/Gunicorn/Nginx
I just developed a machine learning driven python 2.7 application which essentially loads a sklearn model with joblib and predicts a given dataset. On local host the application works perfectly, but when I deploy the django application on digital ocean (Ubuntu 18., gunicorn, nginx) I get a bad gateway error. I found out that the error is being raised when the model is being loaded with joblib. What I noticed as well is that the application works perfectly when a model that has the size of 8000 bites is being loaded but that but that the bad gateway error is being raised when I try to load a model of 60000 bites. What I have tried is to resize the droplet in order to avoid that the error is being caused by a lack of computing resources, but I still get the error! Unfortunately, I have no clue how to tackle the problem. So I hope that you guys can help me to find a way to resolve this issue. I appreciate any help. Thanks in advance. Kind regards Marcel -
Edit home page on django, wagtail project on AWS
I've been asked to change something on homepage on site that is live, and it is hosted on AWS S3. It is Django project with Wagtail as CMS. I know my way around Django but not S3. Can someone explain me what to do to edit homepage.html -
How to embed images in blog post with React and Django
i'm developing a blog for a friend using React and Django, Now I have to develop the text editor that he's going to use to write the articles but I don't know what to do in case of he wanting to embed images(not uploading them to the backend but using a external source like imgur,etc) on the text field between paragraphs, I suppose that django is not going to accept an <img/> being posted to the database on a text field, so my question is: do i need to handle this on the frontend or in the backend? sorry if it is a dumb question but i've been thinking how to approach this and i can't find a way. models.py class Article(models.Model): title = models.CharField(max_length=150) text = models.TextField() created = models.DateTimeField(auto_now_add=True) -
zappa deployment: Getting [Errno 28] No space left on device: OSError. Cleaned the tmp files
Intro: I am deploying my django app using zappa on to AWS lambda. So far I have made several attempts. I feel like I may have just got it. However now I got [Errno 28] No space left on device: OSError I have so far done $ cd /tmp/ $ rm -r * This made my tmp folder empty However when I run my zappa deploy I am still getting the same error. I don't want to format my computer. Is there another way Below is my TraceBack [Errno 28] No space left on device: OSError Traceback (most recent call last): File "/var/task/handler.py", line 580, in lambda_handler return LambdaHandler.lambda_handler(event, context) File "/var/task/handler.py", line 245, in lambda_handler handler = cls() File "/var/task/handler.py", line 102, in __init__ self.load_remote_project_archive(project_archive_path) File "/var/task/handler.py", line 174, in load_remote_project_archive t.extractall(project_folder) File "/var/lang/lib/python3.6/tarfile.py", line 2010, in extractall numeric_owner=numeric_owner) File "/var/lang/lib/python3.6/tarfile.py", line 2052, in extract numeric_owner=numeric_owner) File "/var/lang/lib/python3.6/tarfile.py", line 2122, in _extract_member self.makefile(tarinfo, targetpath) File "/var/lang/lib/python3.6/tarfile.py", line 2171, in makefile copyfileobj(source, target, tarinfo.size, ReadError, bufsize) File "/var/lang/lib/python3.6/tarfile.py", line 252, in copyfileobj dst.write(buf) OSError: [Errno 28] No space left on device Can anyone advise how I can fix this -
Django Form submission leads to 404 Error
When an user submits a form, I am receiving the following error: Page not found (404) Request Method: csrfmiddlewaretoken=uaL0Ogej2bd0oSaNLXYwu1CxSPWz6mcs0PuXiwM2mpe01VecK5IVBK40xvqcFCJF&views=0&likes=0&slug=&name=do+do+ahadalfjkdas%3Bldfjksal%3B12321&submit=Create+CategoryPOST Request URL: http://127.0.0.1:8000/rango/add_category/rango/add_category/ Using the URLconf defined in tango_with_django_project.urls, Django tried these URL patterns, in this order: ^$ [name='index'] ^admin/ ^rango/ ^$ [name='index'] ^rango/ ^about/ [name='about'] ^rango/ ^category/(?P<category_name_slug>[\w\-]+)/$ [name='show_category'] ^rango/ ^page/(?P<page_name_slug>[\w\-]+)/$ [name='show_page'] ^rango/ ^add_category/$ [name='add_category'] The current path, rango/add_category/rango/add_category/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. It seems like I am appending rango/add_category twice and not re-referring back to the index page. But I am not sure what I am overlooking. Here's the relevant template: <!-- created in c7 for form viewing--> <!DOCTYPE html> <html> <head> <title>Rango</title> </head> <body> <h1>Add a Category</h1> <div> <form id="category_form" method="post" action="rango/add_category/"> {% csrf_token %} {% for hidden in form.hidden_fields %} {{hidden}} {% endfor %} {% for field in form.visible_fields %} {{ field.errors }} {{ field.help_text }} {{ field }} {% endfor %} <input type="submit" name="submit" value="Create Category" /> </form> </div> </body> </html> And the relevant forms file: #file added c7, forms from django import forms from rango.models import Page, Category … -
how to get value of download button into my django view?
I have a download button in my HTML that has a href to a path on my system for the corresponding file. How can I load that path into my view when at user clicks download? Also this value is unique for each download button. Right now I have some HTML that looks like this. How do I grab the info from item.OutputPath into my view when clicked? <div class="dashboard-2"> <div class="tasks-finished"> <h1>Finished tasks</h1> </div> <div class="tasks-list"> <table> <tr> <th>Name</th> <th>Task ID</th> <th>Status</th> </tr> {% for item in query_finished %} <tr> <td>{{ item.TaskNavn }}</td> <td>{{ item.TaskID }}</td> <td><a href="{{ item.OutputPath }}">Download</a> </tr> {% endfor %} </table> </div> </div> If there's any other way that I can do this without exposing my system path in the href I would much prefer to know that. Thanks in advance. Additonal info: I need this value because i'm trying to save it as a variable to serve protected files using Nginx. -
How to create custom django urls e.g james.john.website.com
How do I create custom django urls like james.john.website.com that links to a users profile page. I created the link by concatenating words with python, however I can't seem to figure out how to get each custom url into urls.py and how to get each custom url to link to each users custom profile. TL:DR How do I get a custom url like samantha.harvey.website.com to return a users profile page? -
Django - modal form and resubmission on page reload
I have got a modal contact form. The form works fine, but the page reload resubmits previously entered values. view.py ... if request.POST: form = ContactForm(request.POST) if form.is_valid(): entry = form.save() form = ContactForm() c.update(locals()) return render(request, 'template.html', c ) ... template.html <form action="." method="post" id="contact-form"> ... </form> I tried to clear the form in the GET request. Form fields are cleared, but this does not prevent submission on the page reload. else: #request.GET form = ContactForm() c.update(locals()) return render(request, 'template.html', c ) I have seen many examples suggesting a redirect. I do understand this approach, but in case of a modal form I would like to avoid the redirect. How to prevent modal form re-submissions? Is the redirect really the only way? -
How to get the equalent of python [:-1] in django ORM?
I am writing a django application where I want to get all the items but last from a query. My query goes like this: objects = Model.objects.filter(name='alpha').order_by('rank')[:-1] but it throws out error: Assertion Error: Negative indexing not supported. Any idea where I am going wrong? Any suggestions will be appreciated. -
Applying highlighting effect to text through replace() (Django 2.1)
I am writing a custom template filter that highlights the keyword put into the search engine in the search results page, just like in Google search results. Code for custom filter: register = template.Library() @register.filter @stringfilter def highlight(value, search_term): return value.replace(search_term, "<span class='highlight'>%s</span>" % search_term) The filter doesn't change the targeted word's CSS class into <span class='highlight'>. Instead, the output displayed text in the browser is literally <span class='highlight'>word</span>. E.g. "The most desired car brand right now is <span class='highlight'>Tesla</span>." How can I make it so that the replace() method actually changes the CSS class of the targeted word? -
How to solve Identity column missing Always error for oracle 11g, django 2.0.7?
I am using Django 2.0.7, Python 3.7 and Oracle 11g. I cannot change these configurations. Whenever I am trying to migrate my models, I always get the error, 'Missing ALWAYS' which is an error associated with Identity columns. I know that Identity columns were introduced from oracle 12. Is there a way to overcome this issue with the version requirements I have? -
How can I delete or download the needed document from folder by a clicking on webpage button?
Let's say the user cannot find the folder in the computer so it is easier to manage the folder files on webpage. I manage to show the folder file documents on webpage/Here is that webpage/, then I try to download or delete the needed document, but I get some errors. I try to use os.path.exists() and os.remove() to delete the document, but as I understand I do not create my urls pattern correctly, and do not pass the right argument to my html template. Here is my code: urls.py: .... path('edited_agreements/', views.delete_new_file, name='delete_new_file'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) views.py def new_files_list(request): path = MEDIA_ROOT new_files_list = [] for file in os.listdir(path): if file.endswith('.doc') or file.endswith('.docx'): new_files_list.append(file) return render(request, 'uploads/new_files_list.html', { 'new_files': new_files_list }) def delete_new_file(request, path): if request.method == 'POST': file_path = os.path.join(MEDIA_ROOT, path) if os.path.exists(file_path): os.remove(file_path) return redirect('new_files_list') .html .... <tbody> {% for new_file in new_files %} <tr> <td>{{ new_file }}</td> <td> <form method="post" action="{{ new_file.path }}" target="_blank"> {% csrf_token %} <button type="submit" class="btn btn-danger btn-sm">Download</button> </form> </td> <td> <form method="post" action="{{ new_file }}"> {% csrf_token %} <button type="submit" class="btn btn-danger btn-sm">Delete</button> </form> </td> </tr> {% endfor %} </tbody> .... When I click on delete I want the …