Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Regex Pattern to allow alphanumeric and square brackets with text insde it
i am using regex to allow alphanumeric, underscore, hyphen and square brackets in a text box. regex i am using to validate input is r'^[a-zA-Z0-9_\-\[\] ]*$. i need to modify the regex such that if empty brackets are given it should return false. Sample cases "Your message here" - Valid "Your [text] message here" - Valid "your_text_message [text]" - valid "Your [] message here" - Invalid "[] message" - Invalid -
django-simple-history How display related fields in the admin panel?
I use django-simple-history.I keep the historical table of the product and the price, the price is associated with the product and an inlane is added to the admin panelю I want to display in the admin panel in the product history records of the stories of related models (price). How can I do this? And that the fields changed would be displayed my model class Product(models.Model): article = models.PositiveIntegerField() history = HistoricalRecords() class Price(models.Model): prod = models.OneToOneField( Product,) price_supplier = models.FloatField() history = HistoricalRecords() my admin class PriceInline(admin.TabularInline): model = Price class ProductAdmin(SimpleHistoryAdmin): inlines = [ PriceInline,] admin.site.register(Product, ProductAdmin) enter image description here enter image description here I tried to set it up via history_view() and get_history_queryset() to receive objects of another model and I received them, but I do not understand how to embed them in the render so that both changes in the product model and changes in the price model would be reflected, and at the same time the fields that changed were corresponding to their models. or is there another method to achieve this result -
How can I paginate by month in vue.js?
I write a project in django and vue.js. In vue.js I have this: <div class="row"> <div class="col-xl-4 col-sm-6 mb-3" v-for="object in personWorkingScheduleData" :key="object.id"> <div class="card mb-5 h-100" style="border:1px solid #eff2f7; padding: 12px; height: 300px;"> <div class="card-body"> <div class="row"> <div class="col-lg-3"> <div class="text-lg-center"> <div class="mt-3"> <label>Night time</label> <b-form-checkbox :checked="object.is_night_shift" @input="object.is_night_shift = $event" :disabled="!object.can_change" class="mb-3 custom-checkbox" plain></b-form-checkbox> </div> </div> </div> <div class="col-lg-9"> <div> <div class="mt-3"> <label>Days</label> <multiselect :disabled="!object.can_change" required :options="weekdayOptions" :value="extractWeekdays(object.weekdays)" track-by="id" label="weekday" multiple placeholder="Choose days" selectLabel="Choose day" selectedLabel="selected" :max-height="200" @input="handleMultiselectChange($event, object)"> </multiselect> </div> <div> <ul class="list-inline mb-0"> <li class="list-inline-item me-3"> <h5 class="font-size-14" data-toggle="tooltip" data-placement="top" title="From" > <label class="mt-3">From*</label><br> <i class="bx bx-calendar me-1 text-muted"> <b-form-input class="no-border" :value="object.start_date" :disabled="!object.can_change" @input="object.start_date = $event" id="example-input" type="date" placeholder="YYYY-MM-DD" autocomplete="off"></b-form-input> </i> </h5> </li> <li class="list-inline-item me-3"> <h5 class="font-size-14" data-toggle="tooltip" data-placement="top" title="To" > <label class="mt-3">To*</label><br> <i class="bx bx-calendar me-1 text-muted"> <b-form-input class="no-border" :value="object.end_date" :disabled="!object.can_change" @input="object.end_date = $event" id="example-input" type="date" placeholder="YYYY-MM-DD" autocomplete="off"></b-form-input> </i> </h5> </li> </ul> </div> <ul class="list-inline mb-0" v-if="object.start_time && object.end_time"> <li class="list-inline-item me-3"> <h5 class="font-size-14" data-toggle="tooltip" data-placement="top" title="From" > <label>Start time</label> <br /> <i class="bx bx-time me-1 text-muted"> <b-form-input class="no-border" :value="object.start_time" :disabled="!object.can_change" @input="object.start_time = $event" format="HH:mm" value-type="format" type="time" placeholder="hh:mm"></b-form-input> </i></h5> </li> <li class="list-inline-item me-3"> <h5 class="font-size-14" data-toggle="tooltip" data-placement="top" title="From" > <label>End time</label> <br /> <i class="bx … -
Testing concurrency ability of a Django app
Let's suppose I have a Django app named MyApp in which I have a Django model called MyModel. This model has a method called process. The database is Postgresql so it allows concurrent queries. What I need to do is to test if the MyModel.process() method can run simultaneously without problem. So, in my tests, when I do class test_smtg(TestCase): def setup(self): self.my_model = MyModel() self.my_model.save() def test_single_processing(self): self.my_model.process() It processes successfully. However, when I do this instead: import threading class test_smtg(TestCase): def setup(self): self.my_model = MyModel() self.my_model.save() def test_concurrent_processing(self): thread = threading.Thread(target=self.my_model.process) thread.start() It immediately reports me an error, such that the ID of my_model cannot be found in table myapp_mymodel. Why is that? Why is the program not able to see the object in the database while running on a separated thread? And what can I do to still test if the concurrency works whitout crashing my tests? -
How to fetch data with the given order from the database ? (django)
I have a model in which there are different fields of data, and a field of "section-order" is given. now i want to fetch that data into the bootstrap accordians with respect to the "section-order". **MODELS ** model.py image VIEWS views.py code on the home page, once the user clicks on any link it reidrects to the casestudy page. -
Undoing a migration for a duplicate field
We have had a duplicate field added to of our Django Wagtail models which has confused the migration system. The following was added to one of the models while back along with a migration that added a singular instance of the field: stream = fields.StreamField( who_fund_blocks, blank=True, verbose_name="Additional content", ) stream = fields.StreamField( who_fund_blocks, blank=True, verbose_name="Additional content", ) This all seemed to be fine, and the project continued with new fields and migrations being added elsewhere without any problem. Then the duplicate field was spotted and removed from the models page. Now, if we try to add a field on some model and a migration for it, the migration is created but doesn't complete, although there are no errors that directly imply it has failed: (.venv) development ➜ app 🐟 manpy migrate /root/.cache/pypoetry/virtualenvs/.venv/lib/python3.10/site-packages/wagtail/utils/widgets.py:10: RemovedInWagtail70Warning: The usage of `WidgetWithScript` hook is deprecated. Use external scripts instead. warn( System check identified some issues: WARNINGS: ?: (urls.W005) URL namespace 'freetag_chooser' isn't unique. You may not be able to reverse all URLs in this namespace ?: (urls.W005) URL namespace 'pagetag_chooser' isn't unique. You may not be able to reverse all URLs in this namespace ?: (urls.W005) URL namespace 'sectiontag_chooser' isn't unique. You may not … -
Gunicorn Error: ModuleNotFoundError - No module named 'weatherapp.wsgi'
I'm having some trouble deploying my Django application on Heroku using Gunicorn, and I could really use some assistance. Here's some background information about my project: Project Name: weatherapp Procfile web: gunicorn weatherapp.wsgi:application --log-file - wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'weatherapp.settings') application = get_wsgi_application() Error Message Traceback (most recent call last): File "/app/.heroku/python/lib/python3.12/site-packages/gunicorn/arbiter.py", line 609, in spawn_worker ... ModuleNotFoundError: No module named 'weatherapp.wsgi' Relavent code in settings.py WSGI_APPLICATION = 'content_aggregator.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) django_heroku.settings(locals()) MEDIA_URL = '/imgs/' MEDIA_ROOT = BASE_DIR / 'imgs' It seems like Gunicorn is unable to locate the weatherapp.wsgi module during the deployment process. I've double-checked my project structure and everything seems to be in order. Could anyone please provide some guidance on what might be causing this issue and how I can resolve it? Any help would be greatly appreciated. Thanks in advance! Started the Gunicorn server with the command gunicorn weatherapp.wsgi:application --log-file -. But no changes -
Mulitple summernote instances
I have a web page were I have multiple summernote instances in it. I have 4 textareas with different ids. I run $("textarea").each(function () { $(this).summernote({ height: 240, toolbar: [ ['font', ['bold', 'underline', 'clear']], ['para', ['ul', 'ol']], ['insert', ['link']], ['view', ['help']] ] }); }); code to convert textareas to summernote instances. Now I want to access code of a specific one. How to do so? For further information my backend is django and textarea's are generated by multiple forms. The only difference is the form I have will not send the request to the backend using a regular html form. Instead I'm trying to send the request using axios. Note when I try to access textarea's value using it's id: let description = $("#{{ form_invoice.description.auto_id }}").val(); or let description2 = $("#{{ form_brand.description.auto_id }}").val(); I always get the first form's description on the page. -
Django Allauth Google Sign-In not working
I am trying to get a custom form to work with Google via the django-allauth[socialaccount] package but when clicking on the Google Sign-In button, I am getting the ?process=login query string appended to the URL, but nothing else. I have followed the examples available in the official repo and in particular this partial template that I copied in part in my own template: {% load i18n %} {% load allauth %} {% load socialaccount %} {% get_providers as socialaccount_providers %} {% if socialaccount_providers %} {% if not SOCIALACCOUNT_ONLY %} {% element hr %} {% endelement %} {% element h2 %} {% translate "Or use a third-party" %} {% endelement %} {% endif %} {% include "socialaccount/snippets/provider_list.html" with process="login" %} {% include "socialaccount/snippets/login_extra.html" %} {% endif %} My template: {% extends "base.html" %} {% load allauth socialaccount %} {% load i18n %} {% block body_class %}bg-white rounded-lg py-5{% endblock %} {% block content %} <div class="flex justify-center items-center min-h-screen"> <div class="card w-96 bg-base-100 shadow-xl"> <div class="card-body"> {% get_providers as socialaccount_providers %} {% if socialaccount_providers %} {% include "socialaccount/snippets/provider_list.html" with process="login" %} {% include "socialaccount/snippets/login_extra.html" %} {% endif %} </div> </div> </div> {% endblock content %} views.py from django.shortcuts import render from … -
Heroku Postgres database error: "server does not support SSL, but SSL was required"
I am trying to enable pgbouncer to experiment with managing number of connections to my app. I followed this guide, but am seeing the following error when the app hits the database. connection to server at "127.0.0.1", port 6000 failed: server does not support SSL, but SSL was required My Procfile is as follows: web: bin/start-pgbouncer-stunnel gunicorn backend.wsgi release: python manage.py migrate The error does not appear when I omit the bin/start-pgbouncer-stunnel part In settings.py, I have my DATABASES variable configured like this: if env.get("DJANGO_DEVELOPMENT"): DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "OPTIONS": { "service": env.get("DATABASE_SERVICE"), }, } } else: DATABASES = { "default": dj_database_url.config( conn_max_age=500, ssl_require=True ) } However, I notice that the error page lists the DATABASES variable, and this includes sslmode': 'require: DATABASES {'default': {'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_HEALTH_CHECKS': False, 'CONN_MAX_AGE': 600, 'ENGINE': 'django.db.backends.postgresql', 'HOST': '127.0.0.1', 'NAME': 'db1', 'OPTIONS': {'sslmode': 'require'}, 'PASSWORD': '********************', 'PORT': 6000, 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIGRATE': True, 'MIRROR': None, 'NAME': None}, 'TIME_ZONE': None, 'USER': 'zvchpwwqszbgax'}} Have I configured something incorrectly? I assume that Heroku enables SSL for the attached Postgres database, and see it as "required" seems like the correct setting is enabled. -
Cannot access LoadBalancer service of Django deployment on EKS cluster
I have a containerized Django application that was successfully deployed (imperatively) to an EKS cluster. I've used the following commands: kubectl create deployment announcements --port=127 --image=public.ecr.aws/x7a1r0o7/announcements-dev --port=127 [gunicorn exposes the container on port 127. If I exec into the pod, it works, and a curl for localhost:127 gives me the html of the page] Then I create the service using kubectl expose deployment/announcements --type=LoadBalancer --port-127 I tried different ports like 80 and 8000 when exposing the deployment. I've also verified that the Pod has the files and the internal curl shows the application is running. For some reason, when I kubectl get svc and use the external IP (an AWS ELB web address) I am unable to see the application. Nothing is served. Any insight would be appreciated. -
django not showing RAW SQL with sqlmigrate
I'm trying to get the RAW SQL from a migration and it only prints begin and commit. I'm modify a model, adding the middle_name field class User(AbstractBaseUser): email = models.EmailField(max_length=200, blank=False, unique=True) first_name = models.CharField( max_length=200, blank=False, verbose_name="nombre" ) middle_name = models.CharField( max_length=200, blank=True, verbose_name="segundo nombre" ) It creates the migration 0007_user_middle_name.py # Generated by Django 3.2.23 on 2024-06-10 16:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('biglifeapp', '0006_biglifesetting_new_field'), ] operations = [ migrations.AddField( model_name='user', name='middle_name', field=models.CharField(blank=True, max_length=200, verbose_name='segundo nombre'), ), ] but when I run python manage.py sqlmigrate my_app 0007 --database=default it only prints `BEGIN; -- -- Add field middle_name to user -- COMMIT; this should print something like `BEGIN; -- -- Add field middle_name to user -- alter table user add column middle_name (...) COMMIT; I saw 2 questions on stackoverflow, but none of those was the case for this case, the db does indeed change, I'm adding a new column to it For some migrations, why `sqlmigrate` shows empty, or the same SQL both directions? in this case, the --database argument is being provided Django sqlmigrate not showing raw sql -
Telegram mini app with django issue with transferring data
i've faced with problam that i don't know how to connect mini app to user's telegram_id. I'm new with this tecknologie, and dont know how to do this. I try to use django on this project and the problam is that i dont know how to safely transfer collected data from runbot.py to views.py.Could anybody help me? -
django flatpages will show only one page
I'm trying to use flatpages in my Django application. I installed it properly as far as I can see and created 2 pages. Using the shell, when I try: >>> from django.contrib.flatpages.models import FlatPage >>> FlatPage.objects.all() <QuerySet [<FlatPage: /pages/en-US/about/privacy/ -- Privacy Policy>, <FlatPage: /pages/fr-FR/about/privacy/ -- Politique de Confidentialité>]> I can see my 2 pages. But in a template, I'm using: {% get_flatpages as about_pages %} {% for page in about_pages %} <a class="navbar-item" href="{{ page.url }}">{{ page.title }}</a> {% endfor %} And there I can see only the last page. Also when I access directly the first page using it's full URL (http://127.0.0.1:8000/pages/fr-FR/about/privacy/) it displays nicely but when I try the same with the other one (http://127.0.0.1:8000/pages/en-US/about/privacy/) I get a 404. I tried to change the name of the first page, but nothing works. Any idea??? -
Naming an abstract model Django
What is the standard for naming Django abstract classes? My team leader insists that the name of the abstract model should consist of the fields available in it. for example, IsPublishedAndCreatedAt. But My class: class BaseContentProperties(models.Model): is_published = models.BooleanField() created_at = models.DateTimeField() class Meta: abstract = True class Category(BaseContentProperties): ... class Location(BaseContentProperties): ... class Post(BaseContentProperties): ... But if there are more fields, then the name will be more, for example, IsPublishedAndCreatedAtAndPublishedAt.... Who is right?) If there are some generally established recommendations on this issue, you can send a link so that you can familiarize yourself. Thanks I described my problem above -
Double model creation after payment in django website
I am currently working on Learning management course using Django and React .I am creating payment gateway using stripe . After the payment is successfully done , the courses should be called enrolled courses and a model of it created after payment . But for some issue , double course model gets created after payment for each course purchased. I don't know the issue in code. I have attached the code of payment and model created .enter image description here enter image description here enter image description here I tried to pay using stripe and get the enrolled course created of that course. But duplicate (double) enrolled course created for some reason. -
How to get fields names that were chosen with method "only()"?
For example, I have simple model: class Person(models.Model): id = models.BigAutoField("id", primary_key=True) first_name = models.CharField(max_length=150) surname = models.CharField(max_length=150) age = models.IntegerField() I use method only to choose fields I need: queryset = Person.objects.all().only("first_name", "age") How can I get fields names("first_name", "age") that were chosen? I tried this: queryset.query.get_loaded_field_names() But I got this error: AttributeError:'Query' object has no attribute 'get_loaded_field_names' -
js files in the admin
I load some js files in the admin using a custom admin site, let's call it custom_admin_site.html. In this template I override some blocks: {% extends "admin/base_site.html" %} {% load i18n static %} {% block extrahead %} <link rel="shortcut icon" href="{% static 'images/favicon.ico' %}" /> <script src="{% static 'admin/src-min-noconflict/ace.js' %}" referrerpolicy="no-referrer"></script> <script src="{% static 'js/htmx.min-1.9.11.js' %}"></script> {% endblock %} When I use these libraries, on the main page (/admin) they work just fine. When I override other templates, for example I have: projectname \ templates \ admin \ appname \ modelname \ change_form.html: {% extends "admin/change_form.html" %} {% load i18n admin_urls %} ... and I cannot access my libraries form here. Do I need to add something like this in my 'change_form.html`? {% block extrahead %} {{ block.super }} {% endblock %} or can I somehow make sure that other htmls also use my extended custom_admin_site.html and not the normal admin/base_site.html? Or am I approaching this the wrong way and should I define a Media subclass with the js files in the admin.py where it is needed? -
ModuleNotFoundError: No module named 'fullstackcap'
I am doing some cleaning up on a recent project and all of a sudden when running the project, the terminal spits out the error in the title. I was also trying to figure out and environment variable error as well. wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fullstackcap.settings') application = get_wsgi_application() settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'fullstackcapapi', ] # UPDATE THIS MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'fullstackcap.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'fullstackcap.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True … -
Execute callback when django.cache.set timeout is exceeded
I use Django cache with django-redis==5.0.0 like this: cache.set(f'clean_me_up_{id}', timeout=10) Storing an entry into cache, which will be cleared after timeout, works perfectly for me. What I´m trying to acheive, is to execute also some cleanup code (as a callback?) when the cache is deleted. Is there some easy way to do this as it would be extremely helpful. -
graphene-django get_node vs get_queryset
I'm currently getting acquainted with graphene-django and there's one aspect of it I'm not quite getting my head around. I would like to let my users use GraphQL to query our database. I would like them to be able to filter their results by attribute values, so I am providing my models as a ThingNode with filter_fields and interfaces = (relay.Node, ) rather than as a ThingType. Now, all examples I could find tell me to overload get_node() if I want to interact with the output, for instance in order to check for the user's permissions. However my implementation, as I have it working now, never gets past get_node(), but instead uses get_queryset(). I've looked into existing packages that offer permission management, such as django-graphene-permissions but this also hooks into get_node(). I am now unsure if I should just put my permission checks into ThingNode.get_queryset() instead, or is the fact that my code deviates from all the examples I find means that I'm setting this up the wrong way altogether. If anyone could give me some hints on this I'd be massively grateful! -
Error while installing scikit-learn with pip : Preparing metadata (pyproject.toml) did not run successfully
I try to install scikit-learn==1.2.2 for the django project and I got this error. Collecting scikit-learn==1.2.2 Using cached scikit-learn-1.2.2.tar.gz (7.3 MB) Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... error error: subprocess-exited-with-error × Preparing metadata (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [36 lines of output] Partial import of sklearn during the build process. Traceback (most recent call last): File "D:\Group Project Backend\Prediction\env\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 353, in <module> main() File "D:\Group Project Backend\Prediction\env\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 335, in main json_out['return_val'] = hook(**hook_input['kwargs']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Group Project Backend\Prediction\env\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 149, in prepare_metadata_for_build_wheel return hook(metadata_directory, config_settings) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-_ej3exwe\overlay\Lib\site-packages\setuptools\build_meta.py", line 366, in prepare_metadata_for_build_wheel self.run_setup() File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-_ej3exwe\overlay\Lib\site-packages\setuptools\build_meta.py", line 487, in run_setup super().run_setup(setup_script=setup_script) File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-_ej3exwe\overlay\Lib\site-packages\setuptools\build_meta.py", line 311, in run_setup exec(code, locals()) File "<string>", line 669, in <module> File "<string>", line 663, in setup_package File "<string>", line 597, in configure_extension_modules File "C:\Users\ASUS\AppData\Local\Temp\pip-install-xv622fd3\scikit-learn_6df30b226b524d1caf236a6b94005795\sklearn\_build_utils\__init__.py", line 47, in cythonize_extensions basic_check_build() File "C:\Users\ASUS\AppData\Local\Temp\pip-install-xv622fd3\scikit-learn_6df30b226b524d1caf236a6b94005795\sklearn\_build_utils\pre_build_helpers.py", line 82, in basic_check_build compile_test_program(code) File "C:\Users\ASUS\AppData\Local\Temp\pip-install-xv622fd3\scikit-learn_6df30b226b524d1caf236a6b94005795\sklearn\_build_utils\pre_build_helpers.py", line 38, in compile_test_program ccompiler.compile( File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-_ej3exwe\overlay\Lib\site-packages\setuptools\_distutils\_msvccompiler.py", line 343, in compile self.initialize() File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-_ej3exwe\overlay\Lib\site-packages\setuptools\_distutils\_msvccompiler.py", line 253, in initialize vc_env = _get_vc_env(plat_spec) ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-_ej3exwe\overlay\Lib\site-packages\setuptools\msvc.py", line 230, in msvc14_get_vc_env return _msvc14_get_vc_env(plat_spec) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-_ej3exwe\overlay\Lib\site-packages\setuptools\msvc.py", line 187, in _msvc14_get_vc_env raise distutils.errors.DistutilsPlatformError("Unable to find … -
How to Filter by Status in Django Rest Framework with Square Brackets in Query Params
I'm encountering an issue with filtering a model by status in Django Rest Framework. Here's my current setup: When I filter using status=1,14, it works perfectly: class DepartmentFilter(filters.FilterSet): search = filters.CharFilter(method='filter_search') status = filters.CharFilter(method='filter_status') class Meta: model = Department fields = ['search', 'status'] def filter_search(self, queryset, name, value): print("filter_search", value) return queryset.filter(Q(token__icontains=value)) def filter_status(self, queryset, name, value): print("filter_status", value) # Verificar que el filtre s'executa if value: status_values = value.split(',') return queryset.filter(status__id__in=status_values) return queryset However, I'm having trouble capturing the query parameter when I use status[]=1,14. I've tried the following without success: status = filters.CharFilter(method='filter_status[]') status = filters.CharFilter(method='filter_status%5B%5D') There doesn't seem to be a way to create a function to capture this. Resolving status[] is a first step because ultimately, I want to work with the call filters[status][] = 1,14. I haven't found a way to handle this. Can anyone provide some guidance? Thank you! -
facing issues with python module installation
i am gettinig error as : ModuleNotFoundError: No module named 'currency_converter' i installed by command: pip3 install currency_converter after instaltion show succesfull, even showing madule as exit on checking by: pip3 show currency_converter after that use migration command then its show same error as abobe Migration: python3 manage.py makemigrations please help -
how to fix bad request error in platform.sh
im learning web deployment using platform.sh. i pushed my files to platform.sh by command "platform push" and then supposed to get my live url by commanding "platform url" i got some list of urls but in the browser it is showing error 502 "bad gateway" i tried every thing from checking internet connections, updating CLI,DNS etc. is there any command im missing or any pushing issues? help out guys. this is routes.yaml # Each route describes how an incoming URL will be processed by Platform.sh. "https://{default}/": type: upstream upstream: "ll_project:http" "https://www.{default}/": type: redirect to: "https://{default}/" expection! when i commanded "platform url" after "platform push", im supposed to get some list of urls and chose 1 out of them to be my web address according to the book "python crash course by erric maththes" latest edition page no 456. But i was promted 4 urls and no option to select. when i copied all the urls in my brave browser i got error 502 "bad request" in every site.