Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to connect 2 views in the same Django app? (ListView and EditView)
I have 2 apps called Prospecto(which means Prospect) and Cliente(which means Customer). When you see a register in EditView and click on its checkbox, you can indicate whether the register is still in Prospecto or Cliente If you don't click on the checkbox, that record is still in the Propsecto If you click the checkbox, that record becomes a Cliente and is no longer a Prospect In the code I did, when I clicked the checkbox, it turns into record in Customer(that's ok), but I can't delete it from Prospecto(in ProspectoListView). **views.py class ProspectoListView(ListView): model = Prospecto template_name = 'prospectos.html' context_object_name = 'prospectos' def get_queryset(self): queryset = super().get_queryset() fecha_inicio = self.request.GET.get('fecha_inicio') fecha_fin = self.request.GET.get('fecha_fin') if fecha_inicio and fecha_fin: queryset = queryset.filter(fecha__range=[fecha_inicio, fecha_fin]) elif fecha_inicio: queryset = queryset.filter(fecha__gte=fecha_inicio) elif fecha_fin: queryset = queryset.filter(fecha__lte=fecha_fin) return queryset def ProspectoEditar(request, pk): prospecto = get_object_or_404(Prospecto, pk=pk) if request.method == 'POST': form = ProspectoForm(request.POST, instance=prospecto) if 'es_cliente' in request.POST: cliente = Cliente(nombre=prospecto.nombre) cliente.save() prospecto.es_cliente = True prospecto.delete() if form.is_valid(): form.save() return redirect('prospectos:prospectos_list') else: form = ProspectoForm(instance=prospecto) return render(request, 'prospectos-editar.html', {'form': form}) I try with this solution, adding delete() but it doesn't work class ProspectoListView(ListView): model = Prospecto template_name = 'prospectos.html' context_object_name = 'prospectos' def get_queryset(self): fecha_inicio … -
Failed to join room. Token authentication error
I am working on a django project in which I have used zeegocloud uikits for one-one video calling web application. Even when I am using the downloadable uikits html file provided by zeegocloud itself, in which it has generated token using appID, userID, serversecret, username, but then also token authentication error is coming. I am unable to solve this issue -
Docker Compose Up - Received Permission Denied
I am unable to start a new django/python app with docker. I received permission denied. I recently bought a new computer and my app I had previously used with docker is working fine. I then recently tried to build a flask/carmen app but deleted everything that I had loaded. Im not sure if that is effecting my docker containers but my previous app will still do docker compose up and down. I tried this weekly-finances docker-compose config name: weekly-finances services: web: build: context: /Users/eleahburman/Desktop/code/weekly-finances dockerfile: Dockerfile command: - python - manage.py - runserver - 0.0.0.0:3000 networks: default: null ports: - mode: ingress target: 3000 published: "3000" protocol: tcp volumes: - type: bind source: /Users/eleahburman/Desktop/code/weekly-finances target: /code bind: create_host_path: true networks: default: name: weekly-finances_default and the docker compose seems correct. Here is my yaml file: services: web: build: . command: python manage.py runserver 0.0.0.0:3000 volumes: - .:/code ports: - "3000:3000" and here is my docker file: syntax=docker/dockerfile:1 FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ I tried deleting every app I had by docker and then cloning and adding an env. I started over my new app. I tried deleting … -
I have no clue what's going on
I just got to finishing a tutorial with the following link: https://www.youtube.com/watch?v=eOVLhM6_6t0&t=572s and the last step is to check that the server is running properly using python manage.py runserver however when I try to do this, the usual error pops up: [Errno 2] No such file or directory which I was able to solve with the absoulte path solutions provided online. However my problem is not that the problem comes when I finally reach the right cd to be in and all of this errors appear in the terminal: https://docs.google.com/document/d/1PJB2rRQ-Lyd8GQd3Hl9krkTlHD9C60WeakNk-9tM5y0/edit It was so long I couldn't even copy it all here without the computer bugging I have no clue what even is going on here or how could I solve it. I've been stuck here for the past hour. Thanks for the help. -
404 Not Found nginx/1.18.0 (Ubuntu) on running django rest framework with EC2 along with gunicorn, nginx and Supervisor
So I hosted my django rest framework project on AWS EC2. I integrated nginx, gunicorn and Supervisor along with it. After it shows successful configuration, the only link that works is the default one. Example http://35.154.109.114/ works but any other URL say http://35.154.109.114/test isn't working How ever these links work when I use a standard gunicorn --bind 0.0.0.0:8000 DemoProject.wsgi:application command. Please let me know how to work this out. -
Django passing a string from one view to another
I have one view with a chatbot on it, and it works fine. I added a second view and registered it in the urls.py file and simply passed the chatbot response to the new function to display and I got a 500 error. The code from my views.py, urls.py, main.html, and main_2.html pages is posted below. What am I missing? Thanks in advance. VIEWS.PY ` from django.shortcuts import render import openai, os from dotenv import load_dotenv from django.http import HttpResponse load_dotenv() api_key = os.getenv("OPENAI_KEY", None) def chatbot(request): chatbot_response = None if api_key is not None and request.method == 'POST': openai.api_key = api_key user_input = request.POST.get('user_input') prompt = user_input response = openai.Completion.create( engine = 'text-davinci-003', prompt = prompt, max_tokens=256, # stop="." temperature=0.5 ) print(response) chatbot_response = response["choices"][0]["text"] sayhi(request, chatbot_response) <-----(The error comes from this line. When I comment this out it works fine return render(request, 'main.html',{"response": chatbot_response}) def sayhi(request, chat_out): #return HttpResponse("hi") return render(request, 'main_2.html',{"response": chat_out}) URLS.PY (located in the parent directory of the views.py file) urlpatterns = [ path("", chatbot, name="chatbot"), # Uncomment this and the entry in `INSTALLED_APPS` if you wish to use the Django admin feature: # https://docs.djangoproject.com/en/4.2/ref/contrib/admin/ # path("admin/", admin.site.urls), path("sayhi", sayhi) ] MAIN.HTML {% extends 'base.html' … -
Link from Django Model's "absolute url" to its admin page
According to the docs, you can specify a get_absolute_url in your Django Model for a "View on site" button to show up on Django Admin. However, how would you do the opposite? A link on the above defined "absolute url" that takes you to the admin page for that instance? I can think of ways to hardcode the admin url and fill in just the instance ID, but I was hoping for a pythonic way (e.g. instance.get_admin_url()) Thanks for the help! -
I am Trying to create my first Django Project on VS Code and I cant figure out how properly install the packages needed
I am a begginer programmer who was trying to create his first project in VS Code. I installed in the Windows Powershell Django and activated a virtual environment as followed through the following pages: https://docs.djangoproject.com/en/4.2/howto/windows/ And also tried to install it on VS Code directly following this tutorial on YT: https://www.youtube.com/watch?v=Wfu5dPbiyKA however the following problems occur when I check the files in VS Code wsgi.py: from django.core.wsgi import get_wsgi_application This line throws the following warning: Import "django.core.wsgi" could not be resolved from source and the same error is thrown in the urls.py file and asgi.py file for the following: Asgi: from django.core.asgi import get_asgi_application Urls: from django.contrib import admin from django.urls import path After some research I discovered that either I installed incorrectly Django into my computer or VS Code or either I can install them individually, however neither have worked as when I try to check the status of django it says that the module doesnt exist. Please help, thanks -
Celery does not find models when performing the task
I'm writing an Api for a telephone newsletter, my code accepts dispatch requests and when it's time to start the newsletter it sends a request to an external Api, which in turn sends the messages themselves. If you run everything outside of docker, it works fine, but when you run it in docker-compose, the src.newsletter.models.Dispatch.DoesNotExist: Dispatch matching query does not exist. I'm pretty sure models with this index exist, but celery gives the error tasks.py from celery import shared_task from src.newsletter.models import Dispatch, Client, Message from config.settings.development import API_SENDING_URL, API_JWT_TOKEN import requests @shared_task def send_message_to_client(dispatch_id, client_id): dispatch = Dispatch.objects.get(id=dispatch_id) client = Client.objects.get(id=client_id) url = f"{API_SENDING_URL}{client.id}" headers = {"Authorization": f"{API_JWT_TOKEN}"} data = { "id": client.id, "phone": client.phone_number, "text": dispatch.text_message, } try: response = requests.post(url, headers=headers, json=data) print(response.status_code) if response.status_code == 200: message = Message.objects.create( status='S', dispatch=dispatch, client=client ) elif response.status_code == 401: message = Message.objects.create( status='F', dispatch=dispatch, client=client ) elif response.status_code == 400 or response.elapsed.total_seconds() > 10: # Повторная попытка отправки try: response_retry = requests.post(url, headers=headers, json=data) if response_retry.status_code == 200: message = Message.objects.create( status='S', dispatch=dispatch, client=client ) else: message = Message.objects.create( status='F', dispatch=dispatch, client=client ) except requests.exceptions.RequestException: message = Message.objects.create( status='F', dispatch=dispatch, client=client ) else: message = Message.objects.create( status='F', dispatch=dispatch, … -
Django Redirecting to custom prefilled form
So I have the following issue regarding a custom project. I made a page with different pets which are ready for adoption. Each one has a button for Details. I want when a user is Logged In to see a button which indicates that saying "Adopt". When the button is pressed I want to redirect him to a new page with some prefilled fields from the Pet model (the pet which is ready for adoption) and I want the user to fill few new fields. When he press another button (Send...etc.) to tell him that the request is send out. I tried and see that the pk of the first ready for adoption animal is 1, but when I go the url it is saying that no URL is found. Here are some of my code. urls.py urlpatterns = [ path('adoption/create/', AnimalAdoptCreateView.as_view(), name='animal_adopt_create'), path('adoption/', AnimalAdoptListView.as_view(), name='adoption_animals'), path('adoption/details/<int:pk>', AnimalAdoptDetails.as_view(), name='adoption_animals_details'), path('adoption/details/<int:pk>/adopt/', AnimalAdoptFormSendView.as_view(), name='adopt_form'), ] views.py class AnimalAdoptDetails(LoginRequiredMixin, DetailView): model = AnimalAdoptReadyCreate template_name = 'animal_adopt_detail.html' class AnimalAdoptFormSendView(LoginRequiredMixin, UpdateView): model = AnimalAdoptSend form_class = AnimalAdoptSendForm template_name = 'animal_adopt_form.html' models.py class AnimalAdoptReadyCreate(models.Model): animal_choice = { ('dog', 'Dog'), ('cat', 'Cat'), ('other', 'Other') } animal_name = models.CharField(max_length=20) animal_type = models.CharField(max_length=30, choices=animal_choice) location = models.CharField(max_length=60) details = … -
https forced in development by django. Problem with DJANGO_SECURE_HSTS_SECONDS?
Something in my Django code is forcing development server (runserver) redirection from http to https. I get these logs by docker web container after running docker compose up -d --build and trying to access my website development server: 2023-07-04 10:16:50 Starting development server at http://0.0.0.0:8000/ 2023-07-04 10:16:50 Quit the server with CONTROL-C. 2023-07-04 10:16:49 Watching for file changes with StatReloader 2023-07-04 10:18:03 [04/Jul/2023 08:18:03] "GET / HTTP/1.1" 301 0 2023-07-04 10:18:03 [04/Jul/2023 08:18:03] code 400, message Bad request version ('YñEë\x99õUÂ~Ô¾OÝ6P+') 2023-07-04 10:18:03 [04/Jul/2023 08:18:03] You're accessing the development server over HTTPS, but it only supports HTTP. These are my django security settings in: SECURE_SSL_REDIRECT = os.environ.get("DJANGO_SECURE_SSL_REDIRECT", default=True) SECURE_HSTS_SECONDS = int(os.environ.get("DJANGO_SECURE_HSTS_SECONDS", default=2592000)) SECURE_HSTS_INCLUDE_SUBDOMAINS = os.environ.get("DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", default=True) SECURE_HSTS_PRELOAD = os.environ.get("DJANGO_SECURE_HSTS_PRELOAD", default=True) SESSION_COOKIE_SECURE = os.environ.get("DJANGO_SESSION_COOKIE_SECURE", default=True) CSRF_COOKIE_SECURE = os.environ.get("DJANGO_CSRF_COOKIE_SECURE", default=True) But i changed them to make them False in development with environment variables in .env file: DJANGO_DEBUG=1 DJANGO_SECURE_SSL_REDIRECT=False DJANGO_SECURE_HSTS_SECONDS=0 DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS=False DJANGO_SECURE_HSTS_PRELOAD=False DJANGO_SESSION_COOKIE_SECURE=False DJANGO_CSRF_COOKIE_SECURE=False But actually these seem ok and I got the same problem, https is forced. Please what could cause the forcing of redirecting from http to https? I tried changing browser (chrome and firefox), changing env variables, deleting browser cache and basically everything I found on the internet but nothing changes … -
I want to design a shipping option, for standard and express in django
forms.py SHIPPING_CHOICES = ( ('S', 'Standard'), ('E', 'Express'), ) class Shipping(forms.Form): shipping_option = forms.ChoiceField(widget=forms.RadioSelect, choices=SHIPPING_CHOICES) views.py class OrderSummaryView(LoginRequiredMixin, View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) form = Shipping() context = { 'form' : form, 'object' : order, 'couponform': CouponForm(), 'DISPLAY_COUPON_FORM': True, } return render(self.request, 'cart.html', context) except ObjectDoesNotExist: messages.info(self.request, "You do not have an active order") return redirect('estores:home') def post(self, *args, **kwargs): form = Shipping(self.request.POST) order = Order.objects.get(user=self.request.user, ordered=False) if form.is_valid: shipping_option = form.cleaned_data.get('shipping_option') if shipping_option == 'S': order.options ='Standard' order.save() elif shipping_option == 'E': order.options = 'Express' order.save() html <form method="POST"> {% for value, name in form.fields.shipping_option.choices %} <tr class="summary-shipping-row"> <td> <div class="custom-control custom-radio"> <input id="{{ name }}" type="radio" name="shipping_option" value="{{ value }}" class="custom-control-input" required> <label class="custom-control-label" for="{{ name }}">{{ name }}</label> </div> </td> </tr> {% endfor %} </form> I want to retrieve the value of the form option and save it to my order shipping option. anytime i am on the cart page, there should be two options for shipping. either standard or express and i want to be able to add the shipping prices to the order price. -
Page not found (404) error message when using get_object_or_404 method
thank you so much for your help. this is the error message i get when running the code. Page not found (404) *Request Method: GET * Request URL: http://127.0.0.1:8000/blog/1/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ blog/ [name='post_list'] blog/ <int:year>/<int:month>/<int:day>/<slug:post>/ [name='post_detail'] The current path, blog/1/, didn’t match any of these. views.py in blog directory def post_detail(request,year,month,day,post): post = get_object_or_404(Post, status=Post.Status.PUBLISHED, slug=post, publish__year=year, publish__month=month, publish__day=day ) return render(request, 'blog/post/detail.html', {"post":post}) models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class Post(models.Model): class Status(models.TextChoices): DRAFT='DF', 'Draft' PUBLISHED = 'PB', 'Published' title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=2, choices=Status.choices, default=Status.DRAFT) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="blog_posts") def __str__(self): return self.title class Meta: ordering = ['-publish'] indexes = [models.Index(fields=['-publish'])] def get_absolute_url(self): return reverse("blog:post_detail", args = [self.publish.year, self.publish.month, self.publish.day, self.slug]) urls.py in mysite.urls from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls', namespace='blog')) ] urls in blog directory from django.urls import path from . import views app_name='blog' urlpatterns = [ path('', views.PostListView.as_view(),name='post_list'), path('<int:year>/<int:month>/<int:day>/<slug:post>/', … -
Django: aggregate django fields to avoid N + 1 problem
I have 3 tables/classes that are relevant to each other: CourseStudent - represents Student signed up to the course Presence - represents the attendance list of the CourseStudent CourseStudentPayment - represents the payments list for CourseStudent In the code it looks like this: class CourseStudentPayment(models.Model): course_student = models.ForeignKey( "CourseStudent", on_delete=models.CASCADE, related_name="course_student_payments", ) start_date = models.DateField(db_index=True) # other fields: price, currency, etc price = models.DecimalField(default=0, max_digits=10, decimal_places=2) def lessons_complete(self) -> int: return ( Presence.objects.filter( course_student=self.course_student, ) .filter(date__gte=self.start_date) .count() ) class Presence(models.Model): course_student = models.ForeignKey("CourseStudent", on_delete=models.CASCADE) date = models.DateField() # some other fields class CourseStudent(models.Model): # some course-related information student = models.CharField(...) def last_payment(self) -> CourseStudentPayment: return CourseStudentPayment.objects.filter(course_student=self).order_by("-start_date").first() So lessons_complete function calculates the number of the attendances since the payment date. Both CourseStudentPayment and Presence objects have CourseStudent pk. I want to render a list of payments for the students with lessons_complete in an efficient way. The dumb solution would be: get list of payments. course_payments = CourseStudentPayment.objects.all() for each payment I call lessons_complete. This solution creates N+1 problem, where for each payment I do Presence lookup. In SQL I would just join two tables (pseudocode): SELECT csp.*, count(p.id) from CourseStudentPayment csp JOIN Presence p ON scp.course_student_id = p.course_student_id WHERE p.date > … -
Why it can't pass a validation with the django form when set data after initializing
Why it can't pass a validation when I set data like this (form.data=request.POST) @login_required def add_delivery_view(request): user = request.user delivery = (Delivery.objects.filter(user=user) or [None])[0] form = AddDeliveryForm(instance=delivery) if request.method == 'POST': form.data = request.POST if form.is_valid(): delivery = form.save(commit=False) delivery.user = request.user form.save() return redirect('/') return render(request, 'order/add_delivery.html', {'form':form}) But when I set data like this, it works just fine ... if request.method == 'POST': form = AddDeliveryForm(data=request.POST, instance=delivery) if form.is_valid(): delivery = form.save(commit=False) ... I guess it something with initialization of form. Maybe I should add some method after form.data=request.POST Question is: What is the difference underneath the hood? Thanks in advance -
response.set_cookie() vs response.cookies[] in Django
I could set the cookies with response.set_cookie() and response.cookies[] as shown below: # "my_app1/views.py" from django.http import HttpResponse def test(request): response = HttpResponse('Test') response.set_cookie('first_name', 'John') # Here response.cookies['last_name'] = 'Smith' # Here return response Then, I could only delete response.set_cookie()'s cookie first_name rather than response.cookies[]'s cookie last_name with response.delete_cookie() as shown below: # "my_app1/views.py" from django.http import HttpResponse def test(request): response = HttpResponse('Test') response.delete_cookie('first_name') # Deleted response.delete_cookie('last_name') # Undeleted return response So, what is the difference between response.set_cookie() and response.cookies[] in Django? -
Django - Model - Is it possible to use dict key value in UniqueConstraint combined with other attributes
Short version of the question: Is it possible to use dict key value in UniqueConstraint. If not, advice on implementing the logic described; *I use postgreSql In django, I have a model which; has a name attribute which is an I18nCharField meaning, on the form, for the name attribute there are two inputs, one for english and one for portuguese. Other attributes are like below. Unique Constraints: (second one is the problem here) Acronym and Code can be null. This is why I have these UniqueConstraints with query in here. But the involvement of the name should be based on only the portuguese version. English one can be even blank. (name is mandatory but only the portuguese one) What my problem is; this name field is being saved as: {"en": "record5-level3", "pt": "registro5-nível3"} meaning, I cannot use this in the Unique Constraints as it is because someone can just use the same portuguese name and put random stuff in the english input. I cannot keep uniqueness on the pt name with other attributes. What I want to do is; customize this unique constraints in order to consider name as its pt value inside, or use the UniqueConstraints with name.pt Is … -
Simple audio player with <audio> tag not able to control time progress in chrome running on python server (but works on safari and node server)
Very basic audio player, running on python server locally. If I run it on safari, it works fine. If I run it on a node server, it works fine on chrome and safari. But ultimately this will be apart of a django project and needs to run on python server. For some reason on a python server (on chrome only), the audio plays, but I can only stop or go back to beginning. If I click anywhere else on the audio it stays there. There are no errors in console. I do get this in the server log for my entire django project: [04/Jul/2023 12:04:39,230] - Broken pipe from ('127.0.0.1', 61887). I am running python3. Code: <html> <head> <title>Audio Player</title> </head> <body> <h1>Audio Player</h1> <audio controls> <source src="test.mp3" type="audio/mpeg"> Your browser does not support the audio element. </audio> </body> </html> -
Return request Extended not working in Django
I newbie in Django and I'm confused on how can I hide some tags in my extends html, let say I have dashboard.html and it is being extends to the index.html which contains side bar etc. and I want to hide some of my side bar based on the roles and permissions of the user, let say if user is admin the side bar can be view, but the problem it is not being accessible to index.html since it is just an extend to dashboard. views.py @csrf_exempt def login(request): if request.user.is_authenticated: return redirect("dashboard") if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: auth_login(request, user) request.session['user_id'] = user.id request.session['username'] = user.username request.session['fullname'] = user.first_name + user.last_name return redirect("dashboard") else: messages.error(request, 'Invalid Username and Password.') return render(request, 'login.html') @login_required(login_url='login') def dashboard(request): user_details = get_user_details(request) allowed_roles = ["Admin", "Management"] role = RoleDetails.objects.filter(id=user_details.role_id).first() context = { 'user_role' : role.role_name, 'role_permission': role.role_name, } return render(request, 'dashboard.html',context) dashboard.html {% extends 'index.html' %} {% block content %} {% load staticfiles %} <div> ............... etc. index.html contains sidebar etc. let say I want to hide it if it is not equals to admin, I tried putting role_permission … -
Django Docker Container - Changing User, File Permissions, and Accessing Host Resources
I have a Django project running in a Docker container, and I've modified the user inside the container to "webmaster" using the following Dockerfile: # python image FROM python:3.8-slim-buster # Working directory WORKDIR /usr/src/app # environment variables ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 # Install dependencies RUN apt-get update && apt-get install -y --no-install-recommends RUN pip install --upgrade pip pipenv wheel # add user and group RUN groupadd -r webmaster && useradd --no-log-init -r -g webmaster webmaster # copy code COPY . . # Install packages RUN pip install --no-cache-dir -r requirements.txt # Changing ownership RUN chown -R webmaster:webmaster /usr/src/app # Change user USER webmaster # RUN mkdir -p logs && touch logs/errors.log In my Docker Compose file, I'm using volume mounts to access the log and static folders from the host machine: volumes: - /var/run/docker.sock:/var/run/docker.sock - ./static:/usr/src/app/static/ - ./logs:/usr/src/app/logs/ - /tmp:/tmp - /run:/run command: > bash -c " python manage.py migrate && python manage.py collectstatic && gunicorn --bind 0.0.0.0:8000 Arlarse.wsgi:application" I also need the "webmaster" user inside the container to have access to the docker.sock file so that my Django project can create Docker containers. Additionally, my Django project needs to create files in the /tmp and /run directories. … -
I am getting supervisor process ERROR (spawn error)
I am trying to host a django project using gunicorn, supervisor and nginx. I configured gunicorn it's running well. but supervisor process is getting errors. Here is my conf: [program:leadscrapper.nl] command = /root/venv/bin/gunicorn_start user = root stderr_logfile=/var/log/supervisor/test.err.log stdout_logfile=/var/log/supervisor/test.out.log autostart=true redirect_stderr = true environment = LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 The traces: root@scrapper:~# supervisorctl start leadscrapper.nl leadscrapper.nl: ERROR (spawn error) What can be the issue and how can I solve this issue? -
Lookup JSONField from DB without loading it as an object
I have a JSONField in one of my django models. I now want to write a very fast view function that is just meant to return that field as application/json content. However, I'm noticing that with a JSONField the string stored in the DB is automatically loaded into an object so I have to re-pack it into a string to send to the client. Is there a way to have the JSONField skip loading the string into an object? -
I have no errors in the apache log for deploying django, but my page doesn't load
Good morning everyone, I am deploying a django application on Apache and at the moment there are no errors in the LOG after I add the root folder after the first slash in the WSGIScriptAlias line /projeto_cad_usuarios C:/Apache24/htdocs/Cadastro/ project_cad_users/project_cad_users/wsgi.py But in the browser it does not load my application, it only shows the folders and files of the project. Below is the log: [Tue Jul 04 10:31:25.317454 2023] [mpm_winnt:notice] [pid 5672:tid 520] AH00455: Apache/2.4.57 (Win64) mod_wsgi/4.9.5.dev1 Python/3.11 configured -- resuming normal operations [Tue Jul 04 10:31:25.318481 2023] [mpm_winnt:notice] [pid 5672:tid 520] AH00456: Apache Lounge VS17 Server built: May 31 2023 10:48:22 [Tue Jul 04 10:31:25.318481 2023] [core:notice] [pid 5672:tid 520] AH00094: Command line: 'httpd -d C:/Apache24' [Tue Jul 04 10:31:25.320473 2023] [mpm_winnt:notice] [pid 5672:tid 520] AH00418: Parent: Created child process 3856 [Tue Jul 04 10:31:25.727677 2023] [wsgi:info] [pid 3856:tid 564] mod_wsgi (pid=3856): Initializing Python. [Tue Jul 04 10:31:25.740643 2023] [wsgi:info] [pid 3856:tid 564] mod_wsgi (pid=3856): Attach interpreter ''. [Tue Jul 04 10:31:25.748622 2023] [wsgi:info] [pid 3856:tid 564] mod_wsgi (pid=3856): Adding 'C:/Apache24/htdocs/Cadastro/env/Lib/site-packages' to path. [Tue Jul 04 10:31:25.765605 2023] [wsgi:info] [pid 3856:tid 564] mod_wsgi (pid=3856): Imported 'mod_wsgi'. [Tue Jul 04 10:31:25.768597 2023] [mpm_winnt:notice] [pid 3856:tid 564] AH00354: Child: Starting 64 worker … -
Django Multitenant - Populate connection list using default database
I have a Django Project with multitenant. Each client has is own database. I want to create a table in the default database containing the client. Something like this: class Tenant(models.Model): name = model.CharField(max_length=20) I want to use this model so that I can populate DATABASES setting or django connections and to avoid writing more code. How can I do it? -
Retrieve function for viewset without model
I am using object without RDS entry. Model class MyDummy(object): def __init__(self, **kwargs): for field in ('id', 'detail'): setattr(self, field, kwargs.get(field, None)) mydummys = { 1: MyDummy(id=1, detail={"test":"test"}), 2: MyDummy(id=2,detail={"test2":"test2"}) } Serializer class MyDummySerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) detail = serializers.JSONField(allow_null=True) def create(self, validated_data): return MyDummy(id=None, **validated_data) def update(self, instance, validated_data): for field, value in validated_data.items(): setattr(instance, field, value) return instance list function works well for now class MyDummyViewSet(viewsets.ViewSet): serializer_class = s.MyDummySerializer def list(self, request): serializer = s.MyDummySerializer( instance=m.mydummys.values(), many=True) return Response(serializer.data) However now I want to make retreive for url like api/mydummy/1 class MyDummyViewSet(viewsets.ViewSet): serializer_class = s.MyDummySerializer def list(self, request): serializer = s.MyDummySerializer( instance=m.mydummys.values(), many=True) return Response(serializer.data) def retrieve(self, request, pk=None): serializer = s.MyDummySerializer( instance=m.mydummys.values(), many=False) return Response(serializer.data) It returns, { "detail": null } I think I should narrowing by id in retrieve. How can I make it ?