Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Failed template inheritance in django templating
I am in a middle of a project. The project uses basic html at the frontend. I having trouble in template inheritance. This is the basic code : - {% extends 'main.html' %} {% block content %} <h2>Home</h4> <hr> {% if request.user.is_authenticated %} {% block home %}{% endblock home %} {% else %} {% for doc in doctor %} <div> <small>Doctors around</small> <br> <a href="{% url 'profile' doc.user.id %}"><li>{{doc.user.name}}</li></a> <br> </div> {% endfor %} {% endif %} {% endblock content %} Also the code is extended to another template. The child page is :- {% extends 'rec/home.html' %} {% block home %} <div> {% if request.user.usertype == 'p' %} <h1>Hi {{request.user.name}} </h1> {% else %} <h1>Hi {{request.user.name}} </h1> {% endif %} </div> {% endblock home %} Both the files are in the same directory. But i have defined the templates dir in settings file in a different directory. -
How Do I Improve A Huge Many-To-Many Django Query To Improve Django Speed?
I have a query set like this that I need to optimize because I think this query set slows down the website performance. The user_wishlist field is a many-to-many DB relational relationship to an Account model/table. How do I? product_wishlist_store_list = [] non_paged_products = Product.objects.prefetch_related('user_wishlist').select_related('category').filter(is_available=True).order_by('created_date') for product in non_paged_products.iterator(): # Get User Wishlist try: product_wishlist = product.user_wishlist.filter(id=request.user.id).exists() if product_wishlist: product_wishlist_store_list.append(product.id) except ObjectDoesNotExist: pass So when I turn on the log for a DEBUG purpose in Django, I see that there are nearly a thousand (0.000) SELECT queries of INNER JOIN. Does the 0.000 mean there is no hit to the database or is it? Still, seeing a thousand queries like that kind of scary to me -- I feel this code is so inefficient. Is it? -
Django rest-api - attributeerror: 'str' object has no attribute '_meta'
I'm getting the following error while running manage.py in my Django rest-api. attributeerror: 'str' object has no attribute '_meta' The traceback shows the following : '' Traceback (most recent call last): File "/home/myproject/myproject-api/manage.py", line 25, in execute_from_command_line(sys.argv) File "/home/myEnv/lib/python3.9/site-packages/django/core/management/init.py", line 419, in execute_from_command_line utility.execute() File "/home/myEnv/lib/python3.9/site-packages/django/core/management/init.py", line 395, in execute django.setup() File "/home/myEnv/lib/python3.9/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/myEnv/lib/python3.9/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/home/myEnv/lib/python3.9/site-packages/cacheops/init.py", line 18, in ready install_cacheops() File "/home/myEnv/lib/python3.9/site-packages/funcy/flow.py", line 231, in wrapper return func(*args, **kwargs) File "/home/myEnv/lib/python3.9/site-packages/cacheops/query.py", line 578, in install_cacheops opts = rel.through._meta AttributeError: 'str' object has no attribute '_meta' '' -
I am trying to create authentication system in Django. My code is failing to authenticate the user
<form method="post" action="/" class="mb-2"> {% csrf_token %} <div class="form-group"> <label for="username">Username</label> <input type="text" class="form-control" id="username" name="username" placeholder="Enter Your Username" Required> </div> <div class="form-group"> <label for="pass1">Password</label> <input type="password" class="form-control" id="pass1" name="pass1" placeholder="Enter Your Password" Required> </div> <button type="submit" class="btn btn-primary">Log In</button> </form> This is the form from home.html def home(request): if request.method == 'POST': username = request.POST.get('username') pass1 = request.POST.get('pass1') user = authenticate(username=username, pass1=pass1) if user is not None: login(request, user) return render(request,"main_tem/room.html") else: return redirect('signup') return render(request,"main_tem/home.html") this is home view from views.py in 'main' app. so as u can see from the home view if user is present or signuped it should redirect user to room.html page but when i try to do it it redirects to signup page which shouldnt happen if user is already present in data base. i am kind of lost here as i dont know what kind of solution i should search for. from what i have observed i think home view is not able to get data from the form in home.html from django.contrib import admin from django.urls import path from . import views urlpatterns=[ path("",views.home,name="home"), path("signup",views.signup,name="signup"), path("rooms",views.rooms,name="rooms"), ] for reference here is the urls.py from 'main' app -
form submission in class based view: values not adding to the database
after registering values are not adding to database and cant login views.py from django.views.generic import ListView,DetailView,CreateView,UpdateView,DeleteView,FormView from django.contrib.auth.forms import UserCreationForm class registration(FormView): form_class = UserCreationForm template_name='registration.html' success_url = '/login/?next=/' urls.py from.views import display_all,display_detail,insert_detail,update_detail,delete_task,login,registration urlpatterns = [ path('',display_all.as_view(),name='all'), path('view_detail/<int:pk>',display_detail.as_view(),name='detail'), path('insert_detail/',insert_detail.as_view(),name='insert'), path('update_detail/<int:pk>',update_detail.as_view(),name='update'), path('delete_detail/<int:pk>',delete_task.as_view(),name='delete'), path('login/',login.as_view(),name='login'), path('logout/',LogoutView.as_view(next_page='all'),name='logout'), path('registration/',registration.as_view(),name='register')] registration.html <body> <form action="" method="post">{% csrf_token %} {{form.as_p}} <input type="submit" value="register"> </form> -
Django Redirect for All Pages
I have multiple pages in my Django project. Here's my urls.py urlpatterns = [ path('page1', views.page1), path('page2', views.page2), path('page3', views.page3), ] I want to add a redirect that applies to all the pages so that users that aren't authenticated will be redirected to MSOAuth2. Here's my views.py def page1(request): return render(request, "page1.html") def page2(request): return render(request, "page2.html") def page3(request): return render(request, "page3.html") def MS_OAuth2(request): if not request.user.is_authenticated: return redirect('https://login.microsoftonline.com/tenant/oauth2/v2.0/authorize?') What regex or url pattern do I need to use so all my pages can redirect to views.MS_OAuth2? This is what I have so far but it's not working. I want the redirect to apply to all pages in my website. urlpatterns = [ path('page1', views.page1), path('page2', views.page2), path('page3', views.page3), path(r'^$', views.MS_OAuth2) ] Thank you! -
Can I control the order of Cascade Deletes in Django?
I have models like this: class Parent(models.Model): pass class Child(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) class Log(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) detail = models.TextField() I also have a signal like this: @receiver(post_delete, sender=Child) def handle_delete_child(sender, instance, **kwargs): log = Log(parent = instance.parent, detail="child deleted") log.save() Now, if I try to delete the parent, I can see with debug on that the steps are going like this: Delete parent's logs. Delete parent's children (causing new log to be written as per the signal). Try to delete parent, but fails with "Cannot delete or update a parent row: a foreign key constraint fails", I think on the log created in step 2. If I was able to specify that #2 should happen before #1, I think that would solve the problem, but I cannot find any reference to such things in the docs. Even a creative solution like a new signal or a model method override would be welcome. -
Heroku deploy "command '/usr/bin/gcc' failed with exit code 1" Error
I'm trying to deploy a Django app with Heroku, but I keep receiving these errors: Does anyone know how I could solve these issues? -
Use a SQL function in the FROM clause with the Django ORM
I need to convert the following SQL into a Django ORM query but cannot find a way to pull it off. It involves using a SQL function in the FROM clause. In this case, it's a JSONB function that will put the key/value pairs of the json field into separate columns. survey.answers is a JSONB field. The underlying database is postgres. SELECT s.id, jsonb_each_text.key, jsonb_each_text.value FROM survey as s, jsonb_each_text(s.answers); -
When I do "makemigrations" I get do "makemigrations"
I removed all migration files from my django project and now when i want to re-create i get this ./manage.py makemigrations INFO: AXES: BEGIN LOG :: [axes.apps] 2022-09-15 16:51:59,923 - /home/mixnosha/work_MVD/MVD_LTP/MVD_LTP-ltp/venv/lib/python3.10/site- packages/axes/apps.py:33 INFO: AXES: Using django-axes version 5.31.0 :: [axes.apps] 2022-09-15 16:51:59,926 - /home/mixnosha/work_MVD/MVD_LTP/MVD_LTP-ltp/venv/lib/python3.10/site- packages/axes/apps.py:34 INFO: AXES: blocking by IP only. :: [axes.apps] 2022-09-15 16:51:59,927 - /home/mixnosha/work_MVD/MVD_LTP/MVD_LTP-ltp/venv/lib/python3.10/site- packages/axes/apps.py:46 No changes detected ./manage.py migrate Operations to perform: Apply all migrations: admin, auth, axes, base_information, contenttypes, django_celery_beat, sessions Running migrations: No migrations to apply. Your models in app(s): 'admin', 'auth', 'axes', 'contenttypes', 'sessions' have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. Recommend something -
Django admin prefetch related on property
I have models Merchant and PhoneNumber. PhoneNumber has a foreign key to Merchant, and Merchant has property business_phone_number which fetches the first phone number in the set of the phone numbers. In Django admin, for the Merchant model, I have business_phone_number in list_display. Although I've put prefetch_related(phonenumber_set), it still queries PhoneNumber 100 times. What am I doing wrong? Here's the simplified code: class PhoneNumber(models.Model): ... merchant = models.ForeignKey("merchant.Merchant", on_delete=models.SET_NULL, null=True, blank=True) ... class Merchant(models.Model): ... ... @property def business_phone_number(self): number = self.phonenumber_set.first() if number: return number.phone_number return None and then in Django admin I have: @admin.register(Merchant) class MerchantAdmin(admin.ModelAdmin): list_display = ("name", "business_phone_number", ...) ... I've put in get_queryset: def get_queryset(self, request): return super().get_queryset(request).prefetch_related("phonenumber_set")... -
ManyToManyField Data not showing up
Good day, i have got a problem with adding a listing to the watchlist of a specific user. Any tips on how i could fix this? I have tried to create a seperate model and that inherits from the listing model. The model structure class Listing(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT, default='', null=True ) title = models.CharField(max_length=200) description = models.TextField() image = models.ImageField(upload_to='media/') price = models.FloatField() category = models.ForeignKey(Category,on_delete=models.CASCADE,default='') # a listing can have multiple watchers and a watcher can have multiple listings watchers = models.ManyToManyField(User,blank=True,null=True,related_name="listings") def __str__(self): return "%s" % (self.title) Code of the view def listing(request, id): comment_form = AddComment() bid_form = AddBid() listing = Listing.objects.get(id=id) if request.method == "POST": if "watchlistBtn" in request.POST: listing.watchers.add(request.user) listing.save() return render(request, "auctions/listing.html", { "listing": listing, "comment_form": comment_form, "bid_form": bid_form }) # watchlist @login_required(login_url='/login') def watchlist(request): listings = request.user.listings.all() return render(request,"auctions/watchlist.html", { "listings": listings }) The code of the form template <form action="{% url 'watchlist' %}" method="post"> {% csrf_token %} <input type="submit" value="Add to Watchlist" class="btn btn-primary" name="watchlistBtn"> </form> -
STATIC CONTENTS DOESNT DISPLAYING EVEN AFTER LOADING IT IN DJANGO
Html code of the program i have collected static files and stored it in ASSET and gave load static in every img and a tags but still didnt able to get the static files in browser {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'STYLES.css' %}"> <link rel="shortcut icon" href="{% static 'favicon-32x32.png' %}" type="image/x-icon"> <title>HOMEPAGE</title> </head> <body> <div class="TOP"> <table> <tr> <td><img class='LOGO' src="{% static 'LOGO.png' %}" alt="LOGO" width="150px" height="150px"></td> <td><p class="COMPANY">SJ-EVENTS</p></td> <td class="BUTTONS"> <ul class="BUTTONS"> <li class="LINK"><a href="{% url 'SERVICE' %}" target="_blank">SERVICES</a></li> <li class="LINK"><a href="{% url 'CONTACT' %}" target="_blank">CONTACT</a> </li> <li class="LINK"><a href="#ABOUT">ABOUT</a></li> </ul> </td> </tr> </table> </div> <br><br><br> <br><br><br> <div class="TOP1"> <p>EVENT SERVICES</p> <h1>Flawless Event Management</h1> <h2>Whether planning an in-person, virtual, or hybrid event, there is an exciting new world of opportunities available — but also new complexity.</h2> <br><br><br> </div> <img class="PICTURE1" src="{% static 'HOMEPAGE1.jpg' %}" alt="HOMEPAGE" width="1250px" height="550px"> <br><br><br><br> <hr class="LINE"> <div class="MIDDLE"> <p>Pull your event together effortlessly with expert assistance from the leading event management company.</p> <br> <p> We work behind the scenes to keep everything moving and on time for our customers. Our simplified, smart solutions make it easy for exhibitors … -
connection to /run/my.sock failed: [Errno 13] Permission denied
After I've updated code on my Django project and tried restarting the servise, I've started getting this errror: 2022-09-15 16:33:35 +0000] [695873] [INFO] Starting gunicorn 20.1.0 [2022-09-15 16:33:35 +0000] [695873] [DEBUG] connection to /run/my.sock failed: [Errno 13] Permission denied [2022-09-15 16:33:35 +0000] [695873] [ERROR] Retrying in 1 second. [2022-09-15 16:33:36 +0000] [695873] [DEBUG] connection to /run/my.sock failed: [Errno ... [2022-09-15 16:33:39 +0000] [695873] [ERROR] Retrying in 1 second. [2022-09-15 16:33:40 +0000] [695873] [ERROR] Can't connect to /run/my.sock How do I diagnose the problem? Gunicorn logs don't say what's causing it. I didn't change configs. If I maid a mistake in the project folder, it still should have started. But there's no socket file in the run folder. -
Implement Unit Test for OAuth Flow in Django app
I integrated OAuth into my Django app. OAuth has 2 steps: Redirect to OAuth provider domain name Callback to Django app with token I would like to implement TestCase units for the above flow. Here is what I wrote for testing step 1: def test_connect_with_oauth_provider(self): """Test connecting with OAuth provider.""" url = signin_url("oauth-provider") res = self.client.get(url) self.assertEqual(res.status_code, status.HTTP_200_OK) However, the test uses testcase domain not my real domain and thus the test fails. Can you please help me implement tests for both steps? Thanks! -
How do I create if statement on django template?
enter image description here If there are not projects created, projects is the name of my viewclass for my model, then I need it to create a message, but I do not know how to create the right if statement. -
How to create property methods in django models dynamically?
I am creating property methods for every model where the model attribute includes ImageField or FileField. So, I decided to make an abstract model where I check the fields in the model and if there are any ImageField and FileField in the model the property method creates it automatically by itself. I usually add '_url' to the attribute when I create the method Below is what I do usually class MyModel(models.Model): image = ImageField(...) file = FileField(...) ... @property def image_url(self): if self.image and hasattr(self.image, 'url'): return self.image.url @property def file_url(self): if self.file and hasattr(self.file, 'url'): return self.file.url ... Below what I did so far class MyModel(models.Model): ... def __new__(cls, value): fields = self._meta.get_fields() for field in fields: if isinstance(field, ImageField) or isinstance(field, FileField): ??? Any suggestions? -
Best way to handle temporary user-uploads in web-development?
Hello on the overflow, I am fairly new to web development so please don't crucify me. I am currently in the process of laying out the foundation for a web-app (using Django as backend) that will involve user uploads (blob-files). The application will perform some machine learning on the upload and present the output to the user in the browser. Once presented with the output, the user will have the option to save the upload to that particular user's subfolder in the bucket (assuming cloud storage will be used). How do I best deal with the upload while it is temporary, that is, before the user has decided to save it to storage? The above may reveal a crucial misunderstanding of mine in how the user interacts with the server, however, I can see this as one solution: Creating a temporary folder for each user in the bucket, where an upload is stored until the user either decides to save it (move to proper folder) or not to save it (delete it from temporary folder). Is this solution totally bonkers and is there a much easier one? I look forward to any replies. Sincerely, an aspiring web developer -
Static files in django when extending from template
So i am having trouble loading my static files (images) in my template when extending from my base.html, so in my base.html the static files are working for example my favicon and my style are all loading. But when i want to load an image in my charts.html it does not work. To be clear the problem lies with the barchart_coins.png file. This is my charts.html file {% extends "main/base.html" %} {% load static %} {% block title %}Charts{% endblock %} {% block subtitle %}<h1 class="h1">Welcome to your crypto wallet visualized</h1>{% endblock %} {% block content %} <img type="image/png" src"{% static "images/barchart_coins.png" %}" alt="barchart"> {% endblock %} This is my base.html file {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'main/css/style.css' %}"> <title> {% block title %}<h1>You forgot to place a title in your file<h1>{% endblock %} </title> <link rel="icon" type="image/png" href="{% static 'main/images/bitcoin_fav.png' %}"> </head> <body> <header> <nav> <ul> <li><a href="/">Home</a></li> <li><a href="/overview">Overview</a></li> <li><a href="/data">General data</a></li> </ul> </nav> </header> <div class="body"> {% block subtitle %}<h2>>ou forgot to place a subtitle in your file<h2>{% endblock %} {% block form %}<p>You forgot to … -
Array field in not storing array in django?
I'm using django. In my model i used array field. Now the problem is when i hit the api on postman with following body. I get following error. I don't know why this is happening. I'm trying to send array to store in array field but this is not happening. models.py class Booking(models.Model): user = models.ForeignKey(User, related_query_name="user_booking", on_delete=models.CASCADE) booking_hours = ArrayField(models.CharField(max_length=512),null=True,blank=True) create_time = models.DateTimeField(_("Create time"), default=timezone.now) here is body sending from postman. { "booking_hours":["12:00:00 - 13:00:00","13:00:00 - 14:00:00","14:00:00 - 15:00:00"] } response : { "booking_hours": { "0": [ "Not a valid string." ] } } serializers.py class GroundBookingSerializer(serializers.ModelSerializer): class Meta: model = Booking fields = "__all__" -
Django model field bug? "value too long for type character varying(3)" error
I am declaring two choice fields for my django model in the same manner but one of them somehow bugs into having maxlength=3. I am using a PostgreSQL database. Here is how I declare the fields: class AssignmentAd(models.Model): class FieldChoices(models.TextChoices): JFS = "JFS" JAVA = "Java" CLOUD = "Cloud" __empty__ = _('(Unknown)') class RemoteChoices(models.TextChoices): JFS = "JFS" JAVA = "Java" CLOUD = "Cloud" __empty__ = _('(Unknown)') remote = models.CharField(max_length=20, choices=RemoteChoices.choices, blank=True,) field = models.CharField(max_length=20, choices=FieldChoices.choices, blank=True,) After declaring these two fields in my model, I can create an instance through admin by choosing "JFS" for both these fields (since it is 3 chars long) but if I choose any other option that is longer than 3 chars for the remote field, I get this "value too long for type character varying(3)" error. I don't get this error for the "field" field only for the "remote" field. What gives? Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/track/assignmentad/2/change/ Django Version: 4.1 Python Version: 3.10.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'members', 'track'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) The above exception (value too long … -
How to deploy a Django+React App to Herocu?
I've tried many tutorials but I failed to deploy my application specially with handling the static files, can you recommend me a good working tutorial. Thanks alot. -
Unique together causes IntegrityError
Django==4.1 I have stipulated a unique together constraint. Then I try to check whether it really works. But I have an IntegrityError. I hoped that a unique together constraint will raise ValidationError. But it didn't happen. Could you help me understand whether I'm wrong with my supposition about ValidationError in this case. And how to cope with this problem (which method to redefine and how)? Model class Task(PriorityMixin, CommentMixin, ): # n-fipi cypher = models.CharField( max_length=255, null=False, default="", ) fipi_section = models.ForeignKey("fipi_site_sections.FipiSection", on_delete=models.CASCADE, null=False, blank=False) page = models.PositiveIntegerField(null=False, blank=False, default=0) task_description = models.ForeignKey("fipi_task_descriptions.TaskDescription", on_delete=models.CASCADE, null=False, blank=False) def __str__(self): return self.cypher class Meta: ordering = ['fipi_section', 'page', 'priority', ] constraints = [ models.UniqueConstraint(fields=['fipi_section', 'page', 'priority', ], name='fipi_section-page-priority') ] Traceback Environment: Request Method: POST Request URL: https://aux.academic.gift/whibrsp1tapre4rl/fipi_tasks/task/add/ Django Version: 4.1 Python Version: 3.10.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'isbn_field', 'general', 'fipi_exam_parts', 'fipi_exam_sections', 'fipi_site_sections', 'fipi_task_descriptions', 'fipi_tasks', 'fipi_options', 'vocabulary_sources', 'vocabulary_units', 'vocabulary_exercises', 'vocabulary_phrases', 'vocabulary_videos', 'vocabulary_options'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/g/grablmz2/aux.academic.gift/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/g/grablmz2/aux.academic.gift/venv/lib/python3.10/site-packages/django/db/backends/mysql/base.py", line 75, in execute return self.cursor.execute(query, args) File "/home/g/grablmz2/aux.academic.gift/venv/lib/python3.10/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/home/g/grablmz2/aux.academic.gift/venv/lib/python3.10/site-packages/MySQLdb/cursors.py", line 319, in _query … -
django: How add to database by loop corectly?
I am trying to save in the database all fights for a given group (everyone with everyone) at the same time from the form taking the number of rounds for each of the fights, so far the function does not add anything to the database. I am not sure if it can be added in a loop like this following the list of pairs: [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4 ), (2, 5), (3, 4), (3, 5), (4, 5)] and refer to the indexes of list items when creating combat objects to save def add_fights(request, group_id): group = Group.objects.get(pk=group_id) tournament = group.tournament participants = group.participants.all() participants_ids = participants.values('id') only_ids_ls = [i.get('id', 0) for i in participants_ids] participants_pairs = list(itertools.combinations(only_ids_ls, 2)) group.fighters_one = [p[0] for p in participants_pairs] group.fighters_two = [p[1] for p in participants_pairs] print(participants_pairs) if request.user.is_authenticated: form = AddGroupForm(request.POST) if request.method == "POST" and form.is_valid(): rounds = form.cleaned_data['rounds'] obj = form.save(commit=False) if obj: for p in participants_pairs: obj.group = group obj.rounds = rounds obj.tournament = tournament obj.fighter_one = group.participants.get(id=p[0]) obj.fighter_two =group.participants.get(id=p[1]) obj.save() print("obj") print(obj) group.fights.create(group=group, rounds=rounds, tournament=tournament, fighter_one=obj.fighter_one, fighter_two=obj.fighter_two) return HttpResponseRedirect(reverse("tournaments:tournament_details", args=[group_id])) else: form = AddFightsForm return ( render(request, "add_fights.html", context={ 'form': form, … -
Bringing Select-Option values to Select-Option
I made a drop-down field that I created with select-option, after saving the data I selected here, when I enter the update form, I want the data selected in the save form to be selected again, can you help with this? insert.html <select name="healmedy_car_info" id="healmedy_car_info" class="form-select" aria-label="Default select example"> <option value="selectcar">Lütfen Araç Seçiniz</option> <option value="34SAS20">34 SAS 20</option> <option value="34SAS30">34 SAS 30</option> <option value="34BF2904">34 BF 2904</option> <option value="34TP0633">34 TP 0633</option> <option value="34BF9529">34 BF 9529</option> </select> update.html <select name="healmedy_car_info" id="healmedy_car_info" class="form-select" aria-label="Default select example"> <option value="selectcar">Lütfen Araç Seçiniz</option> <option value="34SAS20">34 SAS 20</option> <option value="34SAS30">34 SAS 30</option> <option value="34BF2904">34 BF 2904</option> <option value="34TP0633">34 TP 0633</option> <option value="34BF9529">34 BF 9529</option> </select> I pull the data with django and save it to the database, I just want the data I pulled here to be selected in update.html.