Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django model save operation not creating on default database
I have two databases defined: 'default': { 'ENGINE': 'django.db.backends.postgresql', 'USER': 'app-api-master', 'PASSWORD': 'sdf', 'HOST': 'localhost', 'NAME': 'ev_offshore_bkup' }, 'onshore_db': { 'ENGINE': 'django.db.backends.postgresql', 'USER': 'app-api-master', 'PASSWORD': 'sdf', 'HOST': 'localhost', 'NAME': 'ev_onshore_bkup' } In the model: def save(self, *args, **kwargs): kwargs['using'] = 'default' super().save(*args, **kwargs) NoTice I've commented these #kwargs['using'] = 'onshore_db' #super().save(*args, **kwargs) In the viewset: with transaction.atomic(): self.serializer_class = self.create_serializer_class created_user = viewsets.ModelViewSet.create(self, request, *args, **kwargs) created_user_id = created_user.data['id'] The create() only saves the record in onshore_db immediately and doesn't consider the default db. Even after commenting the onshore_db configuration, when I run the app, I find that the new model objects are created in onshore_db only and no records in default db. What could be the reason? There's also a db-router defined: def get_db_name(): cache_data = {} db = 'default' request = get_current_request() try: user_id = request.session._session_cache['_auth_user_id'] cache_data = cache.get(user_id, {}) except Exception as e: return db if cache_data.get('CLIENT_DB_NAME', None): db = cache_data.get('CLIENT_DB_NAME') return db class MatrixDBRouter: # TODO encrypt db name where data from onshore def db_for_read(self, model, **hints): return get_db_name() def db_for_write(self, model, **hints): return get_db_name() def allow_relation(self, obj1, obj2, **hints): return True def allow_migrate(self, db, app_label, model_name=None, **hints): return True But this only returns the default … -
How do we update pip to it's latest version
A new release of pip is available: 23.2.1 -> 24.0 [notice] To update, run: python.exe -m pip install --upgrade pip By running provided command i am unable to update pip to it's latest version. it's showing the following error upon running the command " python.exe -m pip install --upgrade pip" ERROR: Could not install packages due to an OSError: [WinError 5] Access is denied: 'C:\Python311\Lib\site-packages\pip\init.py' Consider using the --user option or check the permissions. please help to solve the above mentioned problem -
The same uuid is generated for different objects in Django
When I run server on localhost I am able to add new objects in my postgre database through Django admin panel, but only one for every table. When I try to add second new object, it assigns the same uuid that has already been used. There is an example of model with uuid as primary key: models.py from django.db import models from authuser.models import User from django.utils import timezone import uuid class Thread(models.Model): idthread = models.UUIDField(default=uuid.uuid4(), primary_key=True, unique=True) date_created = models.DateTimeField(default=timezone.now) userid = models.ForeignKey(User, on_delete=models.DO_NOTHING) name = models.CharField() def __str__(self): return self.name Only after restarting the server it will assign new unique uuid to object that I would like to add. -
How to implement dual authentication (email and phone number) in Django Rest Framework?
I'm building a Django Rest Framework (DRF) application and I need to implement dual authentication, allowing users to sign in using either their email or mobile number. What is the best approach to implement this? I've already set up the authentication system using email, but now I need to extend it to support mobile number authentication as well. Should I create a custom authentication backend, or is there a DRF package that can help me achieve this more easily? I'd appreciate any advice or examples on how to implement dual authentication in DRF. Thank you! -
ModuleNotFoundError: No module named 'psycopg2' while makemigrations on postgres DB
I cloned a github project on Django and i was following the instructions to execute the program. I am new so, i went ahead and downloaded postgres and installed it. at the make migrations step, this error was logged along with bunch of paths :- ModuleNotFoundError: No module named 'psycopg2' i was following the steps given in the documentation file for this which are as follows : " Installing the Postgres and enabling it in the background We will go to telusko\settings.py in the project folder Around line 78, there's DATABASES dictionary, we will set the value for keys ('NAME', 'USER' & 'PASSWORD') to 'postgres' Then we'll execute python3 manage.py makemigrations & python3 manage.py migrate Finally, we will run the project by python3 manage.py runserver " i followed the steps, at the 3rd step, instead of 'postgre' as the password, i typed in the password asked at the installation process BUT at the 4th step when i run the python3 manage.py makemigrations this error is shown: ModuleNotFoundError: No module named 'psycopg2' i want this project somehow working till tomorrow so please help -
How to Submit Separate Actions from a Single Form Tag? (Django)
I have written the following code where a submit action with the value {{category.name}} unexpectedly triggers the "create" button in form_category, resulting in a "Please enter a name" message. This approach worked fine in a previous project using the same logic. I've confirmed that the urls.py is properly set up. What could be the issue? <form method="POST"> {% csrf_token %} category name: {{ form_category }} <input type="submit" value="create" formaction="{% url 'mk_category' %}"> <span> | </span> {% for category in categories %} <input type="submit" value="{{category.name}}" formaction="{% url 'index_with_category' category.id %}"> {% endfor %} </form> Thank you very much for your help! Wrapping each submit button in separate form tags resolves the issue. However, I plan to continue using multiple submit buttons within a single form in the future. I have checked urls.py multiple times and found no issues. Please help me with this. -
Django Python - How to Query this
I have this Consumer model class ConsumerModel(models.Model): GENDER_LIST = ( ('male','MALE'), ('female','FEMALE'), ("lgbt",'LGBT') ) REGISTER_AS = ( ('consumer','CONSUMER'), ('manager','MANAGER') ) uid = models.CharField(max_length=8) # remove the default value some time profile_id = models.UUIDField() user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=40) birthdate = models.DateField(null=True,blank=True) mobile_number = models.CharField(max_length=12, null=True, blank=True) gender = models.CharField(max_length=20,choices=GENDER_LIST,null=True,blank=True) profile_image = models.ImageField(null=True,blank=True,upload_to="images/") register_as = models.CharField(null=True, blank=False,choices=REGISTER_AS, max_length=12) def __str__(self): return self.user I have this view where I want to look/print for the Consumer with the following user but it returns and error: serializer = ConsumerLoginSerializer(data=request_data) if serializer.is_valid: try: user = User.objects.get(email=request_data["email"]) except: return Response(data={'status': wrong_input, 'message':wrong_body_vals_msg, 'errors':{"Email":"User not found"}}) print("PROFILE ID: " + ConsumerModel.objects.get(user=user)) return Response(data={"status": ok, 'message': "Success"}, status=ok) -
Embedded react component disable select text on other html elements
I am trying to include a react component in a django template which contains non-react content. My template contains the following code: {% load static %} <!DOCTYPE html> <html> <body> <h1>This text CAN NOT be selected</h1> <h2>React app</h2> <div id="react1"></div> <!-- this is the component that the react component will live in. --> <script src="{% static js %}" defer></script> <!-- js is a variable pointing to the main.XXXXX.js file. --> </body> </html> The variable js refers to the build/static/js/main.XXXXX.js-file build using npm run build and served using django. The index.js file (in react) simply add a component to the div: import React from 'react'; import { createRoot } from 'react-dom/client'; import App2 from './App2'; if(document.getElementById("react1") != null){ const root = createRoot(document.getElementById('react1')); root.render( <App2 /> ); } The component (App2.js) is a very simple hello-world example. The page renders correctly (the app is a simple counter app) as shown in the screenshot so all files are up-to-date. As can be seen I can select/interact with the application, but I cannot select the text defined in the tag (and more importantly, events such as button clicks outside of react are not triggered etc.). The React counter-app works as expected. I have googled … -
Cannot index models from Django to Elasticsearch
I have a Django project where we're going to use Elasticsearch for a full-text search. I have a task to connect it with the existing Django project. The first thing I found django-elasticsearch-dsl package. I did everything like in tutorial and all worked fine, but the idea was in using elasticsearch-dsl. I don't understand how to create indexes right now. If in django-elasticsearch-dsl the only thing I need is to run python3 manage.py search_index --rebuild inside Django container, but here I have no idea. I store all code in documents.py. documents.py from elasticsearch_dsl.connections import connections from elasticsearch_dsl import Document, Text connections.create_connection(hosts=['http://elasticsearch:9200']) class FilmWorkDocument(Document): title = Text() description = Text() class Index: name = 'film' FilmWorkDocument.init() first = FilmWorkDocument(title='Example1', description='Example description') first.meta.id = 47 first.save() docker-compose.yml elasticsearch: image: elasticsearch:8.13.0 container_name: elasticsearch environment: - "ES_JAVA_OPTS=-Xms200m -Xmx200m" - discovery.type=single-node - xpack.security.enabled=false ports: - 9200:9200 Sending a request http://localhost:9200 shows that everything is ok. { "name" : "eeb958274241", "cluster_name" : "docker-cluster", "cluster_uuid" : "wUQjIKoLTNGKtFH7A1tzSw", "version" : { "number" : "8.13.0", "build_flavor" : "default", "build_type" : "docker", "build_hash" : "09df99393193b2c53d92899662a8b8b3c55b45cd", "build_date" : "2024-03-22T03:35:46.757803203Z", "build_snapshot" : false, "lucene_version" : "9.10.0", "minimum_wire_compatibility_version" : "7.17.0", "minimum_index_compatibility_version" : "7.0.0" }, "tagline" : "You Know, for Search" } But after … -
Django works perfectly on a local machine, but doesn't work in production
Django works perfectly on a local machine, but has errors with Postgres in production (I am using the same postgres DB in prod and locally). Django server hosted on Railway gives me this: Settings (WORKS PERFECTLY ON A LOCAL MACHINE WITH THIS IN-PROD DATABASE AND SAVES DATA): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASSWORD'), 'HOST': os.getenv('DB_HOST'), 'PORT': os.getenv('DB_PORT'), } } DATABASE_URL = os.getenv('DATABASE_URL') .env: DATABASE_PRIVATE_URL={{DATABASE_PRIVATE_URL}} DATABASE_URL={{DATABASE_URL}} DB_HOST=viaduct.proxy.rlwy.net DB_NAME=railway DB_PASSWORD={{DB_PASSWORD}} DB_PORT=19232 DB_USER=postgres SECRET_KEY={{SECRET_KEY}} Proof for local server working: Postgres server logs (local machine): -
que aplicaciones desplegar en heroku
el problema es que tengo una aplicacion en python y django que usa conexiones web socket con cnannels y daphne, el asunto es si heroku permite el uso de estas conexiones ya adquiri una suscripcion en pythonAnywhere y me toca cancelarla porque no admiten estas conexiones y me vine a dar cuenta ya con los errores que arrojaba despues de estar en el servidor. si, si se permite este tipo d conexion en heroku quiciera que me dieran un enlace donde expliquen bien como se configuran en esete servidor heroku y si no entoces que proveedor de servicios puedo contratar para el uso de esta aplicacion, recuerden aplicacion desarrollada en django y python con conexiones websocket usando chanels y daphne con BD mysql probe en pyrhonAnywhere y quede viendo un chispero -
Automate e2e test with selenium of Django app in gitlab cicd -Error: selenium.common.exceptions.WebDriverException: neterror?e=dnsNotFound
This is the output of my cicd pipline which is failing base/tests/e2e_tests/test_register.py F [100%] =================================== FAILURES =================================== _____________ TestRegistrationPage.test_register_valid_credentials _____________ self = <test_register.TestRegistrationPage testMethod=test_register_valid_credentials> def test_register_valid_credentials(self): """ Test whether the registration process works flawlessly. This method asserts that after sucessful redirect url equals home. """ > self.driver.get("http://secprog:8080/") FAILED base/tests/e2e_tests/test_register.py::TestRegistrationPage::test_register_valid_credentials - selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?e=dnsNotFound&u=http%3A//secprog%3A8080/&c=UTF-8&d=We%20can%E2%80%99t%20connect%20to%20the%20server%20at%20secprog. Stacktrace: RemoteError@chrome://remote/content/shared/RemoteError.sys.mjs:8:8 WebDriverError@chrome://remote/content/shared/webdriver/Errors.sys.mjs:193:5 UnknownError@chrome://remote/content/shared/webdriver/Errors.sys.mjs:832:5 checkReadyState@chrome://remote/content/marionette/navigate.sys.mjs:58:24 onNavigation@chrome://remote/content/marionette/navigate.sys.mjs:330:39 emit@resource://gre/modules/EventEmitter.sys.mjs:148:20 receiveMessage@chrome://remote/content/marionette/actors/MarionetteEventsParent.sys.mjs:33:25 This is my Dockerfile: # Stage 1: Build stage FROM python:3.12.0b2-alpine3.17 RUN apk update WORKDIR /app COPY . . EXPOSE 8080 CMD ["python", "manage.py", "runserver", "0.0.0:8080"] This is my .gitlab-ci.yml. in my build stage everything works fine and it gets passed. The problem is in my run_e2e_test. I don't know where my error is. I assume that there is a problem with how i define the alias for the services, but i don't know how the to services can communicate with each other: stages: - unit_tests - build - integration_tests - static_code_analysis - start_server - sec_vuln_assessment - e2e_tests run_build: stage: build image: docker:20.10.16 services: - docker:20.10.16-dind variables: DOCKER_TLS_CERTDIR: "/certs" before_script: # login working, but -p is unsecure. try --password-stdin - docker login registry.mygit.th-deg.de -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD script: - docker build -t registry.mygit.th-deg.de/pk27532/secprog . - docker … -
user.username shows incorrect information about the logged in user name
views.py def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Account has been updated') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) users/profile.html <h1>{{ user.username }}</h1> <h2>{{ user.email }}</h2> <img src="{{ user.profile.image.url }}" width="200" style="border: 3px solid black;"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ u_form }} {{ p_form }} <button type="submit">Update profile</button> </form> When I submit form with username that already exists, it shows error "A user with that username already exists", but user.username field is equal to that invalid existing username, but in database nothing changes. Also if this field doesn't pass any validators then it also shows this invalid data. I expected {{user.username }} to remain the same as in the database and as the logged in user's data -
How to import and use Django models inside new process outside views.py
I have some models inside 'models.py' inside 'app1' : ... class ChitaMoney(models.Model): chita_market = models.CharField( verbose_name=_('chita market name'), max_length=20 ) ... my 'views.py' calls a function from 'multy.py' from 'core' directory inside 'app1' 'multy.py' startes a new infinite process . when the process whants to import the models: from ..models import ChitaMoney this happens: Process chita_main: Traceback (most recent call last): File "C:\Users\David\AppData\Local\Programs\Python\Python312\Lib\multiprocessing\process.py", line 314, in _bootstrap self.run() File "C:\Users\David\AppData\Local\Programs\Python\Python312\Lib\multiprocessing\process.py", line 108, in run self._target(*self._args, **self._kwargs) File "D:\Django\JaNext_Boos_1\app1\core\multy.py", line 160, in chita_main_thread ins_l_t, ins_l_a = chita_init(chita_dtt) ^^^^^^^^^^^^^^^^^^^^^ File "D:\Django\JaNext_Boos_1\app1\core\multy.py", line 112, in chita_init from ..models import ChitaMoney File "D:\Django\JaNext_Boos_1\app1\models.py", line 5, in class ChitaStock(models.Model): File "d:\Django\JaNext_Boos_1.venv\Lib\site-packages\django\db\models\base.py", line 129, in new app_config = apps.get_containing_app_config(module) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "d:\Django\JaNext_Boos_1.venv\Lib\site-packages\django\apps\registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "d:\Django\JaNext_Boos_1.venv\Lib\site-packages\django\apps\registry.py", line 138, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Django==5.0.4 any help would be appreciated I had same problem without process importing models in top of .py files and after I import the models inside functions, I could use the models. But inside new process ... -
I'm getting a 503 error when I upload an image to a pre-trained model and try to get output using python + Django on a shared web host
Background: *Beginner here. * I made a simple app with some basic models and trained it to distinguish happy and sad faces. I made this and ran it in a local development server with Django which worked perfectly and I was even able to display the image after getting a non-logged-in user to upload. Then, I tried uploading the app to a non-local server. This server is part of a shared web hosting package and has cPanel. The app works fine till I upload the image and then it shows a 503 error. The server resource logs show that usage spikes when I upload the image and it is fed into the pre-trained neural network but nothing that would overpower the limits, only 75% of server physical memory being used. Server Specs: Server Specs TLDR: Uploaded a Django app with an Image Classification model which shows a 503 error after uploading the image from the front-end. Error Logs: 2024-05-05 16:03:28.355186: I external/local_tsl/tsl/cuda/cudart_stub.cc:32] Could not find cuda drivers on your machine, GPU will not be used. 2024-05-05 16:03:28.359620: I external/local_tsl/tsl/cuda/cudart_stub.cc:32] Could not find cuda drivers on your machine, GPU will not be used. 2024-05-05 16:03:28.396387: I tensorflow/core/platform/cpu_feature_guard.cc:210] This TensorFlow binary is … -
django uploaded images from admin panel not displayed in the homepage
i created a django project to upload images both from the user interface and from the admin panel. but when uploading images from user interface, the images are not uploaded to the media folder.and also not shown in the homepage. but when uploading from the admin panel, the images are uploaded to the media folder correctly but in the home page the images are not shown. this problem is with the images only. other fields are correctly displayed like the title, price aand so on. tell me how to fix my issue. these are my code snippets. user interface uploading code <div class="layout__body"> <form class="form" action="" method="POST" enctype="multipart/form-data" > {% csrf_token %} <div class="form__group"> <label for="post_category">Enter a Category</label> <input required type="text" value="{{post.category.name}}" name="category" list="category-list" /> <datalist id="category-list"> <select id="post_category"> {% for category in categories %} <option value="{{category.name}}">{{category.name}}</option> {% endfor %} </select> </datalist> </div> <div class="form__group"> <label for="post_name">Post Title</label> {{form.title}} </div> <div class="form__group"> <label for="post_image">Post Image</label> {{form.image}} </div> <div class="form__group"> <label for="post_price">Post Price</label> {{form.price}} </div> <div class="form__action"> <a class="btn btn--dark" href="{{request.META.HTTP_REFERER}}" >Cancel</a > <button class="btn btn--main" type="submit">Submit</button> </div> </form> views.py for post creation @staff_member_required @login_required(login_url='login') def create_post(request): form = PostForm(request.POST,request.FILES) categories = Category.objects.all() if request.method == 'POST': category_name = request.POST.get('category') category,created_at … -
How to read file from DigitalOcean Spaces using Django?
I have a Django app that uses DigitalOcean Spaces to store user-uploaded files. The app then transcribes those files and returns the text. However when I try to read the file using the url to the stored file it fails. Here is my views.py: This code saves the file to Spaces if form.is_valid(): uploaded_file = request.FILES['file'] request.session['uploaded_file_name'] = uploaded_file.name request.session['uploaded_file_size'] = uploaded_file.size#add to models session_id = str(uuid.uuid4()) request.session['session_id'] = session_id transcribed_doc, created = TranscribedDocument.objects.get_or_create(id=session_id) transcribed_doc.audio_file = uploaded_file transcribed_doc.save() request.session['uploaded_file_path'] = transcribed_doc.audio_file.url#store url to file #rest of code This code reads the file: file_name = request.session.get('uploaded_file_name') file_path = request.session.get('uploaded_file_path')#store url in 'file_path' variable if request.method == 'POST': try: if not file_name or not file_path: return redirect (reverse('transcribeSubmit')) audio_language = request.POST.get('audio_language') output_file_type = request.POST.get('output_file_type') if file_name and file_path: file_extension = ('.' + (str(file_name).split('.')[-1])) #open file located at DO Spaces and initiate transcription with open(file_path, 'rb') as f: path_string = f.name destination_dir = 'ai_transcribe_output' transcript = transcribe_file(path_string, audio_language, output_file_type, destination_dir) My intention is to transcribe the file directly from the url at DO Spaces or if that is not feasible then instead to temporarily store a copy of the file locally so that it can be transcribed then deleted. I'm using django-storages[s3] to … -
django deploywment with daphne
I want to up my django server with run this command for in daphne: daphne -b 0.0.0.0 -p 9001 core.asgi:application And this error occurred: Traceback (most recent call last): File "/usr/local/bin/daphne", line 8, in <module> sys.exit(CommandLineInterface.entrypoint()) File "/usr/local/lib/python3.8/site-packages/daphne/cli.py", line 171, in entrypoint cls().run(sys.argv[1:]) File "/usr/local/lib/python3.8/site-packages/daphne/cli.py", line 233, in run application = import_by_path(args.application) File "/usr/local/lib/python3.8/site-packages/daphne/utils.py", line 17, in import_by_path target = importlib.import_module(module_path) File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 843, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/app/./core/asgi.py", line 4, in <module> from stream.routing import ws_urlpatterns File "/app/./stream/routing.py", line 2, in <module> from .consumers import OccurrenceConsumer File "/app/./stream/consumers.py", line 5, in <module> from .models import Occurrence File "/app/./stream/models.py", line 5, in <module> class Asset(models.Model): File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 129, in __new__ app_config = apps.get_containing_app_config(module) File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 137, in check_apps_ready settings.INSTALLED_APPS File "/usr/local/lib/python3.8/site-packages/django/conf/__init__.py", line 102, in __getattr__ self._setup(name) File "/usr/local/lib/python3.8/site-packages/django/conf/__init__.py", line 82, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must … -
Django ordering with many to many relationship in model
I am using Django-rest-framework modelviewset, I have a many-to-many relationship with my models below: class Data(TimestampMixin): user = models.ForeignKey( "User", null=True, blank=True, on_delete=models.SET_NULL, related_name="files", ) file = models.FileField(upload_to=user_directory_path, null=True, blank=True) doc_id = models.TextField(null=True, blank=True) url = models.CharField(max_length=255, null=True, blank=True) deleted = models.BooleanField(default=False) tags = models.ManyToManyField("Tag", blank=True, null=True) class Tag(models.Model): team = models.ForeignKey("Team", on_delete=models.CASCADE, blank=True, null=True) name = models.TextField(max_length=255) now here is my problem, I want to create a sorting for tag name, and here is what i've got in my Model-view-set: class UserDataViewSet(ModelViewSet): queryset = Data.objects.all() serializer_class = UserDataSerializer ordering_fields = ["file"] def get_queryset(self): user = self.request.user queryset = super().get_queryset() owner_id = getattr(self.request.user.team, "owner_id", None) if user is not None: if owner_id is not None: queryset = queryset.filter(user=owner_id, deleted=False) else: queryset = queryset.filter(user=user, deleted=False) ordering = self.request.query_params.get("ordering", "") if ordering == "tags": pass return queryset as you can see i have a condition regarding ordering == tags , I want to perform the sorting inside the condition. Now i created also a raw query that will suite my needs but i don't know how to execute it on drf side: select * from users_data ud left join users_data_tags udt on ud.id = udt.data_id left join users_tag ut on udt.tag_id = … -
How do I display an image slideshow using Bootstrap Carousel in Django?
I am trying to display a slideshow using Bootstrap Carousel in Django. The idea is to show multiple images in the slideshow for each event detail (attached with a foreign key). I believe it might have something to do with image handling in the settings.py file. What code should I add for this to work? This is an image of where I would like the slideshow to show, but it is not working. admin.py from django.contrib import admin from .models import Person, PersonDetail, Event, EventDetail, EventImage admin.site.register(Person) admin.site.register(PersonDetail) admin.site.register(Event) admin.site.register(EventDetail) admin.site.register(EventImage) models.py from django.db import models class Person(models.Model): person_text = models.CharField(max_length=200) def __str__(self): return self.person_text class PersonDetail(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) person_subtext = models.TextField() def __str__(self): return f"{self.person_subtext[:50]}..." class Event(models.Model): event_text = models.CharField(max_length=200) def __str__(self): return self.event_text class EventDetail(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) event_subtext = models.TextField() def __str__(self): return self.event_subtext class EventImage(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) image = models.ImageField(upload_to='pics/%y/%m/%d/') title = models.CharField(max_length=150) sub_title = models.CharField(max_length=100) def __str__(self): return self.title views.py from django.shortcuts import render from .models import Person, Event, EventImage def index(request): """The home page for History Gallery.""" return render(request, 'galleries/index.html') def persons(request): """Show all persons.""" persons = Person.objects.all() context = {'persons': persons} return render(request, 'galleries/persons.html', context) def person_detail(request, person_id): … -
How can I run tasks in background of djagno project? [duplicate]
I need to run a few tasks in background of my Django project and also I didn't know what is __init__.py file in the Main and App directory in my Django project. I thought myself this file could help me to run my tasks when I run the server with runserver command, But when I'm trying to put some simple codes in this file, I'm facing with this error django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.. My idea is to change my Django database in a scheduled way in background with async functions in django event loop. How can I do that? -
I use decompyle3 or uncompyle6 It decompiles my functions that do not start with "get" but if my function starts with "get" it generates an error?
I use decompyle3 or uncompyle6 It decompiles my functions that do not start with "get" but if my function or method starts with "get" it generates an error: def get_list_patientParse error at or near `POP_BLOCK' instruction at offset 120 so my function is get_list_patient(request): since it starts with "get" it gives this error. def get_list_patientParse error at or near `POP_BLOCK' instruction at offset 120 -
Why uwsgi doesn't disable threads inside django application
Uwsgi docs says, that threads inside an application are turned off until you haven't explicitly turned them on. For me, it works not like that. I have checked it through a simple view in django. uwsgi run params: - uwsgi - --socket=0.0.0.0:8081 - --module=conf.shop.wsgi - --buffer-size=65535 - --py-autoreload=1 - --lazy - --lazy-apps - --vacuum When uwsgi starts, it writes: *** Python threads support is disabled. You can enable it with --enable-threads *** View code: from threading import Thread def view(): def foo(time_sleep, number: int): time.sleep(time_sleep) return number results = {} threads = [] for i in range(8): thread = Thread( target=foo, kwargs={'time_sleep': 1, 'number': i}, name=f'task {i}', ) threads.append(thread) [thread.start() for thread in threads] [thread.join() for thread in threads] performed_threads = [thread for thread in threads if thread.result is not None] for thread in performed_threads: results[thread.name] = thread.result return results But this code works for 1s, not 8s. I tried --strict and many other options, but didn't find why it works in that way. How to turn them off, if it is possible? -
How to transfer from django to drf + nextjs
I divided the django project into back and front. I saw the reference of drf + next.js, but not transfer django to drf + next.js. Please help me I made the previously implemented function react. I'm at a loss trying to convert every page -
Changes to Django-Parler aren't applied
I'm working on my django project and currently I'm incorporating translations and localization and I have an issue. I used to had defoult language English but now I want it to be Spanish, but for some reason it's still English. Also, with Django-parler, I can see on English side of website with Spanish content even I already selected 'hide_untranslated': True, . Why changes aren't applied? # languages LANGUAGE_CODE = 'es' LANGUAGES = [ ('es', _('Spanish')), ('en', _('English')), ('ar', _('Arabic')), ('tr', _('Turkish')), ] LOCALE_PATHS = [ BASE_DIR / 'locale', ] PARLER_LANGUAGES = { 1: ( {'code': 'es',}, # Spanish {'code': 'en',}, # English {'code': 'ar',}, # Arabic {'code': 'tr',}, # Turkish ), 'default': { 'fallbacks': ['es'], 'hide_untranslated': True, } } Thanks in advance!