Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django server calls Google pay API refund
I can't find an open API for Google Pay that I can interact with from my Django server to make automated refunds for my customers who have bought some items but want a refund. I am investigating Google Pay API, but I can't find an open API that I can interact with from my django server. What I need is to make an automated refund for my customer, who have bought an item but wants a refund. -
Django rest framework error when trying to loggin(Authenticate) via post request
Anytime I make a post request to this login route at http://127.0.0.1:8000/api/login/ I keep getting this error in postman, despite providing the right credentials. "detail": "CSRF Failed: Origin checking failed - chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop does not match any trusted origins." Same post request from an android app also gives me cors errors. I use these decorators @api_view(['GET','POST']). It works well without the decorators though. This is also my path declaration : path('login/',csrf_exempt(api_views.login),name='api_login'), How can I login? I expect a login success with user information as response -
How to save an in memory Excel file to a Django models.FileField
I am trying to save an Excel file that is built in memory to a Django models.FileField but get the error message: "'XlsxWriter' object has no attribute 'read'". Here are the steps I follow: Data are first extracted from Django models. The data is saved temporarily in a pandas DataFrame. When completed, the Dataframe is transferred to an Excel file. The final step would be to save the Excel file to a models.FileField. This is the last step I have a problem with. Here are the problematic lines of code with the error message I get: file = File(excel_file) doc.document.save(file_name, file, save=True) 'XlsxWriter' object has no attribute 'read' I suspect the solution might lie with the usage of io.BytesIO but I cannot figure out how. Here are more details on my code: models.py class DocuPlan(models.Model): plan = models.ForeignKey(Plan, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=True) doc_type = models.IntegerField( _('Document type'), choices=DocuPlanType.choices, default=DocuPlanType.OTHER ) date_order = models.DateField(null=True, blank=True) date_published = models.DateField(null=True, blank=True) is_public = models.BooleanField(_('Public document'), default=False) **document = models.FileField( upload_to=docu_plan_directory_path, max_length=100, null=True, blank=True)** date_filed = models.DateTimeField(auto_now_add=True) file_name = models.CharField(max_length=150, null=True, blank=True) views.py def dataExtraction(request, pk): template = 'basic/form_data_extraction.html' plan = Plan.objects.get(pk=pk) context = {} form = DataExtractionForm(request.POST or None, request=request, plan=plan) … -
AttributeError: module 'rest_framework.serializers' has no attribute 'Booleanfield'
I'm trying to create a boolean field serializer and i get this error i tried to make it default is false and did not work is_follower = serializers.Booleanfield(default=False) -
ModuleNotFoundError: No module named 'timescale.fields'
I have downloaded django-timescaledb but when i run server, the following error is displayed in terminal: ModuleNotFoundError: No module named 'timescale.fields' from django.db import models from django.contrib.auth import get_user_model import uuid from datetime import datetime from django.utils import timezone from django.db.models import F from django.utils.timezone import now from timescale.fields import TimescaleDateTimeField User = get_user_model() class TimescaleModel(models.Model): """ A helper class for using Timescale within Django, has the TimescaleManager and TimescaleDateTimeField already present. This is an abstract class it should be inheritted by another class for use. """ time = TimescaleDateTimeField(interval="1 day") class Meta: abstract = True Terminal error message -
NoReverseMatch at / Reverse for 'athlete_profile' with keyword arguments '{'pk': ''}' not found
i'm trying to make a page where i can display an athlete's profile to them by using their primary key as a refernce but i get an error as follows: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.1.7 Python Version: 3.11.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'events', 'userty'] 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'] Template error: In template C:\SHRUTI\SEM_6\PROJECT\COMBAT_CON_F\templates\base.html, error at line 81 Reverse for 'athlete_profile' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['users/profile/athlete/(?P<pk>[0-9]+)/\\Z'] 71 : </head> 72 : <body> 73 : <nav> 74 : <div> 75 : <a href="{% url 'home' %}">Combat-Con</a> 76 : </div> 77 : <div> 78 : <a href="{% url 'events:event_list' %}">Events</a> 79 : {% if user.is_authenticated %} 80 : {% if user.is_athlete %} 81 : <a href=" {% url 'userty:athlete_profile' pk=athlete.pk %} ">Athlete Profile</a> 82 : {% elif user.is_host %} 83 : <a href="{% url 'userty:host_profile' pk=user.host.pk %}">Host Profile</a> 84 : {% endif %} 85 : <a href="{% url 'userty:user_logout' %}">Logout</a> 86 : {% else %} 87 : <a href="{% url 'userty:register' %}">Register</a> 88 : <a href="{% url 'userty:login' %}">Login</a> 89 : {% endif %} 90 : </div> 91 : </nav> Traceback (most … -
Django - Moving from one category post to the next and back
There is a model and posts attached to it. I can not figure out how to make the transition from the active post to the next and back. I read many articles, but I did not find the right one for me. Here is my code. How can this be done? HTML <div class="bootons-navigation"> <span class="span__bootons-navigatiom"><a href="#" title="previous">previous</a></span> <span class="span__bootons-navigatiom"><a href="#" title="next">next</a></span> </div> Models class home(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('URL')) title = models.CharField(max_length=250) top_description = models.TextField(max_length=700, blank=False) class Meta: verbose_name = 'Главная' verbose_name_plural = 'Главная' def __str__(self): return self.title class category(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('URL')) description = models.TextField(max_length=700, blank=False) def __str__(self): return self.slug def get_absolute_url(self): return reverse('category', kwargs={'category_slug': self.slug}) class post(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('URL')) description = models.TextField(max_length=700, blank=False) cat = models.ForeignKey('category', on_delete=models.PROTECT, null=True) def __str__(self): return self.slug def get_absolute_url(self): return reverse('post', kwargs={'post_slug': self.slug}) Views def content_category(request, category_slug): categorypost=category.objects.filter( slug=category_slug) get_list_or_404(categorypost, slug=category_slug) return render(request, 'content/season.html',{ 'category':categorypost, }) def content_post(request, category_slug, post_slug): postpages = post.objects.filter(slug=post_slug, cat__slug=category_slug) get_object_or_404(postpages, slug=post_slug, cat__slug=category_slug) return render(request, 'content/post.html', { 'post': postpages, }) URLS path('', views.ContentHome.as_view(), name='homepage'), path('\<slug:category_slug\>', views.content_category), path('\<slug:category_slug\>/\<slug:post_slug\>', views.content_post)` -
How to start with no formsets and generate form whenever a button / dropdown item is clicked?
Given the following form: class MyForm(forms.Form): my_field = forms.CharField( max_length=255, widget=forms.TextInput( attrs={'placeholder': 'My field', 'class': 'form-control'} ), label='', ) When used with a formset_factory in this way, it generates a minimum of 1 form which is visible whenever the corresponding url is access. def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) match self.request.method: case 'GET': context['formset'] = formset_factory(MyForm)() case 'POST': context['formset'] = formset_factory(MyForm)(self.request.POST) return context and this is how the template looks like: <form method="post"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form.my_field }} {% endfor %} <button class="btn btn-success" type="submit">Create</button> </form> results in: What do I need to modify if I don't need the form to show up at all, without explicitly hiding it? I want to start with something like this / a dropdown menu with different form types: <button class="btn btn-success" type="button">Generate form A</button> <button class="btn btn-success" type="button">Generate form B</button> and each button generates a different form. I don't want any initial forms to show up, just the buttons, what would be a clean way to do it? -
Periodic tasks in Django are not called
I use django_crontab to periodically call my tasks. The problem is that periodic tasks are not called. I created a test function that sends me a message and I can understand that the task is done: def test_crj(): send_message("Test cronjobs!") I set it to run once every five minutes: # in settings.py INSTALLED_APPS = [ ... , "django_crontab", ] CRONJOBS = [ ("*/5 * * * *", "project.cronjob.test_crj", '>> /tmp/test.log'), ] crontab sees it: > docker exec container python3.9 manage.py crontab show # Currently active jobs in crontab: # a35573388f4e46c33f88fc825f0a1d8f -> ('*/5 * * * *', 'project.cronjob.test_crj', '>> /tmp/test.log') > docker exec container crontab -l # */5 * * * * /usr/local/bin/python3.9 /app/manage.py crontab run a35573388f4e46c33f88fc825f0a1d8f >> /tmp/test.log # django-cronjobs for project But nothing happens! Meanwhile, when I run the function independently, everything works fine. And when I run it the way the system crontab should run (as I understand it), it works too. > docker exec container python3.9 manage.py crontab run a35573388f4e46c33f88fc825f0a1d8f # it works What could be the error and who is to blame - django_crontab or the system crontab? Or where and how do I look at the logs, why it doesn't work? -
Django filter for ManyToMany items which exist only in a specified list
I have the following: class Category(): category_group = models.ManyToManyField("CategoryGroup", blank=True, related_name="category_group") class CategoryGroup(): label = models.TextField(null=True, blank=True) categories = Category.objects.exclude(category_group__label__in=["keywords_1", "keywords_2"] I wish to exclude the categories whose group label exists in either keywords_1 or keywords_2 only. If a category group label exists in keywords_1 and keywords_3 I do not want to exclude it. What changes are needed for this query? -
Unique value in django model field
I have the following code: from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Employee(models.Model): employee = models.OneToOneField(User, on_delete=models.CASCADE) executive_head = models.BooleanField( default=False, help_text=_("e.g. Chief Executive Officer or Managing Director."), ) job_title = models.CharField(max_length=100) def __str__(self): return f"{ self.employee }" What I would like to see is that only one value should be true in the executive_head field. It should not be possible to have more than one executive head. Using unique_together in the class Meta does not work (in hindsight it should not) because the false values would then not be unique. Any ideas? -
Django ForeignKey prevent creation when parent is a child
I have the following model: class PostModel(models.Model): post = models.ForeignKey('self', on_delete=models.CASCADE, related_name='posts') I can create new posts like this: post_1 = PostModel.objects.create() Or new posts with a parent post: post_2 = PostModel.objects.create(post=post_1) I want to know if it's possible for a post to have only a parent which itself doesn't have a parent. So the following wouldn't be allowed: post_3 = PostModel.objects.create(post=post_2) # post_2 has a parent, prevent creation -
Django FileDescriptor in settings
In my Django project, I want to use the MaxMind db file to acquire information about IP-addresses. The file takes up to 90 megabytes. I expect about 50 requests per second and also the application will be hosted on the Gunicorn with 3 workers. So, Will I meet the limits if I open a file every request? with maxminddb.open_database('GeoLite2-City.mmdb') as mmdb: info = mmdb.get('152.216.7.110') return Response({'city': info.city, 'other': 'some_other_information_about_ip'}) or should I open the file in settings.py once: mmdb = maxminddb.open_database('GeoLite2-City.mmdb') and use this descriptor in my views.py ? from django.conf import settings .... info = settings.mmdb.get('152.216.7.110') return Response({'city': info.city, 'other': 'some_other_information_about_ip'}) I am concerned about several problems: If 2 workers will try to read the file simultaneously, where might be conflicts. The File descriptor will not be properly closed if the application fails. What is best practice for Django apps to keep files in memory. -
Access the files that are being sent via a PATCH request inside of Django middleware
I have written a Django middelware class that I used to access the files that are being uploaded and do some stuff. I have used rest_framework package to enable some API enpoints. When I try to do a POST request with an uploaded file, I can access that file by calling request.FILES. However, if I do a PATCH request with a file, request.FILES is empty. Instead the file is inside of the request.body as a byte stream. What do I have to do to access the file using request.FILES in a patch request? Middleware: class MyMiddleware: def __init__(self, get_response): # noqa: D107 self.get_response = get_response def __call__(self, request): if request.FILES: for key, file in request.FILES.dict().items(): # Do some stuff pass response = self.get_response(request) return response I tried to parse the request with rest_framework's MultiPartParser but no luck. Thanks in advance! -
I want to make password field in my model by the inheriting AbstractBaseUser, but it shows me the error about non-nullable iid field
It is impossible to add a non-nullable field 'id' to client without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit and manually define a default value in models.py. models.py from django.contrib.auth.models import AbstractBaseUser from django.db import models class Client(AbstractBaseUser): username = models.CharField(max_length=200) password = models.CharField(max_length=200, default="") def __str__(self): return self.username -
Django custom database field - psycopg2.errors.SyntaxError: syntax error at or near "None"
I've created a custom fields called RelativeURLField that inherits the CharField from django.db.models.CharField. from django.db import models from django.core.validators import RegexValidator class RelativeURLField(models.CharField): default_validators = [RegexValidator( regex=r'^(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)', message='Enter a valid URL.', code='invalid_url' )] When replacing the URLField in the model with this custom field. I get this error psycopg2.errors.SyntaxError: syntax error at or near "None" LINE 1: ...onal_investor" ALTER COLUMN "website_url" TYPE varchar(None) This is the part that is causing the error in the migration script migrations.AlterField( model_name='institutionalinvestor', name='website_url', field=accounts.fields.RelativeURLField(blank=True, default='', null=True), ), I've tried giving the field a default value by editing the AlterField part. However, the same issue persists. -
If .env file is not included in git then how the prod deployment works in ec2 , how the prod code gets access to variables?
.env is included in gitignore ,then how do the prod code know the values. I think that the jenkins handle this in order to maintain security , but please someone let me know how this works .Since i dont have much knowledge on devops side. -
list index out of range IndexError at /en/dashboard/edit-server-request/2/
So i'm trting to edit a form and while submission it shows: IndexError at /en/dashboard/edit-server-request/2/ list index out of range this is the views.py def edit_server_request(request, pk): server_request = get_object_or_404(ServerRequest, pk=pk) mediator = server_request.mediator teachers = server_request.teachers.all() if server_request.teachers.exists() else None TeacherFormSet = formset_factory(TeacherForm, extra=1, formset=BaseTeacherFormSet) if request.method == "POST": server_request_form = ServerRequestForm(request.POST, instance=server_request) mediator_form = MediatorForm(request.POST, instance=mediator) teacher_formset = TeacherFormSet(request.POST, prefix='form') if all([server_request_form.is_valid(), mediator_form.is_valid(), teacher_formset.is_valid()]): print('All forms are valid') server_request = server_request_form.save(commit=False) mediator = mediator_form.save() server_request.mediator = mediator server_request.user = request.user server_request.save() # Delete any existing teachers that were removed from the form existing_teachers = set(teachers) new_teachers = set() for form in teacher_formset.forms: teacher = form.save(commit=False) if teacher.name: teacher.server = server_request new_teachers.add(teacher) for teacher in existing_teachers - new_teachers: teacher.delete() # Save the new teachers for form in teacher_formset.forms: teacher = form.save(commit=False) if teacher.name: teacher.server = server_request teacher.save() else: print('One or more forms are invalid') else: server_request_form = ServerRequestForm(instance=server_request) mediator_form = MediatorForm(instance=mediator) initial_data = [{'name': teacher.name, 'contact': teacher.contact} for teacher in teachers] if teachers else None teacher_formset = TeacherFormSet(prefix='form', initial=initial_data) context = { 'server_request_form': server_request_form, 'mediator_form': mediator_form, 'teacher_formset': teacher_formset, } forms.py class ServerRequestForm(forms.ModelForm): """ Server request form for schools This uses a three way chained dependent dropdown for province, district … -
Using related_name in Django Template
I have two models: Usecase and Usecase_progress. I'm creating a page where I can see a list of all the use cases with their information + the usecase progress for each use case. Usecase model: class Usecase(models.Model): usecase_id = models.CharField(primary_key=True, max_length=20) usecase_name = models.CharField(max_length=256) user_email = models.ForeignKey('User', models.DO_NOTHING, db_column='user_email') usecase_type = models.ForeignKey('UsecaseType', models.DO_NOTHING) kpi = models.ForeignKey(Kpi, models.DO_NOTHING) business_owner = models.ForeignKey(BusinessOwner, models.DO_NOTHING) usecase_description = models.CharField(max_length=5000) usecase_creation_date = models.DateField() estimated_date = models.DateField() usecase_priority = models.CharField(max_length=100) usecase_git = models.CharField(max_length=512, blank=True, null=True) current_phase = models.ForeignKey(Phase, models.DO_NOTHING) delivery_date = models.DateField() class Meta: managed = False db_table = 'usecase' usecase progress model: class UsecaseProgress(models.Model): usecase_progress_date = models.DateTimeField(primary_key=True) usecase = models.ForeignKey(Usecase, models.DO_NOTHING, related_name='usecaseids') phase = models.ForeignKey(Phase, models.DO_NOTHING) pipeline = models.ForeignKey(Pipeline, models.DO_NOTHING) usecase_progress_value = models.IntegerField() estimated_date_delivery = models.DateField(db_column='Estimated_Date_Delivery') My views.py: @user_login_required def view_usecase(request): usecase_details = Usecase.objects.all() context = {'usecase_details': usecase_details} return render(request, 'ViewUsecase.html', context) My template: {% extends 'EmpDashboard.html' %} {% block body %} {% if usecase_details is not none and usecase_details %} <div class="col-12 mb-4"> {% for result in usecase_details %} <div class="card border-light shadow-sm components-section d-flex "> <div class="card-body d-flex "> <div class="row mb-4"> <div class="card-body"> <div class="row col-12"> <form> <div class="mb-4"> <h6 class="fs-5 fw-bold mb-0 border-bottom pb-3">{{result.usecase_id}} - {{result.usecase_name}}</h6> <div class="mb-0 mt-2">{{result.usecase_description}}</div> </div> <div class="form-row … -
Why can't I access start_utc? All I want to do is print it once the serializer is initialized
See code Here PROBLEM: def start_utc() -> datetime: return timezone.make_aware( datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0), timezone.utc ) def get_serializer_context(self): print(self.start_utc()) # start_utc() takes 0 positional arguments but 1 was given The error I'm getting when I run this is: start_utc() takes 0 positional arguments but 1 was given I tried: def start_utc(self) print(self.start_utc(self) Nothing worked so far -
Can't see my tables in Google Cloud SQL (PGSQL) but connection is ok
I am developing an application. Everything was going well locally, I now want to create a first postgre SQL database and connect it to django. I established the connection in the Django settings and perform the migrations, it's ok. But I don't see anything on the google cloud SQL console (I have the correct permissions). However, the tables were created, I see it thanks to the VSCODE extension. here's some informations settings.py [...] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PWD'), 'HOST': 'config('DB_HOST')', 'PORT': '5432', 'OPTIONS': { 'sslmode': 'verify-ca', #leave this line intact 'sslrootcert': os.path.join(BASE_DIR, config('CERT_SERVEUR')), "sslcert": os.path.join(BASE_DIR, config('CERT_CLIENT')), "sslkey": os.path.join(BASE_DIR, config('CERT_KEY')), } } } [...] I can see my tables, in my database, in my instance staging-01 But in my Google console, I don't see anything and I can only "delete" my database I configured my IP address in Public IP to test and I embed the certificates. Migrations and table creation seem to be ok. I don't know much about networking. and for example, when I try to create a user with Djoser, I have an error: net::ERR_CONNECTION_REFUSED. Everything was going well locally. I continue to launch with manage.py runserver but I would … -
Primary Key varchar - no detection of model changes
PostgreSql database, Django 4. I have a problem with detecting data model changes to a migration file. I am trying to add my primary key of type varchar which has format dddddd-ddd in the model. The field definition itself looks like this : mid = models.CharField(max_length=10, primary_key=True, verbose_name='custom ID'), Unfortunately, after creating the migration file, you can't see the mid field, but there is an id. To test the correctness of the makemigrations itself, I added the phone1 field, which is already detected and has coverage in the migration. Here is my model class Report(ModelBaseClass): mid = models.CharField(max_length=10, primary_key=True, verbose_name='custom ID'), created_user = models.ForeignKey(User, on_delete=models.PROTECT, editable=False, verbose_name='Przyjmując') client = models.ForeignKey(Client, on_delete=models.PROTECT, verbose_name='Klient') email = models.EmailField(null=True, blank=True, verbose_name='E-mail') phone = models.CharField(max_length=20, null=True, blank=True, verbose_name='Telefon') phone1 = models.CharField(max_length=20, null=True, blank=True, verbose_name='Telefon') comment = models.TextField(max_length=1000, blank=True, verbose_name='Uwagi do zgłoszenia') registration_date = models.DateField(auto_now_add=True, verbose_name='Data przyjęcia') ending_date = models.DateTimeField('Data zakończenia', null=True, blank=True) And an excerpt from the migration file. migrations.CreateModel( name='Report', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_date', models.DateTimeField(auto_now_add=True)), ('modified_date', models.DateTimeField(auto_now=True)), ('email', models.EmailField(blank=True, max_length=254, null=True, verbose_name='E-mail')), ('phone', models.CharField(blank=True, max_length=20, null=True, verbose_name='Telefon')), ('phone1', models.CharField(blank=True, max_length=20, null=True, verbose_name='Telefon')), ('comment', models.TextField(blank=True, max_length=1000, verbose_name='Uwagi do zgłoszenia')), ('registration_date', models.DateField(auto_now_add=True, verbose_name='Data przyjęcia')), ('ending_date', models.DateTimeField(blank=True, null=True, verbose_name='Data zakończenia')), ('client', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='organize.client', verbose_ … -
Passing two arguments in reverse
return HttpResponseRedirect(reverse("listing", args=[auction_id, commentForm])) The path in urls.py is: path("<int:auction_id>/listing", views.listingPage, name="listing"), The listingPage definition function: def listingPage(request, auction_id, commentForm = None): My experience throws this error: NoReverseMatch at... Reverse for 'listing' with arguments '(3, )' not found. 1 pattern(s) tried: ['(?P<auction_id>[0-9]+)/listing\Z'] I have no problem passing 1 arg: return HttpResponseRedirect(reverse("listing", args=[auction_id,])) -
python/ Django values_list is not returning all values
I have this bit of ugly code that is producing what I want. It's working but only necessary because what I would like to do with values_list is not working. member_channels = Channel.objects.filter(Q(members=request.user) | Q(owner=request.user)).prefetch_related('members').prefetch_related('owner') members_nested = list(map(lambda channel: channel.members.all(), member_channels)) members = list(dict.fromkeys(itertools.chain(*members_nested))) owners = list(map(lambda channel: channel.owner, member_channels)) # this is all the user's who's comment's the request.user should be able to see. valid_comment_users = list(dict.fromkeys(members + owners)) What I would like to do and should work is: member_channels = Channel.objects.filter(Q(members=request.user) | Q(owner=request.user)).prefetch_related('members').prefetch_related('owner') member_ids = member_channels.values_list('members', 'owner', flat=True) valid_comment_users = AppUser.objects.filter(id__in=member_ids).distinct() The issue is that with values_list I'm not getting all the members for each Channel in the members_channels it seems like it's only returning the members that are the same in all channels, or maybe just the first member I can't tell. Any insight into why values_list isn't working for this? -
How to remove all duplicates and similiar quieries from Django admin
I have a lot different models in my project and in every of them there`s a duplicated sql quieries I want to know how to remove them but the main problem is that in one model when im trying to take a look on single object of this model i have like 5k sql queries I also tried to for loop all of information from this model in my template and still got ~5k queires how does it work? models.py class PresenceSectionList(models.Model): presence_detail = models.ForeignKey(PresenceDetailInfo, on_delete=models.CASCADE) presence_sections = models.ForeignKey(CleanSections, blank=True, on_delete=models.CASCADE, null=True) class Meta: verbose_name = 'Раздел с информацией' verbose_name_plural = 'Разделы с информацией' ordering = ['presence_detail', ] def __str__(self): return f'{self.presence_detail}' admin.py class PresenceSectionListAdmin(admin.ModelAdmin): list_display = ('presence_detail', 'presence_sections') ordering = ['presence_detail__presence_info', 'presence_detail__work_date'] admin.site.register(PresenceSectionList, PresenceSectionListAdmin) Amount of sql queries