Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Ninja REST API to React - Forbidden (CSRF cookie not set.)
I made a Django REST API using Ninja API, and most calls work, except POST, DELETE, etc.. CONFIGURATIONS Django site URL: http://127.0.0.1:8000/ API CALL: http://127.0.0.1:8000/hello Methode: POST Parameters: None settings.py: INSTALLED_APPS: [..., "corsheaders"...] MIDDLEWARE: [..., "corsheaders.middleware.CorsMiddleware"...] # Set CORS settings CORS_ALLOW_ALL_ORIGINS = True CORS_ORIGIN_ALLOW_ALL = True CSRF_HEADER_NAME = "HTTP_X_CSRFTOKEN" CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_NAME = "X-CSRFToken" CSRF_HEADER_NAME = "X-CSRFToken" CSRF_TRUSTED_ORIGINS = [ "http://localhost:3000", ] generate csrf token for react GET: @router.get("/get_csrf_token", summary="Get CSRF Token") def get_csrf_token(request: HttpRequest) -> JsonResponse: """.""" csrf_token = get_token(request) print("TOKEN: ", csrf_token) return JsonResponse({"csrf_token": csrf_token}) hello POST rest api call: @api.post("/hello") def hello(request: HttpRequest, data: HelloSchema) -> str: """.""" return f"Hello {data.name}" React site When I make a call to django I get a csrf_token: const tokenResponse = await axios.get("/login/get_csrf_token"); const csrfToken = tokenResponse.data?.csrf_token; which is used in my REST API /hello call: const response = await axios.post("/hello", { headers: { "Content-Type": "application/json", "X-CSRFToken": csrfToken, }, credentials: "include", }); PROBLEM First, I fetch the CSRF token from my Django REST API and use this CSRF token in my HEADER for the POST calls, but I get a forbidden 403 every time. I know it's because I'm messing up the CSRF token, but … -
Error while connecting to MSSQL db using django application running on apache web server with ODBC17
Im trying to connect to a MSSQL2012 db with django 4.2.4, the application is running on an Apache2 web server using mod_wsgi running on debian12. Im getting the followinf error "('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]SSL Provider: [error:0A00014D:SSL routines::legacy sigalg disallowed or unsupported] (-1) (SQLDriverConnect)')". db config in settings.py: DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': '****', 'USER': '****', 'PASSWORD': '****', 'HOST': '192.168.50.20', 'PORT': '1433', 'OPTIONS': { "driver": "ODBC Driver 17 for SQL Server", "MARS_Connection": "True", }, }, } wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'PortaleScot.settings') application = get_wsgi_application() apache virtual host <VirtualHost *:443> DocumentRoot /var/www/PortaleScot/ ServerName *****.it ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined WSGIDaemonProcess PortaleScot python-path=/var/www/PortaleScot/ python-home=/var/www/PortaleScot/venv/ WSGIProcessGroup PortaleScot WSGIScriptAlias / /var/www/PortaleScot/PortaleScot/wsgi.py <Directory /var/www/PortaleScot/> Require all granted </Directory> Alias /static/ /var/www/PortaleScot/scotHub/static/ <Directory /var/www/PortaleScot/scotHub/static/> Require all granted </Directory> <IfModule mod_ssl.c> SSLEngine on SSLCertificateFile /etc/letsencrypt/live/portalescotsrl.it/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/portalescotsrl.it/privkey.pem SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+EXP </IfModule> Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> The driver is installed correctly and everything works just fine when ran locally using manage.py runserver or when trying to access it with tsql from the cli, but it doesnt work with apache. I think it might be a problem with wsgi/apache not being configured properly but nothing i've tried seemd to work. -
TinyMCE in a Django template
I am trying to implement an TinyMCE textarea in my Django project on the frontend via an template. When i use the js statement nothing happens. I have tried to run the same code on a 'Normal' Webserver and it worked out of the Box. Here is my Code: html file: {% extends "base.html" %} {% load static %} {% block content %} <script src="https://cdn.tiny.cloud/1/bkgmn58j8jobid31da2q8ncozamffoi5pkzf9115d22j593x/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script> <script> tinymce.init({ selector: 'textarea#content', plugins: 'ai tinycomments mentions anchor autolink charmap codesample emoticons image link lists media searchreplace table visualblocks wordcount checklist mediaembed casechange export formatpainter pageembed permanentpen footnotes advtemplate advtable advcode editimage tableofcontents mergetags powerpaste tinymcespellchecker autocorrect a11ychecker typography inlinecss', toolbar: 'undo redo | blocks fontfamily fontsize | bold italic underline strikethrough | link image media table mergetags | align lineheight | tinycomments | checklist numlist bullist indent outdent | emoticons charmap | removeformat', tinycomments_mode: 'embedded', tinycomments_author: 'Author name', mergetags_list: [ { value: 'First.Name', title: 'First Name' }, { value: 'Email', title: 'Email' }, ], ai_request: (request, respondWith) => respondWith.string(() => Promise.reject("See docs to implement AI Assistant")), }); </script> <textarea id="content"></textarea> {% endblock content %} -
How to Add search Bar in Django raw_id_fields?
So here is the problem I a facing, I have multiple apps in one app have all the contact info of my users and other apps are my departements where I will register the users form contact app. I used raw_id_fields to extend thier info and achieve what I want this is the problem enter image description here When i click on that maginyfing Glass it takes me to contacts but it has no search bar [no search bar in raw_id_fields}(https://i.stack.imgur.com/Ywp0e.png) How to do i add the bar in it This is my code class PersonRegistrationAdmin(admin.ModelAdmin): list_display = ('person_role', 'contact') search_fields = ('contact__name', 'contact__phone_number', 'contact__email', 'contact__date_of_birth', 'contact__cnic') raw_id_fields = ('contact',) admin.site.register(PersonRegistration, PersonRegistrationAdmin) I tried a few ways but looks like I could not achieve what I want -
How to capture Data from a column and add it to a dropdown menu for a form to fill another table
Here is my Model. I would like to capture the data in column "Address" then display it in a dropdown menu for a form that i am using to fill another table instead of typing the email address again. Create your models here. class Employee(models.Model): address = models.EmailField(max_length=100,null=True) first_name = models.CharField(max_length=50,null=True) sec_name = models.CharField(max_length=50,null=True) department = models.CharField(max_length= 50,null=True) company = models.CharField(max_length= 50,null=True) date_created = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.first_name + ' - ' + self.department This is the form i am using to add data to the second model class SaveCategory(forms.ModelForm): name = forms.CharField(max_length="250") description = forms.Textarea() status = forms.ChoiceField(choices=[('1','Active'),('2','Inactive')]) class Meta: model = Category fields = ('name','status') def clean_name(self): id = self.instance.id if self.instance.id else 0 name = self.cleaned_data['name'] # print(int(id) > 0) try: if int(id) > 0: category = Category.objects.exclude(id=id).get(name = name) else: category = Category.objects.get(name = name) except: return name raise forms.ValidationError(f"{name} Category Already Exists.") This is the model i am adding data into. class Category(models.Model): name = models.CharField(max_length=250) status = models.CharField(max_length=2, choices=(('1','Active'),('2','Inactive')), default=1) date_created = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name -
Django Test Detail View Returns 404 with object created in testcase
Im trying to create a detail view with a form because i need the reference of the object i use in the form. Pardon the spanglish. Heres the code below: The view: class CreateSolicitud(FormMixin, generic.DetailView): model = models.Solicitud_Curso template_name = 'forms/formulario_estudiantes.html' form_class = forms.CreateSolicitudF success_url = reverse_lazy('solicitud:home') def get_form_kwargs(self) -> dict[str, Any]: dict = super().get_form_kwargs() aux = models.Curso.objects.filter(id=self.get_object().id) cursos = models.CursosNecesarios.objects.filter(id=aux) dict['quantity'] = len(cursos.curso_necesario) dict['cursos'] = cursos.curso_necesario def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid: return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form: Any) -> HttpResponse: form.save() return super().form_valid(form) the form: class CreateSolicitudF(forms.Form): nombre = forms.CharField(max_length=255) apellido = forms.CharField(max_length=255) foto_carnet1 = forms.ImageField() foto_carnet2 = forms.ImageField() titulo = forms.FileField() institucion = forms.CharField() aval = forms.FileField() certificacion_ingles = forms.FileField() titulo_informacion = forms.FileField() def __init__(self, *args, **kwargs) -> None: self.quantity = self.kwargs.pop('quantity', None) self.cursos = self.kwargs('cursoskey', None) self.curso = self.kwargs.pop('curso', None) super().__init__(*args, **kwargs) count = 0 while count < self.quantity: self.fields['archivo' +str(count)] = forms.FileField() def save(self, commit=False): solicitud = models.Solicitud_Curso.objects.create( nombre = self.nombre, apellido = self.apellido, foto_carnet_cara = self.foto_carnet1, foto_carnet_tapa = self.foto_carnet2, titulo = self.titulo, institucion = self.institucion, aval = self.aval, certificacion_ingles = self.certificacion_ingles, titulo_informacion = self.titulo_informacion, curso = self.curso ) solicitud.save() cursos = models.CursosNecesarios.only('curso_necesario').filter(curso_id=self.cursos) cursos_solicitud = models.Solicitud_Curso_Necesario.objects.create(solicitud=solicitud) cursos_solicitud.save() for i … -
Django-simple-history: serializer m2m objects
I'm using django-simple-history==3.2.0 library and my models show below: class Employee(models.Model): last_name: str | None = models.CharField(max_length=100, null=True) # type: ignore first_name: str | None = models.CharField(max_length=100, null=True) # type: ignore middle_name: str | None = models.CharField(max_length=100, null=True) # type: ignore job_title: str | None = models.CharField(max_length=512, null=True) # type: ignore class Meta: app_label = "task_flow" class Assignment(models.Model): overdue: int = models.IntegerField(null=True) # type: ignore # ManyToManyField executors: QuerySet[Employee] = models.ManyToManyField(Employee, related_name="executor_assignments", blank=True) # type: ignore coordinators: QuerySet[Employee] = models.ManyToManyField(Employee, related_name="coordinator_assignments", blank=True) # type: ignore approvers: QuerySet[Employee] = models.ManyToManyField(Employee, related_name="approver_assignments", blank=True) # type: ignore # ForeignKey status: Status | None = models.ForeignKey(Status, on_delete=RESTRICT, related_name="assignments") # type: ignore access: Access = models.ForeignKey(Access, on_delete=RESTRICT, related_name="assignments", default=Access.Choices.general, null=True, blank=False) # type: ignore document_type: DocumentType | None = models.ForeignKey(DocumentType, on_delete=SET_NULL, null=True, related_name="assignments") # type: ignore domain: Domain = models.ForeignKey(Domain, on_delete=RESTRICT, null=False, related_name="assignments", default=Domain.Choices.internal) # type: ignore source: str | None = models.CharField(max_length=2048, null=True, blank=True) # type: ignore created_at: datetime = models.DateTimeField(auto_now_add=True) # type: ignore updated_at: datetime = models.DateTimeField(auto_now=True) # type: ignore history = HistoricalRecords(m2m_fields=[executors, coordinators, approvers]) So, now i want to serializer Assignment.history.all() queryset with employees all fields like this: "results": [ { "id": 551, "overdue": 243, "executors": [ { "id": 32, "last_name": "Копытов", … -
PyLint Django: django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured
My Django app works fine when i am just launch my application through python src/manage.py runserver But i would like to integrate pylint here, and when i launch the command pylint src --load-plugins pylint_django i got the following traceback: Traceback (most recent call last): File "/venv/lib/python3.11/site-packages/pylint_django/checkers/foreign_key_strings.py", line 87, in open django.setup() File "/venv/lib/python3.11/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) ^^^^^^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.11/site-packages/django/conf/__init__.py", line 102, in __getattr__ self._setup(name) File "/venv/lib/python3.11/site-packages/django/conf/__init__.py", line 82, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MO DULE or call settings.configure() before accessing settings. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/venv/lib/python3.11/site-packages/pylint_django/checkers/foreign_key_strings.py", line 114, in open django.setup() File "/venv/lib/python3.11/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/venv/lib/python3.11/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.11/site-packages/django/apps/config.py", line 178, in create mod = import_module(mod_path) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1126, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load … -
Combining two Queryset for sorting , Django
I have two Queryset result. I need to combine before it gets sorted. How to solve this problem in Django? And it should convert it back to Queryset for sending it to template. Tried to convert it to a list but its not converts back to Queryset. -
Stripe payment gateway not working after Installing certbot ssl certificate in django site
Stripe payment gateway in my django website was working fine but after installing certbot ssl certificate Stripe payment gateway not working. I am getting error - No api proxy found for service "urlfetch". you can see error in this image do I need to change payment gateway??? -
Running docker with mysql and django bachend
My first time dealing with docker and i kinda can't start it up properly. This is my docker-compose.yml file: version: "3" services: mysql: image: mysql container_name: my-mysql restart: on-failure ports: - 3306:3306 volumes: - ./mysql_data:/var/lib/mysql environment: MYSQL_ROOT_PASSWORD: "" MYSQL_USER: intranet MYSQL_PASSWORD: "" MYSQL_DATABASE: intranet MYSQL_ALLOW_EMPTY_PASSWORD: yes healthcheck: test: [ "CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-pmy-root-password", ] interval: 10s timeout: 5s retries: 5 backend: build: context: . dockerfile: Dockerfile container_name: my-backend restart: on-failure volumes: - .:/app environment: DATABASE_URL: mysql2://intranet@mysql:3306/intranet SECRET_KEY: x ports: - 8000:8000 depends_on: - mysql command: ["./etc/entry", "web-prod"] I created in mysql workbench database 127.0.0.1:3306 with name intranet and code in it: CREATE USER 'intranet'@'localhost'; CREATE DATABASE intranet; GRANT ALL PRIVILEGES ON intranet.* TO 'intranet'@'localhost'; FLUSH PRIVILEGES; And I got dockerfile like this: FROM python:3.7 RUN wget https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64 -O /usr/local/bin/cloud_sql_proxy \ && chmod +x /usr/local/bin/cloud_sql_proxy RUN pip3 install poetry ENV LC_ALL C.UTF-8 ENV LANG C.UTF-8 # -- Install Application into container: WORKDIR /app COPY pyproject.toml pyproject.toml COPY poetry.lock poetry.lock RUN poetry config virtualenvs.create false && poetry install COPY . /app ARG GIT_VERSION ENV GIT_VERSION $GIT_VERSION ENTRYPOINT ["/app/etc/entry"] CMD ["web-prod"] When running docker-compose up i got this error: django.db.utils.OperationalError: (1045, "Access denied for user 'intranet'@'172.19.0.3' (using password: NO)") … -
Double nested loop in Django HTML template not getting desired results
I have been staring at this one for a while and need some help. I am trying to display a 'quit' button instead of a 'book' button on days where a logged in user has already booked into a session. Can someone please provide some guidance here? Models class Member(models.Model): gym = models.ForeignKey(Gym, on_delete=models.CASCADE, blank=True, null=True, related_name="gym_membership") member = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="member_of_gym") def __str__(self): return f'{self.member.username}' class Session(models.Model): program = models.ForeignKey(Program, on_delete=models.CASCADE, blank=True, null=True, related_name="session_program") focus = models.ForeignKey(Focus, on_delete=models.CASCADE, blank=True, null=True, related_name="session_focus") location = models.ForeignKey(Location, on_delete=models.CASCADE, blank=True, null=True, related_name="session_location") booking_counter = models.IntegerField(default=0) start_datetime: datetime = models.DateTimeField() duration = models.DurationField() day = models.CharField(max_length=12, blank=True, null=True) week_number = models.IntegerField(blank=True, null=True) def __str__(self): return f'{self.program}, {self.day} - Week {self.week_number}' class Booking(models.Model): member = models.ForeignKey(Member, on_delete=models.CASCADE, blank=True, null=True, related_name="member_booking") session = models.ForeignKey(Session, on_delete=models.CASCADE, blank=True, null=True, related_name="booking_session") booking = models.BooleanField() date_booked = models.DateTimeField() date_cancelled = models.DateTimeField(blank=True, null=True) attendance_verified = models.BooleanField(blank=True, null=True) def __str__(self): return f'{self.member.member.username} booked {self.session}' Views def index(request): # store the user information in a variable user = request.user # get the membership object for that user member = Member.objects.get(member=user.id) context = { "sessions": Session.objects.all(), "bookings": Booking.objects.filter(member=member) } return render(request, "booking/index.html", context) index.html {% extends "booking/layout.html" %} {% block body %} … -
Error when scrapping Selenium and Firefox
I have a scrapper inside my Django project. It works on Selenium + Firefox My Dockerfile # Install geckodriver # Copied from: https://hub.docker.com/r/selenium/node-firefox/dockerfile ARG GECKODRIVER_VERSION=0.26.0 RUN wget --no-verbose -O /tmp/geckodriver.tar.gz https://github.com/mozilla/geckodriver/releases/download/v$GECKODRIVER_VERSION/geckodriver-v$GECKODRIVER_VERSION-linux64.tar.gz \ && rm -rf /opt/geckodriver \ && tar -C /opt -zxf /tmp/geckodriver.tar.gz \ && rm /tmp/geckodriver.tar.gz \ && mv /opt/geckodriver /opt/geckodriver-$GECKODRIVER_VERSION \ && chmod 755 /opt/geckodriver-$GECKODRIVER_VERSION \ && ln -fs /opt/geckodriver-$GECKODRIVER_VERSION /usr/bin/geckodriver Selenium container in docker-compose selenium: image: selenium/standalone-firefox:latest hostname: firefox ports: - "4444:4444/tcp" shm_size: "2gb" restart: unless-stopped I'm getting an error when I init my scrapper class from selenium import webdriver from selenium.webdriver import DesiredCapabilities class Scrapper: WEBDRIVER_TIMEOUT = 2 WEBDRIVER_ARGUMENTS = ( "--disable-dev-shm-usage", "--ignore-certificate-errors", "--headless", ) def __init__(self, useragent=None): self.options = webdriver.FirefoxOptions() for argument in self.WEBDRIVER_ARGUMENTS: self.options.add_argument(argument) self.driver = webdriver.Remote( command_executor="http://127.0.0.1:4444/wd/hub", desired_capabilities=DesiredCapabilities.FIREFOX, options=self.options, ) self.driver.set_page_load_timeout(self.WEBDRIVER_TIMEOUT) Error raise MaxRetryError(_pool, url, error or ResponseError(cause)) | urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='127.0.0.1', port=4444): Max retries exceeded with url: /wd/hub/session (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f2c4df553c0>: Failed to establish a new connection: [Errno 111] Connection refused')) Selenium successfully is on http://localhost:4444/ui I don't know how to fix it. -
nginx not serving static files for django, searching in an other folder
I am deploying my django project to server using Nginx and Gunicorn static files are not loading. 2023/11/07 05:17:42 [error] 68970#68970: *40 open() "/home/pau/perp2.0/perp/staticfiles/static/admin/js/core.js" failed (2: No such file or directory) The nginx is searching the file in /home/pau/perp2.0/perp/staticfiles/static/ but the directory for the static files is just /home/pau/perp2.0/perp/staticfiles without the last static my file configuration for nginx is this server { listen 80; server_name my_ip; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/pau/perp2.0/perp/staticfiles; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } and just in case my settings.py for the static files part is this: `# Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, '../static'), ) # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = "whitenoise.storage.CompressedStaticFilesStorage" )` I just one to serve the static files in the correct directory, thanks. If you can explain, the solution, will be great. -
No module named 'rng_base'
It's error when I run python manage.py runserver. I google but no answer can fix my error please help. File "/Users/ahkomu/Documents/myproject/account/models.py", line 21, in <module> from utils.encryption import AESCipher File "/Users/ahkomu/Documents/myproject/utils/encryption.py", line 4, in <module> from Crypto import Random File "/Users/ahkomu/Documents/myproject/venv/lib/python3.9/site-packages/Crypto/Random/__init__.py", line 28, in <module> from Crypto.Random import OSRNG File "/Users/ahkomu/Documents/myproject/venv/lib/python3.9/site-packages/Crypto/Random/OSRNG/__init__.py", line 32, in <module> from Crypto.Random.OSRNG.posix import new File "/Users/ahkomu/Documents/myproject/venv/lib/python3.9/site-packages/Crypto/Random/OSRNG/posix.py", line 32, in <module> from rng_base import BaseRNG ModuleNotFoundError: No module named 'rng_base' -
Bootstrap modal not sending a request to django view for rendering model form
I'm currently working on a django project that manages inventory of biological samples. I have a specimen details page that renders four tables with data associated with the selected specimen. In each of these tables I have an Edit button where the user can update a record associated with the specimen. Right now, when the button is clicked, a new page is opened and the update form is rendered. I'd like to use a bootstrap modal to create a popup of the form instead of having to go to a whole new page. I already created something similar on the home page for adding a new specimen record and it works great. For some reason tryin the same thing on the details page will not work. The modal does pop up, but the form does not render and it seems like the issue is that there is no request being sent to the edit_specimen url/view even though it is specified. Im wondering if it has to do with urls and the pk being in the url for this operation. I've tried several things and I can't get it to work. Any advice is appreciated as I am relatively new to … -
i get a form validation error when i want to create lisitng in django
i want to create a listing based on my model with django form but i get a validation probleme when i try to submit my new listing with the price field (foreinkey to bid class), Select a valid choice. That choice is not one of the available choices., i dont want how i can fix it model.py class Bid(models.Model): bid = models.PositiveIntegerField(default="", blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="userBid") def __str__(self) -> str: return f" {self.bid}" class Listing(models.Model): title = models.CharField(max_length=64) descreption = models.TextField() price = models.ForeignKey(Bid, on_delete=models.CASCADE, blank=True, null=True, related_name="userBid") image = models.URLField(max_length=200) active = models.BooleanField(default= True) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True, related_name="category") user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="user") watch = models.ManyToManyField(User, null=True, blank=True, related_name="watch") def __str__(self) -> str: return f"{self.title} By {self.user}"` form.py from django import forms from django.forms import ModelForm, Textarea from auctions.models import Listing class Listing(ModelForm): class Meta: model = Listing fields = [ 'title','descreption','image', 'category', 'price', 'active'] widgets = { 'price': forms.NumberInput } views.py def create(request): if request.method == "POST": form = Listing(request.POST) user = request.user price = request.POST["price"] bid = Bid(bid=int(price), user=user) bid.save() if form.is_valid(): form.save() return HttpResponseRedirect(reverse("index")) else: error = form.errors return render(request, "auctions/create.html", { "error" : error }) … -
Check if Django is able to connect with given parameters or return an error message, instead of causing an internal server error (500)
I'm trying to build dynamic connections to databases. This because I just now and then have to query them to get some data. The sources change over time, so I'm not in favor of adding them to settings. Currently I have the following code: DBTYPE = ( ('postgres', ('PostgreSQL')), ('mysql', ('MySQL')), ('mysql', ('MariaDB')), ('oracle', ('Oracle')), ('mssql', ('MSSQL')), ('sqlite', ('SQLite')), ) URLTEMPLATES = ( ('postgres', ('postgres://{USER}:{PASSWORD}@{HOST}:{PORT}/{NAME}')), ('mysql', ('mysql://{USER}:{PASSWORD}@{HOST}:{PORT}/{NAME}')), ('oracle', ('oracle://{USER}:{PASSWORD}@{HOST}:{PORT}/{NAME}')), ('mssql', ('mssql://{USER}:{PASSWORD}@{HOST}:{PORT}/{NAME}')), ('sqlite', ('sqlite:///{HOST}')), ) dburl = [item for item in URLTEMPLATES if item[0] == self.engine] self.db_url = dburl.format(**template_values) dbsetting = dj_database_url.parse(self.db_url,conn_max_age=600,conn_health_checks=True,) database_id = self.name newDatabase = {} for conn in connections.all(): print(conn) try: newDatabase["id"] = database_id newDatabase['ENGINE'] = dbsetting['ENGINE'] newDatabase['NAME'] = dbsetting['NAME'] newDatabase['USER'] = dbsetting['USER'] newDatabase['PASSWORD'] = dbsetting['PASSWORD'] newDatabase['HOST'] = dbsetting['HOST'] newDatabase['PORT'] = dbsetting['PORT'] newDatabase['ATOMIC_REQUESTS'] = True newDatabase['TIME_ZONE'] = 'Europe/Paris' newDatabase['CONN_HEALTH_CHECKS'] = False newDatabase['CONN_MAX_AGE'] = 600 newDatabase['OPTIONS'] = {} newDatabase['AUTOCOMMIT'] = False connections.databases[database_id] = newDatabase cursor = connections[database_id].cursor() cursor.close() What I would like to achieve is, that when Django is unable to connect, it just responds with a message that connection could not be established. Now I get, for example: Exception Type: OperationalError Exception Value: (1045, "Access denied for user 'test'@'localhost' (using password: YES)") In those case I would just … -
celery beat ExpressionDescriptor.py get_full_description
I hope your day is going well. I've hit a bit of a snag with a Django project I’m working on. I'm relatively new to Django and would deeply appreciate it if you could spare a moment to help me troubleshoot an issue. I'm using Celery Beat for scheduling periodic tasks. I have a view in the admin where I check and set periodic tasks, but recently a strange error has appeared, and I can't locate the issue. Whenever I try to open any admin view with periodic tasks, I get this type of error: It indicates a problem with resolving the names of the crontabs: During handling of the above exception (invalid literal for int() with base 10: '0DAY'), another exception occurred: But I haven't changed anything in the database or modified anything with settings. Do you know how I can resolve this issue, or where to look for a solution? It's probably a default setup and nothing there is set or modified, and I also couldn't find any solution to my problem on the internet :( I'm using : django-celery-beat==2.5.0 Django==4.2.2 I do not have any external settings to celery beat in django project :( -
Password change form URL in Django admin cannot find user with correct ID
I'm having some trouble with my admin settings. I am using a custom user model (called Org, for context), and everything works perfectly in the admin except for the password change form. For clarity, I'm talking about the little form that says "Raw passwords are not stored, so there is no way to see this user’s password, but you can change the password using this form." However, when I click on "this form", I'm redirected back to the admin homepage, with the warning "Org with ID '40/password (40 being the ID)' doesn’t exist. Perhaps it was deleted?" Examples of inline and admin # all inlines look like this: class OrgContactInfoInline(admin.TabularInline): model = OrgContactInfo @admin.register(Org) class OrgAdmin(admin.ModelAdmin): inlines = [OrgContactInfoInline, OrgInfoInline, OrgLocationInline, ItemInline] add_form = CustomUserCreationForm form = CustomUserChangeForm model = Org ordering = ("-org_name",)``` Important forms class CustomUserCreationForm(UserCreationForm): password = forms.CharField( widget=forms.PasswordInput(), label=mark_safe( "Your password must:<br />-Be longer than 8 characters<br />-Have an uppercase and lowercase characters<br />-Use a special character/number" ), ) confirm_password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = Org fields = ["org_name"] class CustomUserChangeForm(UserChangeForm): class Meta: model = Org fields = ["org_name"] URLs urlpatterns = [ #my urls path('', include('apps.homepage.urls')), path('accounts/', include('apps.accounts.urls')), path('mynonprofit/', include('apps.dashboard.urls')), #django urls path('accounts/', include('django.contrib.auth.urls')), … -
How to syncronize the elimination of two components
Lets say I have two componentes that display a common component when I make a delete request to the api inside one of the componentes the other component does not get deleted until I refresh the browser how can I fix that such that the common component gets eliminated at the same time here are the components: import React, { useEffect, useState } from "react"; import { getTasks } from "../api/task.api"; import { TaskCard } from "./TaskCard"; export function TaskLists() { const [tasks, setTasks] = useState([]); useEffect(() => { async function loadTasks() { const res = await getTasks(); console.log(res.data); setTasks(res.data); } loadTasks(); }, []); const removeTask = (id) => { setTasks(tasks.filter((task) => task.id !== id)); }; return ( <div> {tasks.map((task) => ( <TaskCard key={task.id} task={task} onDelete={removeTask} /> ))} </div> ); } and import React, { useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; import { getTasks } from "../api/task.api"; import { TaskCard } from "./TaskCard"; export function Daycard({ hashv }) { let b = 0; const [tasks, setTasks] = useState([]); useEffect(() => { async function loadTasks() { const res = await getTasks(); console.log(res.data); setTasks(res.data); } loadTasks(); }, []); const removeTask = (id) => { setTasks(tasks.filter((task) => task.id … -
Couldn't import Django after updating to windows 11
When I run "python manage.py runserver" the following error occurs: Traceback (most recent call last): File "F:\blear\manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "F:\blear\manage.py", line 21, in <module> main() File "F:\blear\manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? how can I solve. ps: this error occurred after updating to windows 11 image i hope solve this problem -
'CustomUser' object is not iterable
serializers.py class UserprofileSerializer(ModelSerializer): class Meta: model = Profile fields = ['id','mobile','pincode', 'address','profileimage','coverImg'] class UserSerializer(ModelSerializer): profile = UserprofileSerializer(required=True,) class Meta: model = CustomUser fields = ['email', 'first_name', 'created_at','profile'] views.py class profiledata(mixins.RetrieveModelMixin, mixins.ListModelMixin, generics.GenericAPIView): serializer_class = UserSerializer lookup_field = 'id' authentication_classes = [ JWTAuthentication, TokenAuthentication, SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated, ] def get_queryset(self): user = CustomUser.objects.get(email=self.request.user) return user def get(self, request, id=None): if id: return self.retrieve(request) else: item = self.list(request) return item when i try to get single data and serializers them, this time generated the error 'CustomUser' object is not iterable -
calling a view without passing request
I have a view that is called like this. def device_check(request, d, i): # A bunch of stuff the view does When i call this view by default it works perfect no issues, then i have another function that generates some data and tries to call that function to check and i keep getting the error that its not passing enough arguments, since i am trying to use it like this def test_function(request): test = device_check("test", "i-1799") And i understand the error is being caused because i am not passing it the request parameter like so device_check(request, "test", "i-1799") But i have no idea how i would pass it the request parameter from within another function. Is there a better way of doing this, or a way around that? -
Cannot Grab request.get_host() from Django Request to get real domain name
I use docker and nginx to run my system but I am hitting an issue now to where I would like to redirect client users of my system automatically to a subdomain. i.e. something like prod.example.com. This already works in my nginx config to duplicate access to the page, but I would like to map specific client urls to the subdomain, not the main one. Normally this would be simple in Django using something like: if not 'app.' in request.get_host(): redirect(f'app.{request.get_host()}') # example # get_host()=app | get_absolute_ur()=http://app/, meta: app But my nginx proxy pass uses an upstream variable, and it appears that is all that is posted through with the variables tried above. How can I get this done? upstream app { server web:8000; # appserver_ip:ws_port } server { server_name prod.example.com; listen 80; client_max_body_size 250M; # enforces HSTS or only content from https can be served. We do this in CloudFlare add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; add_header Permissions-Policy "autoplay=(), encrypted-media=(), fullscreen=(), geolocation=(), microphone=(), browsing-topics=(), midi=()" always; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://app; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_headers_hash_max_size 512; proxy_headers_hash_bucket_size 128; } }