Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Websocket with Django Channels and IIS - No route found for path
I'm trying to deploy my Django application to my IIS server, but my websocket doesn't work when accessing via IIS, only locally. What did I miss? When I access via IIS: new WebSocket('ws://server:8000/ws/notificacoes') -> error 1006 Log: ValueError: No route found for path 'ws/notificacoes' When I access via python runserver: new WebSocket('ws://http://127.0.0.1:8000/ws/notificacoes') -> connected Log: WebSocket HANDSHAKING /ws/notificacoes [127.0.0.1:53541] WebSocket CONNECT /ws/notificacoes [127.0.0.1:53541] consumers.py class NotificacaoConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_group_name = 'notificacoes' await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def notificacao_update(self, event): await self.send(text_data=json.dumps({ 'message': 'Notificação atualizada!' })) routing.py websocket_urlpatterns = [ ... path('ws/notificacoes', NotificacaoConsumer.as_asgi(), name='notificacao'), ] asgi.py from index.routing import websocket_urlpatterns os.environ.setdefault("DJANGO_SETTINGS_MODULE", "web.settings") django_asgi_app = get_asgi_application() application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(websocket_urlpatterns)) ), } ) -
Error in Django - [WinError 3] The system cannot find the path specified - Django
The problem is: Im trying to let users upload 5 images and on uploading I want them to change directory. So far my views.py class ProductCreateView(LoginRequiredMixin, CreateView): template_name = "product/add_product.html" success_url = reverse_lazy('home') form_class = ProductForm login_url = "/login/" # Save current user id as product_user_id in DB def form_valid(self, form, **kwargs): form.instance.product_user_id = self.request.user.id response = super().form_valid(form) id = form.instance.id picture_1 = form.instance.product_img_1 picture_2 = form.instance.product_img_2 picture_3 = form.instance.product_img_3 picture_4 = form.instance.product_img_4 picture_5 = form.instance.product_img_5 product_title = form.instance.product_title user = form.instance.product_user_id # Change directory new_directory = change_directory(id, product_title, user, picture_1, picture_2, picture_3, picture_4, picture_5) return new_directory utils.py def change_directory(id, product_title, user, picture_1, picture_2, picture_3, picture_4, picture_5): file_name = f"{id}-{product_title}-{product_title}-{user}" new_path = os.path.join(settings.MEDIA_ROOT, "product_images", file_name) if not os.path.exists(new_path): os.makedirs(new_path) picture_list = [picture_1, picture_2, picture_3, picture_4, picture_5] for i in picture_list: old_image_path = os.path.join(settings.MEDIA_ROOT, f"product_images/{i}") new_image_path = os.path.join(settings.MEDIA_ROOT, f"product_images/{file_name}/{i}") os.rename(old_image_path, new_image_path) return new_path The solution is not far away, but im out of ideas. If this helps: models.py class Product(models.Model): product_title = models.CharField(max_length=255) product_description = models.TextField() product_description_short = models.CharField(max_length=255, blank=True) product_condition = models.CharField(max_length=100) product_code = models.CharField(max_length=100, blank=True) product_manufacturer = models.CharField(max_length=100, blank=True) product_location_state = models.CharField(max_length=100) product_location_city = models.CharField(max_length=100) product_delivery_time = models.IntegerField() product_category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE, related_name='products') product_img_1 = models.ImageField(upload_to="product_images", blank=True) product_img_2 = … -
celery apply_async returning missing argument error
I have a celery function with definition - @async_worker.task(ignore_result=True, queue="data_path") def publish_msg_from_lock(self, mac: str, data: bytes, gateway_euid: str): previously it wasn't a celery task it was being called like this - n.publish_msg_from_lock(addr, unhexlify(payload), gateway_euid) After making it a celery task I updated the call in this way - n.publish_msg_from_lock.apply_async(args=(addr, unhexlify(payload), gateway_euid),) I've also tried - n.publish_msg_from_lock.apply_async(args=(addr, unhexlify(payload), gateway_euid), kwargs={}) and n.publish_msg_from_lock.apply_async(kwargs={"mac": addr, "data": unhexlify(payload), "gateway_euid": gateway_euid}) But I'm getting error - ** File "/usr/local/lib/python3.8/dist-packages/celery/app/task.py", line 531, in apply_async check_arguments(*(args or ()), **(kwargs or {})) TypeError: publish_msg_from_lock() missing 1 required positional argument: 'gateway_euid' ** Can you please help to fix it? -
Multi Tenancy with Multiple Users Multi Multi Tenancy
Hello I am working on an a project where multi-tenancy is needed. In my case tenant is a company and with in that company you ll have multiple users. Lets say our company is called abc and our domain is domain.com. So abc.domain.com reaches the abc's resources. Now should each request check to see if subdomain is valid at application server level given that our dns is registered as *.domain.com (for simplicity lets forget about www as a domain) or should you explicitly register each subdomain (In this case is the registration of subdomains instant) IS this a common practice to actually write a script that adds the each subdomain explicitly. Starting a new tenant would take a lot longer I think. but if a wildchar is used you would need to make sure that that domain exists, so maybe a DB request is necessary or alternatively maybe you can attach the domain to your token or jwt or whatnot. How do one go about handling the domains ? -
Access to XMLHttpRequest from origin has been blocked by CORS policy
I have backend on Django 4 and frontend on Angular. Django started on 192.168.1.195:8080. Angular on the 192.168.1.195:4200 When i try to open http://192.168.1.195:4200 i got Home:1 Access to XMLHttpRequest at 'http://192.168.1.195:8080/api/hosts_groups' from origin 'http://192.168.1.195:4200' has been blocked by CORS policy: Request header field pragma is not allowed by Access-Control-Allow-Headers in preflight response. settings.py ALLOWED_HOSTS = ['192.168.1.195','127.0.0.1','localhost'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'host_manager.apps.HostManagerConfig', # CORS 'corsheaders', ] CORS_ALLOWED_ORIGINS = ( "http://192.168.1.195:4200", 'http://127.0.0.1:4200', 'http://localhost:4200' ) CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = ( 'http://192.168.1.195:8080', 'http://192.168.1.195:4200', 'http://127.0.0.1:4200', 'http://localhost:4200', 'http://127.0.0.1:8080', 'http://localhost:8080' ) CORS_ALLOW_HEADERS = ( 'Access-Control-Allow-Headers', 'Access-Control-Allow-Credentials', 'Access-Control-Allow-Origin', 'Access-Control-Allow-Methods' ) MIDDLEWARE = [ # CORS 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', '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', ] Where i'm wrong? -
Error when passing file content to Celery task: "Object of type InMemoryUploadedFile is not JSON serializable"
Description: I'm encountering an error when trying to pass file content directly to a Celery task in a Django application. The error message I'm getting is: "Error: Object of type InMemoryUploadedFile is not JSON serializable" API View: class TradeMappingView(APIView): parser_classes = (MultiPartParser,) def post(self, request, format=None): serializer = InputSerializer(data=request.data) if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) file_content = serializer.validated_data['file'] column_mapping = serializer.validated_data["column_mapping"] merge_columns = serializer.validated_data.get("merge_columns", {}) values_to_replace = serializer.validated_data.get("values_to_replace", {}) try: synchronizer.delay( file=file_content, file_type="trade", columns_to_rename=column_mapping, merge_columns=merge_columns, values_to_replace=values_to_replace, ) return Response("Trades synchronization started successfully.", status=status.HTTP_202_ACCEPTED) except Exception as e: return Response(f"Error: {e}", status=status.HTTP_500_INTERNAL_SERVER_ERROR) Celery Task: @shared_task def synchronizer(file, file_type, columns_to_rename=None, values_to_replace=None, merge_columns=None): try: synchronizer_instance = Synchronizer( file=file, file_type=file_type, columns_to_rename=columns_to_rename, values_to_replace=values_to_replace, multiple_sheets=None, merge_columns=merge_columns ) synchronizer_instance.run() except Exception as e: raise synchronizer.retry(exc=e) I've noticed that the error occurs even though the data passed to the Celery task passes the validation of the InputSerializer. How can I resolve this error and successfully pass the file content to the Celery task? -
I am trying to use Zustand but I will get an error
import { create } from 'zustand'; import { mountStoreDevtools } from 'simple-zustand-devtools'; const useAuthStore = create((set, get) =>({ allUserData: null, loading: false, user: () => ({ user_id: get().allUserData?.user_id || null, username: get().allUserData?.username || null, }), setUser: (user) => set({ allUserData: user}), setLoading: (loading) => set({loading }), isLoggedIn: () => get().allUserData !== null, })) if (import.meta.env.DEV){ mountStoreDevtools(useAuthStore, 'AuthStore'); } export default { useAuthStore} Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/simple-zustand-devtools.js?v=0062664c' does not provide an export named 'mountStoreDevtools' (at auth.js:2:10) -
How to keep checkboxes selected and count after navigating to another page in using a select all function - ReactJS
I have a react app that contains a table that is populated with records from Django through rest-API. The app have a function that can select all checkboxes of each record from the table using a main checkbox in the header. I am looking if it is possible to keep the checkboxes checked and keep the count after navigating to another page. Here are the snippets for selectAllHandler, selectOnHandler and the selected counter which counts the number of checkboxes selected. const selectAllHandler = (e) => { const toggleAll = e.target.checked; const updatedCheckBoxes = {}; const newCheckBoxes = {}; accounts.forEach((account) => { updatedCheckBoxes[`ch${account.id}-${account.compliant}`] = toggleAll; }); setCheckBoxes(updatedCheckBoxes); for (let cbox in checkBoxes) { newCheckBoxes[cbox] = toggleAll; } setCheckBoxes(newCheckBoxes); setSelectAll(toggleAll) }; const selectOneHandler = (e) => { const target = e.target; const value = target.checked; const name = target.name; const newCheckBoxes = { ...checkBoxes, [name]: value }; const toggleAll = Object.values(newCheckBoxes).every((chk) => chk); const someChecked = Object.values(newCheckBoxes).some((chk) => chk); setCheckBoxes(newCheckBoxes); setSelectAll(toggleAll || (someChecked && !value)); }; const selectedCount = Object.values(checkBoxes).filter(Boolean).length; Here is how the records are populated const getAccount = async () => { const data = await axios .get("accounts/api/get-accounts/", { params: { page: pageParam, order: order, field: fieldOrder, search_field: searchField, search_value: … -
Celery tasks runs multiple times in a load balanced environment
I have a django project that deployed in a load balanced environment. there are some periodic celery tasks in my project, but they are executing twice at the time that they should execute. what is the problem? this is my tasks: from my_project.celery import app from django_redis_task_lock import lock import sentry_sdk @app.task() @lock('test_task6') def test_task_6(): sentry_sdk.capture_message(this task runs every 4 minutes starting at 17:46 PM time = {timezone.now()}') this is the schedule for this task -
Change a MultipleChoiceField to only be able to select one choice at a time
so I am currently working on a program in Django that uses MultipleChoiceFields, I only want to be able to select one choice at a time within the bounds of my code. How exactly would I be able to change my MultipleChoice field to accomplish this goal, and what attributes would I need to add? I have tried looking into documentation as well as some questions here as well for how one could modify the MultipleChoiceField function as seen here: https://www.geeksforgeeks.org/multiplechoicefield-django-forms/ https://groups.google.com/g/django-users/c/faCorI1i8VE?pli=1 Show multiple choices to admin in django But I have found no attributes to help me limit the size of the answers one could pick out to just one answer, or the answers are unrelated to the problem I am seeking to solve. Here is my code as well which also has the MultipleChoiceFields that I am trying to have select only one option: class ArdvarkForm(forms.ModelForm): class Meta: model = Course fields = ('is_done',) score_visual = forms.IntegerField(widget=forms.HiddenInput()) score_kinestetic = forms.IntegerField(widget=forms.HiddenInput()) score_auditory = forms.IntegerField(widget=forms.HiddenInput()) question1options = (('1', 'Read the instructions.'), ('2', 'Use the diagrams that explain the various stages, moves and strategies in the game.'), ('3', 'Watch others play the game before joining in.'), ('4', 'Listen to somebody explaining … -
displaying choice in django admin
im making a reservation app, i want one of the ways to see the data being in the admin panel but right now i can see everything except for the time, i think it is because its a choice field and in the admin it appears like it wasnt chosen. models.py class Reservation(models.Model): name = models.CharField(max_length=50) people = models.IntegerField() date = models.DateField() time_choice = ( (times_available[0], times_available[0]), (times_available[1], times_available[1]), (times_available[2], times_available[2]), (times_available[3], times_available[3]), (times_available[4], times_available[4]), (times_available[5], times_available[5]), (times_available[6], times_available[6]) ) time = models.CharField( max_length= 7, blank= True, null= True, choices= time_choice ) phone = models.IntegerField() def __str__(self): return self.name views.py def reservar_mesa(request): reserve_form = FormReservarMesa() if request.method == 'POST': reserve_form = FormReservarMesa(request.POST) if reserve_form.is_valid(): reserve_form.save() reserve_form = FormReservarMesa() return HttpResponseRedirect("/home/") context = {'form' : reserve_form} return render(request, 'reservas.html', context) my admin.py is the deafault. i checked and the value is being stored in the database -
I can't use templates for HTML in VS code in a project with jango and vs code doesn't close the tag
enter image description here enter image description here I can't use templates for HTML in VS code in a project with jango using the "! + tab" combination, because vs code thinks it's a different file than html Also vs code doesn't close the tag. If I put "(", vs code puts automatically ")", but there is no such thing with "<". I remember it used to be possible to do that. enter image description here enter image description here I tried different extensions, tried changing the settings a little bit. -
how can i update two model table fields at one request in django rest api
i have two tables called user and address. the address table have a foreign key relation with the user table. so how access the fields of both table and update it in a single request call { "first_name": "abijith", "last_name": "manu", "profile_picture": "http://127.0.0.1:8000/media/profile_pictures/my_pic_RxnXQ6n.jpg", "date_of_birth": "2024-02-16", "username": "", "gender": "male", "email": "doc@gmail.com", "phone_number": "7306986870", "addresses": [ { "street": "xvsvf", "city": "sss", "state": "ssss", "country": "ggggggggg", "zip_code": "sssssss" } ] this is the sample form of response that i want. and i have to update the filed as well -
How to resolve: Django, Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?
I have dockerized a django app. And when I start the container the login screen apears. But after login. I get this message: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Address not available Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? Of course there is a lot of information available on the internet. But I think, I have set everything correct - settings.py, docker-compose.yml, env file. So that is why I ask. I have the docker-compose file like this: version: "3.9" services: web: image: crdierenwelzijn.azurecr.io/web1 build: context: ./ dockerfile: Dockerfile.prod restart: always command: gunicorn DierenWelzijn.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/usr/src/app/staticfiles - media_volume:/usr/src/app/media expose: - 8000 env_file: - ./.env proxy: image: crdierenwelzijn.azurecr.io/proxy1 build: context: ./proxy restart: always depends_on: - web ports: - 80:80 volumes: - static_volume:/home/app/staticfiles - media_volume:/home/app/media volumes: static_volume: media_volume: and settings.py file: SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = bool(int(os.environ.get('DEBUG', 1))) ALLOWED_HOSTS = ['localhost', '127.0.0.1', '192.168.1.135', '10.0.2.2', '10.14.194.138', '0.0.0.0', 'dockerwelzijn.azurewebsites.net', 'welzijndocker.azurewebsites.net', 'https://welzijndocker.azurewebsites.net'] ALLOWED_HOSTS.extend( filter( None, os.environ.get('ALLOWED_HOSTS', '').split(" "), ) ) # SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") CSRF_TRUSTED_ORIGINS = [ "https://dockerwelzijn.azurewebsites.net", "https://welzijndocker.azurewebsites.net", "http://0.0.0.0:8000", "http://10.0.2.2:8000", "http://localhost:8000", "http://10.14.194.138:8000", … -
Django Backend doesn't return json to Angular frontend
I have web project, backend on Django , frontend on Angular Backend started as: python3 manage.py runserver 192.168.1.195:8080 Frontend started as: ng serve --host 192.168.1.195 on the 4200 port. On the Django in CORS_ORIGIN_WHITELIST section in settings.py CORS_ORIGIN_WHITELIST = ( 'http://192.168.1.195:8080', 'http://localhost:8081', 'http://192.168.1.195:4200', 'http://127.0.0.1:4200', ) On the frontend side in service.ts: var apiUrl = "http://192.168.1.195:8080"; var httpLink = { getAll: apiUrl + "/api/hosts_groups", When i call http://192.168.1.195:8080/api/hosts_groups django returns json as excpected and in console i see : "GET /api/hosts_groups HTTP/1.1" 200 85 But in case when i call http://192.168.1.195:4200 no json returned although in console i see: "OPTIONS /api/hosts_groups HTTP/1.1" 200 0 -
Choosing between Laravel and Django for a CRM project?
I need to build a CRM application for a medium-sized clothing factory that mainly produces t-shirts. The factory manages a large fabric storage with fabrics labeled by code (e.g., #001). Each fabric code corresponds to different models, and each model has various colors and materials. The goal is to store and display each fabric variety separately, along with showing the quantity of that model in the storage. Additionally, the factory frequently imports and exports fabrics, requiring tools for journaling these transactions. The application should log details such as the imported/exported model, quantity, color, and date. Currently, these activities are managed using Excel, and the aim is to create a user-friendly and comprehensive tool for these tasks. The application should include a search/filter tool to allow managers to easily find information. For instance, a manager might want to know which models and colors were imported/exported on a specific day or which fabric types were used for creating certain product models—an advanced search functionality is crucial. I've previously built something similar using Laravel but not at that scale (there was much less data). However, I'm uncertain if Laravel (with Postgres and NextJs) would be powerful enough for this specific application, considering the … -
Unable to connect to rmq hosted on openshift from my local machine
I'm trying to connect to rabbitMQ hosted/installed/deployed on openshit container from my local machine, and i'm facing issues. connection = pika.BlockingConnection(pika.ConnectionParameters(credentials=credentials, host=settings.RABBIT_MQ_HOST, port=settings.RABBIT_MQ_PORT)) here settings.RABBIT_MQ_HOST i have given container hostname got getaddrinfo failed error and tried ip of the container pod got pika.exceptions.AMQPConnectionError can some please help on this, thanks in advance. -
different scope throttle limits depending on the type of user in the same action of a single API
I have categorized my multiple APIs in 5 different categories now I want that throttling limit of those APIs should not be common all across. I want different limits for type of user eg. if it is user_1 scope throlling limits should {Category1: 100/hr; Category2: 100/min; Category3 : 10/hr; Category4: 10/min ;Category1: 20/sec;} and if it is user_2 scope throlling limits should {Category1: 230/hr; Category2: 40/min; Category3 : 120/hr; Category4: 15/min ;Category1: 50/sec;} I have tried multiple methods by creating custom class, creating dictionary and importing overring but nothing works this is what I tried have commented upperpart to make it distinguish from rest_framework.throttling import UserRateThrottle,ScopedRateThrottle # from backend.settings.base import VIEWSET_CATEGORIES from backend.settings.base import * # class APIThrottle(ScopedRateThrottle): # def allow_request(self, request, view): # category = self.determine_category(view) # if category: # self.set_rate_limit(category) # return super().allow_request(request, view) # def determine_category(self, view): # viewset_path = f"{view.__module__}.{view.__class__.__name__}" # return VIEWSET_CATEGORIES.get(viewset_path) # def set_rate_limit(self, category): # self.scope = category # if category == 'category1': # self.rate = '5/hour' # elif category == 'category2': # self.rate = '10/hour' class ExpectionUserRateThrottle(UserRateThrottle): def allow_request(self, request, view): if self.rate is None: return True self.key = self.get_cache_key(request, view) if self.key is None: return True self.history = self.cache.get(self.key, []) self.now … -
Django url with params(int), don't know how to test, i tried but failed
can anyone give help me how to test the following url in django? path('sendtokitchen/int:table_number/', send_to_kitchen, name='sendtokitchen'), So far I have this, but it does not contains the param, therefore it fails. def test_sendtokitchen_url_is_resolves(self): url = reverse('sendtokitchen', kwargs={'table_number': 1}) self.assertEquals(resolve(url).func, send_to_kitchen) -
Is there a way to get Django to reload after changes when using it with Docker?
I'm relatively new to Docker/deployment in general. I have a django app that utilizes rpy2 (not sure if relevant), that I have deployed using a docker container. However, I want to be able to continue developing the application and testing within the docker environment without having to spin the container up and down constantly. I read that using volumes could help to bring this functionality back, but I either have gotten the container working and don't see updates, or I get errors saying that manae.py can't be found. Is there any way to reintroduce the autoloading functionality? Here is my Dockerfile: FROM rocker/r-ver:4.1.1 ENV RENV_VERSION 0.14.0 # Install system dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ build-essential \ python3-pip \ python3-setuptools \ python3-dev \ libcurl4-openssl-dev \ libssl-dev \ libfontconfig1-dev \ libxml2-dev \ libharfbuzz-dev \ libfribidi-dev \ libfreetype6-dev \ libpng-dev \ libtiff5-dev \ libjpeg-dev \ libbz2-dev \ libopenblas-dev \ unixodbc-dev \ libcairo2-dev \ zlib1g-dev \ curl \ libpq-dev RUN apt-get update && apt-get install -y cmake RUN apt-get install -y --no-install-recommends libxt6 WORKDIR /app COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt RUN R -e "install.packages('remotes')" RUN R -e "remotes::install_github('rstudio/renv@${RENV_VERSION}')" COPY renv.lock renv.lock RUN R -e "renv::restore()" RUN … -
Django tags being displayed as text
I am currently working on a Django project. I am having problem with the tags on my HTML, they are being displayed as text. The HTML for the page in question: <div class="row"> <div class="col s12"> <button type="button" class="btn waves-effect waves-light tool-pattern-btn btn-action-pattern" onclick="javascript:history.go(-1)"><i class="material-icons left">keyboard_return</i>Go Back</button> </div> <div class="col s12"> {% if submitted %} Employee included succefully! {% else %} <form action="{% url 'incluirPessoa' %}" method="post"> <div class="card hoverable"> <div class="card-content exib-pattern"> <span class="card-title-home"><i class="material-icons left">add</i>New Employee</span> {% csrf_token %} <div class="row"> <div class="input-field col s12 l6"> <input ng-model="pessoa.name" maxlength="255" type="text" class="form-control" id="nome" name="nome" /> <label for="nome">Name:</label> </div> <div class="input-field col s12 l4"> <input ng-model="pessoa.email" maxlength="255" type="text" class="form-control" id="nome" name="nome" /> <label for="nome">Email address:</label> </div> </div> <div class="row"> <div class="input-field col s12 l3"> <input ng-model="pessoa.identidade" maxlength="255" type="text" class="form-control" id="identidade" name="identidade" /> <label for="id">identidade:</label> </div> <div class="input-field col s12 l3"> <label for="id">Institute:</label> <input ng-model="pessoa.institute" maxlength="255" type="text" class="form-control" id="instituto" name="instituto"> </div> </div> {{ form.as_p }} <div class="row"> <div class="col s12"> <button type="submit" class="btn waves-effect waves-light tool-pattern-btn green"> <i class="material-icons left">add</i>Add</button> </div> </div> </div> </div> </form> {% endif %} </div> </div> I have already read a couple of questions, but couldn't find any answer. -
Why is this local django DATABASES configuration not honored in django 5.0.1?
I'm using a local.py settings inclusion so the devs can use sqlite3 and deployed sites can use things like postgres. This is the local_py_example.py (using /tmp just for this repro): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/tmp/db.sqlite3', } } The settings file imports this thus: import os import sys from django.utils.translation import gettext_lazy as _ from utilities.find_base_dir import find_base_dir # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = find_base_dir() sys.path.insert(0, f"{BASE_DIR.parent}") # will look for local.py in the parent directory try: # noinspection PyPackageRequirements,PyUnresolvedReferences from local import * except ImportError: from club_site.settings.local_py_example import * sys.path.pop(0) ... (no DATABASES declared in settings (ONLY IN local.py)) print(f"sqlite: {DATABASES['default']['NAME']}") # at end just for debugging this An e.g. 'django migrate' creates the database at the wrong location (in the BASE_DIR) in spite of the print statement at the end of the settings showing the correct location (/tmp/db.sqlite3). -
Django: group by two columns and distinct without regard to order
I have a TextMessage model as you see: class TextMessaage(models.Model): id = models.UUIDField( _("Id"), primary_key=True, default=uuid.uuid4, editable=False, null=False, blank=False, ) created_at = models.DateTimeField(_("Created at"), auto_now_add=True) modified_at = models.DateTimeField(_("Modified at"), auto_now=True) sender = models.ForeignKey( User, on_delete=models.PROTECT, related_name="sent_messages", blank=False, null=False, verbose_name=_("Sender"), ) receiver = models.ForeignKey( User, on_delete=models.PROTECT, related_name="received_messages", blank=False, null=False, verbose_name=_("Receiver"), ) body = models.TextField( null=False, blank=False, validators=[MaxLengthValidator(4096)], verbose_name=_("Body"), ) What I am trying to do is to get last message of each conversation. I tried this: conversations = ( models.TextMessage.objects.filter(Q(sender=user) | Q(receiver=user)) .order_by( "sender__id", "receiver_id", "-modified_at", ) .distinct("sender__id", "receiver_id") ).all() The problem is that query that I have written will consider pair (sender=A, receiver=B) different from (sender=B, receiver=A) which is not I am looking for. I want these two pairs supposed the same since they share the same foreign keys regardless of their order. What should I do? To add more info, I am using Postgres by the way. -
Error when executing pipenv shell in python 3.9.12
I am trying to install and use pipenv on windows. The steps that I did: 1.pip install pipenv. 2.Added the path where pipenv was installed to the PATH. 3. Created a directory for the project and named it "work". 4. pipenv --python 3.9.12. 5.(ERROR) An error occurs when entering the "pipenv shell": E:\work>pipenv shell Launching subshell in virtual environment... Traceback (most recent call last): File "C:\Users\NickName\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\NickName\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Users\NickName\AppData\Roaming\Python\Python39\Scripts\pipenv.exe\__main__.py", line 7, in <module> # when invoked as python -m pip <command> File "C:\Users\NickName\AppData\Roaming\Python\Python39\site-packages\pipenv\vendor\click\core.py", line 1157, in __call__ return self.main(*args, **kwargs) File "C:\Users\NickName\AppData\Roaming\Python\Python39\site-packages\pipenv\cli\options.py", line 58, in main return super().main(*args, **kwargs, windows_expand_args=False) File "C:\Users\NickName\AppData\Roaming\Python\Python39\site-packages\pipenv\vendor\click\core.py", line 1078, in main rv = self.invoke(ctx) File "C:\Users\NickName\AppData\Roaming\Python\Python39\site-packages\pipenv\vendor\click\core.py", line 1688, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "C:\Users\NickName\AppData\Roaming\Python\Python39\site-packages\pipenv\vendor\click\core.py", line 1434, in invoke return ctx.invoke(self.callback, **ctx.params) File "C:\Users\NickName\AppData\Roaming\Python\Python39\site-packages\pipenv\vendor\click\core.py", line 783, in invoke return __callback(*args, **kwargs) File "C:\Users\NickName\AppData\Roaming\Python\Python39\site-packages\pipenv\vendor\click\decorators.py", line 92, in new_func return ctx.invoke(f, obj, *args, **kwargs) File "C:\Users\NickName\AppData\Roaming\Python\Python39\site-packages\pipenv\vendor\click\core.py", line 783, in invoke return __callback(*args, **kwargs) File "C:\Users\NickName\AppData\Roaming\Python\Python39\site-packages\pipenv\cli\command.py", line 394, in shell do_shell( File "C:\Users\NickName\AppData\Roaming\Python\Python39\site-packages\pipenv\routines\shell.py", line 44, in do_shell shell.fork(*fork_args) File "C:\Users\NickName\AppData\Roaming\Python\Python39\site-packages\pipenv\shells.py", line 100, in fork _handover(self.cmd, self.args + list(args)) File "C:\Users\NickName\AppData\Roaming\Python\Python39\site-packages\pipenv\shells.py", line 68, in _handover … -
How do I fix the module not found error in django
I created a django project which has 2 apps: Aceit and api, I am getting a module not found error when trying to make migrations or do anything that requires the manage.py file. I am using a virtual environment that uses python 3.10 it is worth noting that I had another project called AceIt(with a capital i as opposed to the one I have now), which I deleted. I am not sure if me deleting it is causing these problems but just thought to mention it. Below I have provided my file directory structure and stack trace of the error, if there is anything else I need to provide let me know. file directory structure: stack trace after calling python manage.py makemigrations: Traceback (most recent call last): File "C:\Users\mosta\Desktop\Desktop\Mostafa Azouz\Queen mary\Ace-It!\Code\Backend\api\manage.py", line 22, in <module> main() File "C:\Users\mosta\Desktop\Desktop\Mostafa Azouz\Queen mary\Ace-It!\Code\Backend\api\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\mosta\miniconda3\envs\Aceit\lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\mosta\miniconda3\envs\Aceit\lib\site-packages\django\core\management\__init__.py", line 416, in execute django.setup() File "C:\Users\mosta\miniconda3\envs\Aceit\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\mosta\miniconda3\envs\Aceit\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\mosta\miniconda3\envs\Aceit\lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Users\mosta\miniconda3\envs\Aceit\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File …