Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom permissions in Django
In Django Rest framework, we can verify permissions such as (isAuthenticated, isAdminUser...) but how can we add our custom permissions and decide what django can do with those permissions? I really want to understand what happens behind (I didn't find a documentation that explaint this): @permission_classes([IsAdminUser]) Thank you -
How to count how many times is finished function in django?
I have created a function in Django with the purpose that users download files after they fill some form. I want to count how many times is downloaded a file, now how many times is called function. And I want to show that number on my site. How do I do this? This is my function... def Only(request): page_title = 'Title' if request.method == "POST": form = Form(request.POST, request.FILES) if form.is_valid(): newdoc = request.FILES['file'] #some tasks response = HttpResponse( output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response else: form = Form() return render(request, 'only.html', { 'form': form, 'page_title':page_title }) -
switch and route does not work in full stack react-django
hello i'm learning full stack react and django and now work on routing in this my routing is not working i dont know why but my template did not show on my browser please help me My project consists of different parts, which is the React section in the front section, and in this section I have several folders The src folder in which the components are located[enter image description here][1] app.js import React, { Component } from "react"; import { render } from "react-dom"; import HomePage from "./HomePage"; import RoomJoinPage from "./RoomJoinPage"; import CreateRoomPage from "./CreateRoomPage"; import ReactDOM from "react-dom"; export default class App extends Component { constructor(props) { super(props); } render() { return <div> <p>sadiasidasipdhasip</p> </div>; } } const appDiv = document.getElementById("app"); render(<App />, appDiv); HomePage import React, { Component } from "react"; import ReactDOM from "react-dom"; import RoomJoinPage from "./RoomJoinPage"; import CreateRoomPage from "./CreateRoomPage"; import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; export default class HomePage extends Component { constructor(props) { super(props); } render() { return ( <Router> <Switch> <Route path=''> <HomePage /> </Route> <Route path='/join'> <RoomJoinPage /> </Route> <Route path='/create'> <CreateRoomPage /> </Route> </Switch> </Router> ); } } I created a component in … -
fork process under uwsgi, django
I need to execute some slow tasks upon receiving a POST request. My server runs under UWSGI which behaves in a weird manner Localhost (python manage.py runserver): when receiving request from browser, I do p = Process(target=workload); p.start(); return redirect(...). Browser immediately follows the redirect, and working process starts in the background. UWSGI (2 workers): Background process starts, but Browser doesn't get redirected. It waits until the child exit. Note, I have added close-on-exec=true (as advised in documentation and in Running a subprocess in uwsgi application) parameter in UWSGI configuration, but that has no visible effect, application waits for child's exit -
django models related manager filtering in views.py
I want to develop DJANGO application for booking rooms. The following two models are used. class suit(models.Model): iquarter = models.ForeignKey(iquarter, related_name= 'suit', on_delete=models.CASCADE) suit_no = models.IntegerField() remarks = models.CharField(max_length=100) def __str__(self): return self.remarks + ' - ' + self.iquarter.iq_name class suitbooking(models.Model): suit = models.ForeignKey(suit, related_name= 'suitbookingforsuit', on_delete=models.CASCADE) booked_for_date_from = models.DateField() booked_for_date_to = models.DateField(blank=True, null=True) booked_for_date = models.DateField(blank=True, null=True) booked_for_no_of_days = models.IntegerField(blank=True, null=True) booked_date = models.DateField(auto_now_add=True,) booked_by_officer = models.TextField(max_length=1000, default='') remarks = models.CharField(max_length=100,) class Meta: constraints = [ models.UniqueConstraint( fields=["suit", "booked_for_date"], name="unique_product_name_for_shop", ), ] def __str__(self): return self.suit.remarks To avoid assigning one room to 2 diffrent persons on any day, “ UniqueConstraint” is used. Now, how to query the list of rooms which are vacant from DATE1 to DATE2 -
Can't get css file in Django
I'm trying to get a css file in my new django application, but I keep getting errors like this: [07/Dec/2021 19:52:13] "GET /users/register HTTP/1.1" 200 4715 [07/Dec/2021 19:52:13] "GET /static/users/css/register.css HTTP/1.1" 304 0 Here is the structure of my project: register.html: {% extends '../main/layout.html' %} {% load static %} {% block styles %} <link rel="stylesheet" href="{% static 'users/css/register.css' %}"> {% endblock %} {% block content %} <div class="container"> <div class="row"> <div class="col-lg-12"> <h2>Регистрация</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Зарегистрироваться</button> </form> </div> </div> </div> {% endblock content %} settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static" ] How to fix it? -
i can't understand what is new in django 4.0?
what is new in django 4.0 ???? I am looking for release notes what is new in django-tastypie 4.0 but I can not find it. I would like to know what is new before update the package. Thanks -
Could not resolve URL for hyperlinked relationship using view name "<viewname>". ResourceRelatedField URL/pk problem (django+rest+json api)
Summary Background I am trying to implement a JSON:API-compliant general Django app to be used in various projects. I am able to generate decent JSON:API, but I only get "related"-links for one-to-one relationships (foreignkey in the model). I cannot get "related"-links to reverse relationships (other models with a foreign key pointing to my object). Thank you! //S Questions Is ResourceRelatedField the correct way to implement reverse relationship links (e.g. "related")? How do you properly use ResourceRelatedField with related_link_view_name and _url_kwarg? Specifics There are three models in the database: TopObject, Status and RelatedObject. TopObject-objects has a foreignkey status pointing to Status RelatedObject-objects has a foreignkey topobject pointing to its 'parent' TopObject-object. All of the following url's work properly when entering them manually (e.g. browser or httpie): localhost:8000/topobjects/1/relatedobjects/ (gives a list of related objects with topobject foreignkey = 1) *localhost:8000/topobjects/ (gives list, currently without reverse links. The related link for Status [direct relationship] works). *localhost:8000/topobjects/1/ (gives topobject 1, currently without reverse links. The related link for status [direct relationship] works). localhost:8000/relatedobjects/ localhost:8000/relatedobjects/1/ localhost:8000/statuses localhost:8000/statuses/1/ The view name topobject-relatedobject-list works from views when tested with print(reverse...) When related_link_view_name='topobject-relatedobject-list' is set under ResourceRelatedField, localhost:8000/relatedobjects/ and localhost:8000/relatedobjects/1/ raises a Django error. I have not figured … -
is there a way to display a particular inline in a new page based on a condition?
I need to display only one inline in a new page based on the condition like if the url has the parameter country_id then i need to display only one inline. Since I cannot make it in one ModelAdmin since the model admin has form validations in it, I used two modelAdmins for the same model. I have a readonly field called get_countries in CorporateConfig(admin which has form validations) and it will display a list of countries. If i click on a country based on that country id i need to display CorporateBrand which is an inline model to CorporateConfig on a new page(remember only that inline needs to be displayed). class CorporateConfigurationAdmin(admin.ModelAdmin): form = CorporateConfigurationAdminForm inlines = [CorporateIncludeBrandAdmin, CorporateExcludeBrandAdmin, CorporateBrandsAdmin] def get_urls(self): from django.urls import path urls = super(CorporateConfigurationAdmin,self).get_urls() filter_url = [ path('filter_brand/',self.admin_site.admin_view(self.brand_filter), name='brand-filter'), ] return filter_url + urls def brand_filter(self, request, obj=None): pass def get_countries(self, instance): country_list = '<ul style="font-weight: bold;list-style-type:circle;">' countries = Country.objects.all() print("countries", countries) for country in countries: url = reverse_lazy('admin:brand-filter') print("urls is",url) country_list += '<li class="changelist"><a href="{url}?country_id={id}" target="_blank">{country}</a></li>'.format(url=url, country=country.name,id=country.id) country_list+='</ul>' return mark_safe(country_list) get_countries.short_description = 'Country Url' Clicking on the link above should go to the custom url which is created by get_urls() class BrandOrderFilter(CorporateConfiguration): class … -
Django: Could not found exception in Traceback
I have facing some issue with python requests in a Django project. It only occur in 2nd requests.post(). Although It exited with exception TypeError: getresponse() got an unexpected keyword argument 'buffering'. But after updating urllib3. There is no exception in traceback. Traceback (most recent call last): File "/home/ubuntu/projects/project/api/views/a_view.py", line 765, in create_power_trace headers=power_trace_headers) File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/requests/api.py", line 117, in post return request('post', url, data=data, json=json, **kwargs) File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/requests/api.py", line 61, in request return session.request(method=method, url=url, **kwargs) File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/requests/sessions.py", line 542, in request resp = self.send(prep, **send_kwargs) File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/requests/sessions.py", line 655, in send r = adapter.send(request, **kwargs) File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/requests/adapters.py", line 449, in send timeout=timeout File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/urllib3/connectionpool.py", line 677, in urlopen chunked=chunked, File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/urllib3/connectionpool.py", line 426, in _make_request six.raise_from(e, None) File "<string>", line 3, in raise_from File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/urllib3/connectionpool.py", line 421, in _make_request httplib_response = conn.getresponse() File "/usr/local/lib/python3.7/http/client.py", line 1373, in getresponse response.begin() File "/usr/local/lib/python3.7/http/client.py", line 319, in begin version, status, reason = self._read_status() File "/usr/local/lib/python3.7/http/client.py", line 280, in _read_status line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1") File "/usr/local/lib/python3.7/socket.py", line 589, in readinto return self._sock.recv_into(b) File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/gunicorn/workers/base.py", line 201, in handle_abort sys.exit(1) SystemExit: 1 For your information, my code is something like this:- res1 = requests.post(url1, data=data1) result = res1.json() print(result['id']) # successfully prints data2 … -
Django - form validate images on upload
How to clean() an image with his size and extension? Image is uploading well into db, but when i'm trying to get cleaned_data it returns None. I set same looking validator on models and it works well, but only when i upload an image by adminsite. forms.py: class AdditionalInfoForm(forms.Form): first_name = forms.CharField(label='First name', max_length=20) last_name = forms.CharField(label='Last name', max_length=40) male = forms.ChoiceField(label="Male", choices=MALES, required=False) date_of_birth = forms.DateTimeField(label="Date of birth", required=False, widget=DateInput) about = forms.CharField(label='Tell us about yourself', widget=forms.Textarea(), required=False) image = forms.ImageField(label="Profile picture", required=False) def clean_image(self): avaible_formats = [ 'png', 'jpeg', 'jpg', ] img = self.cleaned_data.get('image') print(img) #always None if img: img_ext = img.name.split(".")[-1] if img.size > 4194304: raise ValidationError("Image size must be less than 4MB") if img_ext not in avaible_formats: raise ValidationError("Image extension is not avaible") return img -
Django - Show date and time of appointment
I'm currently showing all dates that appointments are not booked. from datetime import date, timedelta num_days = 5 start_date = date.today() timeframe = [start_date + timedelta(days=d) for d in range(num_days)] exclude = list(Transaction.objects.values_list("start_appointment__date", flat=True).distinct()) set(timeframe) - set(exclude) For example i have appointments booked for: [datetime.date(2021, 12, 8), datetime.date(2021, 12, 7), datetime.date(2021, 12, 7), datetime.date(2021, 12, 7)] And the dates not booked: {datetime.date(2021, 12, 10), datetime.date(2021, 12, 9), datetime.date(2021, 12, 11)} I would like to show also the available times for the not booked dates with a time interval between 11:00AM to 21:00PM:. Is that possible with the current implementation? If yes how can i achieve that? If not could you please suggest an alternative way? Thank you -
Django autoredirect to default language not work with Debug=False
I have app, with next urls.py urlpatterns += i18n_patterns( path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'), path('admin/', admin.site.urls), path('accounts/social/login/cancelled/', RedirectView.as_view(url='/')), path('accounts/', include('allauth.urls')), path('', include(cms_urls)), ) also in settings.py I setup: LANGUAGE_CODE = "de" LANGUAGES = [ ('de', _('German')), # ('en', _('English')), ] so, if DEBUG = True when I go to / url app automatically redirect me to '/de/', but if DEBUG = False - app not autoredirect me to /de, I just got 404 error How I can manage it on production with DEBUG = False? -
fetch data using ForeignKey relationship data filtering
hai stackoverflow community, i need a favour from your side to complete this one class Store_Master(models.Model): id = models.IntegerField(primary_key=True) d_code = models.CharField(max_length=50,blank = True,null = True) showroom =models.CharField(max_length=50,blank = True,null = True) short_code=models.CharField(max_length=50,blank = True,null = True) type=models.CharField(max_length=50,blank = True,null = True) flat_house_no =models.CharField(max_length=50,blank = True,null = True) street_building_name=models.CharField(max_length=50,blank = True,null = True) landmark=models.CharField(max_length=50,blank = True,null = True) pincode=models.CharField(max_length=50,blank = True,null = True) area=models.CharField(max_length=50,blank = True,null = True) taluk=models.CharField(max_length=50,blank = True,null = True) district= models.CharField(max_length=50,blank = True,null = True) state=models.CharField(max_length=50,blank = True,null = True) status=models.CharField(max_length=50,blank = True,null = True) dob=models.CharField(max_length=50,blank = True,null = True) closed=models.CharField(max_length=50,blank = True,null = True) def __str__(self): return self.showroom class edition(models.Model): id = models.IntegerField(primary_key=True) district= models.ForeignKey(Store_Master, on_delete=models.DO_NOTHING) state = models.CharField(max_length=50, blank=True,null=True) vk_daily = models.CharField(max_length=50, blank=True,null=True) vk_dhinam= models.CharField(max_length=50,blank=True,null=True) def __str__(self): return self.district help me to write views for this on. in both tables district is present I use that as a foreign key. and I have some limited districts in that district we have more showrooms I need to map that using ForeignKey my expected output is when I click district the store_master data will appear on table view. please help me to resolve this thanks in advance -
smtplib.SMTPAuthenticationError: (534, b'5.7.9 Application-specific password required
smtplib.SMTPAuthenticationError: (534, b'5.7.9 Application-specific password required. Learn more at\n5.7.9 https://support.google.com/mail/?p=InvalidSecondFactor h22sm15927247pfv.25 - gsmtp') Environment Variable are set but does not work (even though it's the exact value). I have set the app password in google account, captcha is disabled I have set the env variables in .bashrc file export EMAIL_USER='da24@gmail.com' Comparision btw the os.environ.get('EMAIL_USER') and the mail value string is True -
When i register a worker, he gets added into both client and worker group. I only want him to be added to worker grp. For client it is working fine
When i register a worker, he gets added into both client and worker group. I only want him to be added to worker grp. For client it is working fine signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.contrib.auth.models import Group from .models import Client,Worker #worker signal def worker_profile(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='worker') instance.groups.add(group) Worker.objects.create( user=instance, name=instance.username, ) print('profile created!') post_save.connect(worker_profile, sender=User) #client signal def client_profile(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='client') instance.groups.add(group) Client.objects.create( user=instance, name=instance.username, ) print('Profile created!') `post_save.connect(client_profile, sender=User`) When i register a worker, he gets added into both client and worker group. I only want him to be added to worker grp. For client it is working fine signals.py Here is the views.py file from django.http.response import JsonResponse from django.shortcuts import render, redirect from .forms import CreateUserForm, AppointmentForm from .models import * from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib.auth.models import Group from django.contrib import messages from .decorators import allowed_users, unauthenticated_user, worker_only from .forms import * from .filters import AppointmentFilter @unauthenticated_user def registerPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, 'Account was created … -
Django Youtube video download to client machine
Hi Friend I want to write python code to that video download to user machine. Now I send ajax request my view.py file and download video But my project videos file. def download_youtube_video(url): url="https://www.youtube.com/watch?v="+str(url) myVideo = YouTube(url) higest = myVideo.streams.get_highest_resolution().resolution if myVideo.streams.filter(res=higest).first().download('videos'): return True else: return False def ajax(request): if request.method == "GET": url=request.GET.get('url') if download(download_youtube_video(url)) == True: return JsonResponse(data = {"success":"Successs"}) else: return JsonResponse(data = {"success":"Error"}) -
Getting an CommandError in virtual environment in django app : You appear not to have the 'sqlite3' program installed or on your path
I am trying to create my first django website.I am using windows and visual studio code. I am following the tutorials given on their sitehere I have completed the part 1, now I want to use sqlite database. I have used the command $ python manage.py migrate Now I want to check the schema of the database created. I have tried running the command $ python manage.py dbshell But it is giving me error : CommandError: You appear not to have the 'sqlite3' program installed or on your path. I don't how to resolve. What I did? I have installed precompiled binaries from the official site. and also downloaded sqlite3.exe from the same link. Then I created a folder in my C:/ directory and included a folder SQLite and included these 3 files: sqlite3.def, sqlite3.dll and sqlite3.exe files. And also include the path of that folder into Environment Paths. Its working in a windows command prompt. But not running in virtual environment. Please suggest some solutions. -
Ran into this problem while using webbot library on python
Traceback (most recent call last): File "C:\Users\Anil\Desktop\instagram\instagram-brute-force.py", line 14, in <module> web = Browser() File "C:\Users\Anil\AppData\Local\Programs\Python\Python39\lib\site-packages\webbot\webbot.py", line 68, in __init__ self.driver = webdriver.Chrome(executable_path=driverpath, options=options) File "C:\Users\Anil\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 70, in __init__ super(WebDriver, self).__init__(DesiredCapabilities.CHROME['browserName'], "goog", File "C:\Users\Anil\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\chromium\webdriver.py", line 93, in __init__ RemoteWebDriver.__init__( File "C:\Users\Anil\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 268, in __init__ self.start_session(capabilities, browser_profile) File "C:\Users\Anil\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 359, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "C:\Users\Anil\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 424, in execute self.error_handler.check_response(response) File "C:\Users\Anil\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: cannot find Chrome binary (Driver info: chromedriver=2.39.562718 (9a2698cba08cf5a471a29d30c8b3e12becabb0e9),platform=Windows NT 10.0.19042 x86_64) -
Multithreading in Django
I'm working on a Django project, in which I will need the use of multithreading and multiprocessing concepts (Send and receive data from other servers such as PACS server/ I/O Threads... ). The question I have is Django capable of applying multithreading /multiprocessing? Can we make two tasks run simultaneously or concurrently ? Thank you -
Django + PostgreSQL: how to identify user contributions?
I'm building a Django website based on a PostgreSQL database. Identified users will be allowed to add entities through the admin. I'm looking for a way to identify which entity was added by which user, to be able to keep the information associated with the record and retrieve it later. Is it possible? The "recent actions" widget that a connected user can see in the admin suggests it is. -
Reverse for 'edit-todo' with arguments '('',)' not found. 1 pattern(s) tried: ['edit\\-todo/(?P<id>[0-9]+)/$']
I've dug around the internet and can't find a solution. Please help me lovely people of the internet. In my views.py @login_required def edit_todo(request, pk): usertodo = get_object_or_404(Todo, pk=pk) return HttpResponse('test') In my urls.py urlpatterns = [ ... path('edit-todo/<int:pk>/', views.edit_todo, name='edit-todo'), path('test/<int:pk>/', views.edit_todo, name='test'), ... ] In my template/component that's included <form hx-encoding="multipart/form-data" hx-post="{% url 'core:edit-todo' tododetail.todo.id %}" hx-target="#todo-list" method="post"> tododetail.todo.id is called because I've got an ordering table which has todo & user as foreign keys. When accessing the view directly using a test URL it works -
How to allow the user to change theme color for a bootstrap4 theme using a color picker in a django website?
I want to allow the application users to be able to change the bootstrap theme color using a color picker. I haven't found any good examples yet on how to achieve this in Django. I understand that adding predefined themes and toggling between them is simpler. But in this case, I need to allow user to select from a color picker rather than switching between few predefined templates. -
Django Channels Consumer Not Connecting to websocket
i created a websocket with javascripts on the client side...then followed up with setting up my project to handle webocket connections as follows(following the official django-channels documentation). But each time i refresh the page and watch the websocket from the browser console...its fails. i inserted an print statement in the init of the consumer class and it was printed(each time a page containing a websocket was visited or refreshed)..which mean that the routing is working fine...but for some reasons the consumer is not connecting/accepting the connection as expected to the websocket. and again there is no log in the development server as to any websocket connection process.Please can anyone help and suggest a fix. my setting.py file(relevant lines) INSTALLED_APPS = [ ... 'channels', ] ASGI_APPLICATION = 'ma_mall.asgi.application' CHANNEL_LAYERS = { "default": { 'BACKEND': "channels_redis.core.RedisChannelLayer", "CONFIG": { 'hosts': [('127.0.0.1', 6379)], } } } my asgi.py file application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": URLRouter( routing.websocket_urlpatterns ) }) my routing.py file websocket_urlpatterns = [ path("ws/notifications/", consumers.NotificationConsumer), ] my consumer file class NotificationConsumer(AsyncJsonWebsocketConsumer): groups = ['general_group'] async def connect(self): await self.accept() await self.channel_layer.group_add('notification_group', self.channel_name) await self.channel_layer.group_send('notification_group', { 'type': 'tester.message', 'tester': 'tester' } ) async def disconnect(self, close_code): await self.channel_layer.group_discard('notification_group', self.channel_name) the javascript for the … -
Removing element from for loop html django?
I have a for loop in my html to show the user their favourite games. Like this: <div class="dropdown-cart-products"> {% if user.is_authenticated %} {% for i in wishlist %} <div class="product"> <div class="product-details"> <h4 class="product-title"> <a href="{% url 'detail' i.oyunlar.platformurl i.oyunlar.slugyap %}">{{i.oyunlar.title}} {{i.oyunlar.platform}}</a> </h4> <span class="cart-product-info"> <!-- <span class="cart-product-qty">1</span>--> Anlık en ucuz Fiyatı: {{i.oyunlar.en_ucuz}} </span> </div><!-- End .product-details --> <figure class="product-image-container"> <a href="{% url 'detail' i.oyunlar.platformurl i.oyunlar.slugyap %}" class="product-image"> <img src=" {{i.oyunlar.image}}" alt="product"> </a> <a href="javascript:{document.getElementById('upvote1').submit()}" class="btn-remove" title="Favorilerden Çıkar"><i class="icon-retweet"></i></a> <form id="upvote1" method="POST" action="{% url 'favhome' i.oyunlar.game_id %}"> {% csrf_token %} </form> </figure> </div><!-- End .product --> {% endfor %} I am trying to remove element like this: form id="upvote1" method="POST" action="{% url 'favhome' i.oyunlar.game_id %}"> {% csrf_token %} </form> The problem is that I can only remove first element in this loop cannot remove the second one third one or last one. How can I change my code to remove the selected element?