Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to connect package django-storages[azure] with docker container?
I have dockerized a django app. And the docker container is working and running smoothly.But now I have installed the package django-storages[azure] for a seperate server for the css and image files. And I can upload images to the azure environment. So if I start the django app with the command python manage.py runserver I can upload images to the Azure container. But if I try to build the docker container with the commands: docker compose -f docker-compose-deploy.yml build and docker compose -f docker-compose-deploy.yml up And I go to: http://localhost/admin/ I will get an: admin/:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error) dockerfile: # pull official base image FROM python:3.9-alpine3.13 # ENV PATH="/scripts:${PATH}" # set work directory # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /tmp/requirements.txt COPY ./scripts /scripts WORKDIR /usr/src/app EXPOSE 8000 # install psycopg2 dependencies ARG DEV=false RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ apk add --update --no-cache postgresql-client jpeg-dev && \ apk add --update --no-cache --virtual .tmp-build-deps \ build-base postgresql-dev musl-dev zlib zlib-dev linux-headers && \ /py/bin/pip install -r /tmp/requirements.txt && \ if [ $DEV = "true" ]; \ … -
<rest_framework.request.Request: PATCH catching the whole debugging instead of the id/url
So i'l using a class Class(ApiView) in my code and create a patch request from the front i'm getting this error api- | /v1/a06300db-30bc-4890-8154/ api- | heeeeeeeeeeello world api- | print id <rest_framework.request.Request: PATCH '/v1/a06300db-30bc-4890-8154/'> api- | Good bye world api- | ["“<rest_framework.request.Request: PATCH '/v1/a06300db-30bc-4890-8154/'>” is not a valid UUID."] api- | 112.00.0.10 - "PATCH /v1/claims/a06300db-30bc-4890-8154-d1813a08f68e/ HTTP/1.0" 500 145 so when i make the http axios patch request i pass the id as arg a06300db-30bc-4890-8154 and it undestand very well since i'm able to make the request now the problem is that when i print the id instead of getting just a06300db-30bc-4890-8154 i get the whole object <rest_framework.request.Request: PATCH '/v1/a06300db-30bc-4890-8154/'> and since this is not valid a get the error is not a valid UUID."] i don't undestand why im getting the whole url as the id <rest_framework.request.Request: PATCH i tried, usinkg the pk, the arks, kwargs and the id itself to retrieve the id, but i always get <rest_framework.request.Request: PATCH '/v1/a06300db-30bc-4890-8154/'> i tried `def patch(request, id):` or even just `def patch(request):` still getting the same ` <rest_framework.request.Request: PATCH '/v1/a06300db-30bc-4890-8154/'> `as id -
Issue with Forbidden Error when Accessing Django Backend through AWS API Gateway
My web application faces a perplexing 403 Forbidden Error when calling the Django backend (hosted on Railway.app) through AWS API Gateway (proxy). This error curiously only manifests in live scenarios, as testing the API Gateway endpoint from the AWS console works flawlessly. I've meticulously ruled out potential culprits like authorization mechanisms, Web ACL, and API key requirements. Interestingly, swapping out Django for a different backend, the Starwars API in this case, completely eliminates the error, hinting at a potential compatibility issue between AWS and Django in my specific configuration. To further isolate the source of the problem, I undertook the following actions: Deployed the Django app on both Railway.app and an EC2 instance, eliminating any platform-specific hosting issues. Configured Django to allow all origins and request headers, preemptively addressing potential CORS restrictions. Verified that no access-limiting resource policies were associated with either the API Gateway or the Django app. These steps successfully ruled out both hosting and CORS as potential culprits, narrowing the investigation down to the intricate configuration of the API Gateway or the logic within the Django application itself. -
Zappa is not deploying all the packages in my virtual env to Lambda
I am deploying a django application using Zappa. My application's dependencies are bigger than 1GB in size for this reason I am using slim_handler:true parameter in zappa settings as well as increasing ephemeral size of lambda using "ephemeral_storage": {"Size": 10240}, but still i am getting error django not found in my cloudWatch logs. All my configurations are attached below: My zappa_settings.py file: { "test-staging": { "ephemeral_storage": {"Size": 10240}, "aws_region": "us-west-1", "django_settings": "lu_development.settings", "profile_name": "default", "project_name": "linkedunion-bac", "runtime": "python3.10", "s3_bucket": "zappa-sultan-test-migration", "slim_handler": true } } All the packages installed in my virtual env: aioredis==1.3.1 amqp==2.6.1 anyio==4.0.0 argcomplete==3.2.1 asgiref==3.7.2 async-timeout==4.0.3 attrs==23.1.0 autobahn==23.6.2 Automat==22.10.0 autopep8==2.0.4 backoff==2.2.1 billiard==3.6.4.0 boto==2.49.0 boto3==1.24.8 botocore==1.27.8 celery==4.4.3 certifi==2023.7.22 cffi==1.15.1 cfn-flip==1.3.0 channels==3.0.5 chardet==3.0.4 click==8.1.7 constantly==15.1.0 cryptography==41.0.3 daphne==3.0.2 Deprecated==1.2.14 Django==4.0.10 django-cacheops==7.0.1 django-cors-headers==3.14.0 django-debug-toolbar==4.0.0 django-environ==0.4.5 django-mysql==3.9.0 django-ninja==0.22.2 django-redis==5.3.0 django-simple-history==2.12.0 django-storages==1.10 djangorestframework==3.14.0 djangorestframework-simplejwt==4.6.0 durationpy==0.6 exceptiongroup==1.1.3 factory-boy==3.3.0 Faker==19.3.1 funcy==1.18 gcloud==0.18.3 geographiclib==2.0 geopy==2.4.0 googleapis-common-protos==1.52.0 grpcio==1.60.0 gunicorn==20.0.4 h11==0.14.0 hiredis==2.2.3 hjson==3.1.0 httpcore==0.17.3 httplib2==0.22.0 httpx==0.24.1 hyperlink==21.0.0 idna==2.10 importlib-metadata==6.11.0 incremental==22.10.0 jmespath==0.10.0 JSON-log-formatter==0.5.2 jws==0.1.3 kappa==0.6.0 kombu==4.6.11 markdown-it-py==3.0.0 MarkupSafe==2.1.3 mdurl==0.1.2 mysql-connector==2.2.9 mysql-connector-python==8.0.21 mysqlclient==2.0.1 numpy==1.25.2 oauth2client==4.1.2 onesignal-sdk==2.0.0 opentelemetry-api==1.19.0 opentelemetry-distro==0.40b0 opentelemetry-exporter-otlp==1.19.0 opentelemetry-exporter-otlp-proto-common==1.19.0 opentelemetry-exporter-otlp-proto-grpc==1.19.0 opentelemetry-exporter-otlp-proto-http==1.19.0 opentelemetry-instrumentation==0.40b0 opentelemetry-instrumentation-celery==0.40b0 opentelemetry-instrumentation-dbapi==0.40b0 opentelemetry-instrumentation-django==0.40b0 opentelemetry-instrumentation-logging==0.40b0 opentelemetry-instrumentation-psycopg2==0.40b0 opentelemetry-instrumentation-redis==0.40b0 opentelemetry-instrumentation-requests==0.40b0 opentelemetry-instrumentation-urllib3==0.40b0 opentelemetry-instrumentation-wsgi==0.40b0 opentelemetry-proto==1.19.0 opentelemetry-sdk==1.19.0 opentelemetry-semantic-conventions==0.40b0 opentelemetry-util-http==0.40b0 pandas==2.0.3 pdf2image==1.16.3 pep8==1.7.1 Pillow==10.0.1 placebo==0.9.0 protobuf==3.20.3 pyasn1==0.5.0 pyasn1-modules==0.3.0 pycodestyle==2.11.0 pycparser==2.21 pycryptodome==3.10.1 pydantic==1.9.1 Pygments==2.17.2 PyJWT==2.8.0 pymssql==2.2.5 … -
Django Rest Framework generic views, so clunky to get the object/instance
Often I wish to use the created/updated object, for say to log it in some history, or use it in an email. E.g.1. CreateAPIView def create(self, request, *args, **kwargs): ret = super().create(request, *args, **kwargs) # Do something with the create object here, e.g. create a history log return ret E.g.2. UpdateAPIView def update(self, request, *args, **kwargs): ret = super().update(request, *args, **kwargs) # Do something with the create object here, e.g. create a history log return ret Answers that are not solutions Use ret.data to see a dict of the object data ... because I wish to access the object so so I can look up foreign keys, call methods on it etc. Create a new object using ret.data ... wasteful to create object, through it away, and recreate it again Copy and paste most of the original create/update method just so one can save a reference to the object ... this is terrible because it's the meat of the generic view, so why event use it in the first place. The best I have come up: A CreateAPIView, e.g.: def perform_create(self, serializer): self.object = serializer.save() return self.object def create(self, request, *args, **kwargs): ret = super().create(request, *args, **kwargs) # Do something … -
pytest-django could can't find modules correctly
I have a django project with a structure like below project_root/ │ ├── Tia/ │ ├── manage.py │ ├── Tia/ │ │ ├── __init__.py │ │ ├── my_settings.py │ │ └── ... │ └── repository/ │ ├── __init__.py │ ├── tests/ │ └── ... └── pytest.ini I installed pytest-django and created a pytest.ini file. the context of the file are below: [pytest] DJANGO_SETTINGS_MODULE=MKalender.settings_local_prod_connection python_files = tests.py test_*.py *_tests.py Now I'm getting this Error when running the test only. runserver command works fine: ModuleNotFoundError: No module named 'Tia.repository' Any Idea on how to solve this? -
CKEditor is not showing on Pythonanywhere django project | "Not Found: /static/ckeditor/ckeditor/ckeditor.js"
CKEditor is working fine and is visible on the local host. When on (free)hosting it on pythonanywhere.com, it is not showing up; instead, it shows default input field. "textarea" sharing the page. Please suggest some fixes. Thank you. Error log: 2024-01-15 09:13:51,307: Not Found: /static/admin/css/base.css 2024-01-15 09:13:51,315: Not Found: /static/admin/css/forms.css 2024-01-15 09:13:51,322: Not Found: /static/admin/css/nav_sidebar.css 2024-01-15 09:13:51,584: Not Found: /static/ckeditor/ckeditor.css 2024-01-15 09:13:51,608: Not Found: /static/admin/css/responsive.css 2024-01-15 09:13:51,846: Not Found: /static/admin/js/jquery.init.js 2024-01-15 09:13:51,852: Not Found: /static/admin/js/vendor/jquery/jquery.js 2024-01-15 09:13:51,868: Not Found: /static/ckeditor/ckeditor-init.js 2024-01-15 09:13:51,874: Not Found: /static/ckeditor/ckeditor/ckeditor.js 2024-01-15 09:13:51,899: Not Found: /static/admin/js/core.js 2024-01-15 09:13:51,925: Not Found: /static/admin/js/admin/RelatedObjectLookups.js 2024-01-15 09:13:52,120: Not Found: /static/ckeditor/ckeditor.css 2024-01-15 09:13:52,129: Not Found: /static/admin/js/actions.js 2024-01-15 09:13:52,150: Not Found: /static/admin/js/urlify.js 2024-01-15 09:13:52,157: Not Found: /static/admin/js/prepopulate.js 2024-01-15 09:13:52,205: Not Found: /static/admin/js/vendor/xregexp/xregexp.js 2024-01-15 09:13:52,226: Not Found: /static/admin/js/prepopulate_init.js 2024-01-15 09:13:52,497: Not Found: /static/admin/js/change_form.js 2024-01-15 09:13:52,504: Not Found: /static/admin/js/nav_sidebar.js 2024-01-15 09:13:52,512: Not Found: /static/admin/css/responsive.css 2024-01-15 09:13:55,332: Not Found: /static/ckeditor/ckeditor.css 2024-01-15 09:13:55,367: Not Found: /static/ckeditor/ckeditor-init.js 2024-01-15 09:13:55,422: Not Found: /static/ckeditor/ckeditor/ckeditor.js static files: URL Directory /static/ /home/nielitchandan/project/static /media/ /home/nielitchandan/project/media Project structure (static directory location): Directories .idea/ blog/ project/ static/ venv/ Files db.sqlite3 manage.py settings.py INSTALLED_APPS = \[ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'ckeditor', 'ckeditor_uploader', \] CKEDITOR_BASEPATH = '/static/ckeditor/ckeditor/' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_CONFIGS = { … -
Storing and displaying document files like pdf word excel etc in Django using cx_oracle into CLOB datatye of Oracle DB
I have a requirement using Django where I need to store documents( pdf, word, excel in Oracle database) as Clob in Oracle and display it in a page. But I am just not sure how to use 'cx_oracle' or 'python-oracledb' for storing and retrieving the Document stored as CLOB in oracle. I am new to django, Can anybody please help me. -
Django admin with Nullable ForeignKey in Model but why required in admin page?
I am using Django and Python to create a custom admin interface for a model named ContentProgress. The ContentProgress model has a nullable ForeignKey field named custom_user_content. However, when I try to save or edit a ContentProgress instance in the Django admin without providing a value for custom_user_content, I encounter an error stating "This field is required for Custom user Content." # Admin class class ContentProgressAdmin(admin.ModelAdmin, ExportCsvMixin): list_display = ['user', 'lesson', 'in_percent', 'in_seconds', 'done', 'created_at', 'updated_at'] fields = ['user', 'lesson', 'in_percent', 'in_seconds', 'done', 'real_seconds_listened', 'custom_user_content'] search_fields = ['user__username', 'lesson__name', 'user__email'] list_filter = ['done', ('custom_user_content', RelatedDropdownFilter), ('user__company', RelatedDropdownFilter)] autocomplete_fields = ['user', 'lesson', 'custom_user_content'] actions = ['export_as_csv'] admin.site.register(ContentProgress, ContentProgressAdmin) # Model class ContentProgress(Progress): lesson = models.ForeignKey(MediaFile, on_delete=models.CASCADE) custom_user_content = models.ForeignKey(CustomUserContent, null=True, on_delete=models.CASCADE) def __str__(self): return f'{self.lesson.name} - {int(self.in_percent * 100)}%' Despite setting null=True for the custom_user_content field, I still face validation issues in the Django admin. How can I properly handle nullable ForeignKey fields in the admin interface to avoid this error? -
Warnings for a View without parameters in drf-spectacular
There are a problem with drf-spectacular. I have a View, something like this: class SomeView(APIView): def get(self, request): return JsonResponse("Hello world!") in other words, a View that does not accept parameters. And when generating the schema, I get a warning in the console: Error [SomeView]: unable to guess serializer. This is graceful fallback handling for APIViews. Consider using GenericAPIView as view base class, if view is under your control. Either way you may want to add a serializer_class (or method). Ignoring view for now How to make it so that there is no warning and the scheme is generated correctly? I've searched through a bunch of articles and questions on stackoverflow and other resources and still haven't found a solution. -
CORS "No Access Control Allow Origin Header" Present on requested resource Django/React/Gitpod
I am in the process of working on a project with a React frontend, a Django backend, developing in gitpod. I believe that gitpod may be complicating this more than I'd expect. Currently, I can confirm that I am able to run python manage.py runserver, then browse the Django Rest Framework via the api root. I also have a Create-React_app frontend that is able to make requests to another API, but requests to my API returns only the error: "Access to fetch at 'https://8000-anthonydeva-sylvanlibra-8b5cu5lyhdl.ws-us107.gitpod.io/lineitem/' from origin 'https://3000-anthonydeva-sylvanlibra-8b5cu5lyhdl.ws-us107.gitpod.io' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled." I know that django-cors-headers is the recommended solution for this based on what I have seen so far, but even after installing and setting this up in settings.py, the same error is showing up and my django server doesn't seem to be showing any updates for the failed requests. My apologies if any needed information is missing. I'm pretty new to this and having a bit of trouble identifying … -
Can I reduce number of requests made to redis data store when using celery and beat
I am using on a project Django + celery + beat. Is there a way how to reduce number or requests made to redis data store? -
Phonenumber-field issue
I have already installed django-phonenumber-field and also added in Installed apps but still facing this issue (AttributeError: module 'django.db.models' has no attribute 'PhoneNumberField') while running migrations I was expecting the migrations to work fine -
Can not install typed-ast==1.1.0
I am trying to run a django python project, but I can not install typed-ast == 1.1.0. Below is the error I encountered, please help me note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for typed-ast Failed to build typed-ast ERROR: Could not build wheels for typed-ast, which is required to install pyproject.toml-based projects I tried to find a way on the internet but couldn't. -
How to implement fool proof Error handling in python-django
I am a newbie and have a question related to error handling in django/python; hoping the pros can provide some directions. In my project, I am sometimes using try/except and other places checking for errors returned from functions. Mostly, all API calls have try/except and then general error handling otherwise. As the project has grown in size, it is becoming quite unwieldy and now it is very hard to ensure that all errors are being properly handled. Especially, with multiple levels of nested functions, it is hard to make sure that I am checking for errors from each function, propagating it properly upstream and handling at every level. I have so far ensured that all APIs have try/except. And I am also checking each function for error handling. My simple question is - is there a defined or recommended way to handle errors? is it possible to really end the program and gracefully exit (after logging the error + stack trace in the log file) in case of certain errors? This is because even if I am handling the error in the function and returning appropriate value, I don't want to rely on the upstream functions properly handling/propagating the error? … -
Adding a Doughnut plot using Vue.js 3 to a Django template
I want to display a Doughnut plot in a Django template using Vue.js 3. The Doughnut plot will be a component because I need to reuse this plot a lot. So far I have managed to create a simple text component in this way: base.html <script src="https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.prod.js"></script> {% block vue %} {% endblock %} status.html {% extends "../base.html" %} {% load static %} <doughnut-plot title={{title}}></doughnut-plot> {% block vue %} <script type="module" src="{% static 'js/status.js' %}"></script> {% endblock %} status.js import DoughnutPlot from "./components/doughnut_plot.js" const app_status = Vue.createApp({ components: { DoughnutPlot, } }); app_status.mount("#app_status"); doughnut_plot.js export default { props: ['title'], template: `<h4>{{title}}</h4>` }; This code show the correct title that I pass with the context in the corresponding view. However, I cannot manage to change doughnut_plot.js into a plot. I tried the following: status.html % block vue %} <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <!-- Include Vue Chart.js wrapper --> <script src="https://cdn.jsdelivr.net/npm/vue-chartjs@3"></script> <!-- Include your Vue component script --> <script type="module" src="{% static 'js/components/doughnut_plot.js' %}"></script> <script type="module" src="{% static 'js/status.js' %}"></script> {% endblock %} doughnut-plot.js import { Doughnut } from 'vue-chartjs'; export default { extends: Doughnut, props: ['data', 'options'], mounted() { this.renderChart(this.data, this.options); } }; But I get the error Uncaught TypeError: Failed to resolve … -
Method Not Allowed Error when calling an existing endpoint
I get this error: Method Not Allowed: /api/v1/auth/users/student/submission/ "POST /api/v1/auth/users/student/submission/ HTTP/1.1" 405 41 when accessing the endpoint to one of my Django apps modelviewset (Submission). Below is the setup; views class SubmissionViewSet(viewsets.ModelViewSet): serializer_class = SubmissionSerializer queryset = Submission.objects.all().order_by("-created_at") permission_classes = [IsAuthenticated] def perform_create(self, serializer): serializer.save(student=self.request.user) URLs router = routers.DefaultRouter() router.register("admin/courses", views.AdminCourseViewSet) router.register("student/courses", views.StudentCourseViewSet) router.register("student/submission", views.SubmissionViewSet) urlpatterns = [ path("users/", include(router.urls)), ] Serializer class SubmissionSerializer(serializers.ModelSerializer): project = serializers.UUIDField() course = serializers.SerializerMethodField() date_submitted = serializers.SerializerMethodField() class Meta: model = Submission fields = [ "id", "project", "course", "submission_link", "status", "date_submitted", "student_comments", "mentor_comments", ] read_only_fields = ["course", "status"] def get_course(self, instance): return instance.project.course.title def get_date_submitted(self, instance): return instance.date_submitted.strftime("%b %d, %Y") Models class Submission(TimeStampedUUIDModel): class STATUS(models.TextChoices): """ Choices for the project """ REVIEWED = "Reviewed", _("Reviewed") PENDING = "Pending", _("Pending") NOT_SUBMITTED = "Not_Submitted", _("Not_Submitted") student = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) submission_link = models.URLField() status = models.CharField( verbose_name=_("Project Review Status"), choices=STATUS.choices, default=STATUS.NOT_SUBMITTED, max_length=20) date_submitted = models.DateTimeField(default=timezone.now) student_comments = models.TextField(blank=True, null=True, default="") mentor_comments = models.TextField(blank=True, null=True, default="") def __str__(self): return f"{self.student.first_name} {self.student.last_name} {self.project.project_title} submission." I want to understand what I am doing wrong as I have exhausted all possibilities to get it work. django version: 4.1.13 django-rest-framework: 3.14.0 -
Incorrect vps nginx redirect settings for django app
I use vps, ubuntu 20, nginx, gunicorn for run django project. <my_ip>:3000 runs react app, <my_ip>:8000 runs django app. I want run <my_ip> react (frontend), <my_ip>/api/ django (backend) sudo nano /etc/nginx/sites-available/default/: root /home/ubuntu/clinent/build; server { listen 80; server_name <my_ip>; access_log /var/log/nginx/example.log; location /media/ { root /home/ubuntu/api; expires 30d; } location /static/ { root /home/ubuntu/api; expires 30d; } location /api/ { rewrite /api/(.*) /$1 break; proxy_pass http://<my_api>:8000; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location / { try files $uri $uri /index.html } } Frontend, backend works fine, static and media works fine. But when I get into api/admin page, all my hrefs still point to root directory. For example, when I press to "orders" href I-ve got link to Orders I want get "/api/admin/orders/" I think about /admin/ redirect, but is it correct decision? I see a lot of not found errors in gunicorn logs because of incorrect links. Can I fix it with nginx? Or in django settings? -
Access to fetch at 'http://127.0.0.1:8000/api/movie/1' from origin 'http://localhost:3000' has been blocked by CORS policy
Every thing is normal but its not working, I have followed https://pypi.org/project/django-cors-headers/,https://github.com/adamchainz/django-cors-headers these documentation but its not working for me after that I have tried every possible solution available but its not working. Can anyone tell me what is wrong in this why it is not working. this is settings file of my project from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', "rest_framework", "cinemagic", ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] ROOT_URLCONF = 'cinemagic_backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'cinemagic_backend.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': "cinemagic", } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True STATIC_URL = 'static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] -
The current path, login/accounts/login/, didn’t match any of these
I'm trying to make a login application, however whenever I try to log in using my template it gives this error.'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' urls.py from django.urls import path from .views import login urlpatterns = [ path('', login), path('login/', login, name="login"), ] views.py from django.shortcuts import render from django.contrib.auth import authenticate from django.http.response import HttpResponse from CRUDfuncionario.models import Funcionario # Create your views here. def login(request): if request.method == "GET": return render(request,'login.html') else: idFuncionario = request.POST.get("idFuncionario") senha = request.POST.get("senha") user = Funcionario.objects.filter(idFuncionario=idFuncionario, senha=senha) if user: return HttpResponse('autenticado') else: return HttpResponse('Email ou senha invalidos') login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> </head> <body> <form action= "{% url 'login' %}" method="POST"> {% csrf_token %} <input type="text" placeholder="Identificação" name="idFuncionario"> <br> <input type="text" placeholder="Senha" name="senha"> <br> <button type="submit">Login</button> </form> </body> </html> apps.py from django.apps import AppConfig class LoginConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'login' settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent X_FRAME_OPTIONS = 'SAMEORIGIN' # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-2$2#kr-+3(*k46w+*+r-ij5@=bhhzuee$o57%@3rgfofo%ek&(' # SECURITY WARNING: don't run with debug turned on in … -
data not sent by AJAX to Django view
register.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <script src="{% static 'jquery.min.js' %}"></script> <link rel="stylesheet" href="{% static 'all.css' %}" /> <title>Customer Registration</title> <style> body { font-family:Verdana, Geneva, Tahoma, sans-serif, 'Arial', sans-serif;s margin: 0; padding: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; } #cr{ color: #f8f8f8; } #registration-container { display: flex; flex-direction: column; align-items: center; gap: 15px; width: 300px; padding: 20px; border: 1px solid #ccc; border-radius: 8px; background-color: #fff; box-shadow: 0 0 10px rgba(110, 1, 1, 0.1); } .maindiv { gap: 15px; padding: 10px; background-color: rgb(40, 6, 6); opacity: 1; /* Set the opacity to 60% */ display: flex; flex-direction: column; align-items: center; } input { padding: 10px; width: 100%; box-sizing: border-box; margin-bottom: 10px; } input[type="submit"] { cursor: pointer; background-color: #2ecc71; color: #fff; border: none; border-radius: 8px; transition: background-color 0.3s ease; } input[type="submit"]:hover { background-color: #27ae60; } </style> </head> <body> <header> <nav> <ul> <li><a href="{% url 'home' %}">HOME</a></li> <li><a href="{% url 'Registration' %}">REGISTRATION</a></li> <li><a href="{% url 'Entry' %}">LOGIN</a></li> </ul> </nav> </header> <div class="maindiv"> <h1 id="cr">Customer Registration</h1> <div id="registration-container"> <form method="POST" id="someForm"> {% csrf_token %} <label for="name">Name:</label> <input type="text" id="name" name="name" required /> <label for="email">Email:</label> <input type="email" id="email" … -
Deploy Django on WHM and Cent7
This is my issue: I am using bluehost VPS & WHM plan, and VPS Cent7 to deploy my django project which was created by python 3.11 and django v.4, I have installed python 3.11 and sqlite 3 successfully on Cent7, everything is working but when try to run this command " python 3.11 manage.py runserver 8000 ", I get this error Python 3.11.X ModuleNotFoundError: No module named '_sqlite3' Please help me to solve this problem, thanks -
How to fix Internal Server Error for Django deployment on Heroku
I am facing an issue on deployment of the website using django and heroku the image in production als on build logs it seems okay , i think is something with secret key or anything else ? -
Django. DJ_REST_AUTH redirects to login page after email confirmation
As I want my app to be REST app I don't want users to be redirected to login page after successful email confirmation. I use following: settings: ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_CONFIRM_EMAIL_ON_GET = True installed apps: APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites' 'allauth', 'allauth.account', 'allauth.socialaccount', "rest_framework", "rest_framework.authtoken", "dj_rest_auth", "dj_rest_auth.registration", 'accounts', ] and urls: from django.urls import path, include from dj_rest_auth.registration.views import VerifyEmailView, ConfirmEmailView urlpatterns = [ path("", include("dj_rest_auth.urls")), path( 'signup/account-confirm-email/<str:key>/', ConfirmEmailView.as_view(), name="account_confirm_email", ), path("signup/", include("dj_rest_auth.registration.urls")), path('signup/account-confirm-email/', VerifyEmailView.as_view(), name='account_email_verification_sent'), ] The registration works, I get an email with a link to confirm. I click and it redirects me to login page which as it is REST doesn't exists. I belive that it is allauth responsible for this redirection as I haven't found any settings in dj_rest_auth What I can see in the logs is just: Not Found: /accounts/login/ I expect there to be some way to redirect to page that informs about the result of verification but I can't find anything in the documentation. Do I need to make my own ConfirmEmailView doesn't redirects but returns page with the result? -
DTL tags are not working inside the template script
I am working on a django web application and I need to create a pie graph on dashboard page. I decided to use chart js for this. For some reason when I try to use DTL inside the script inside the template, every piece of DTL has a red line underneath(error ofc). I have no idea how to solve this. Solving the issue with the DTL meaning it's working <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script> var ctx = document.getElementById('expenseChart').getContext('2d'); // Prepare data using Django template language var data = { labels: [ {% for expense in expenses_by_type %} "{{ expense.place_type }}"{% if not forloop.last %}, {% endif %} {% endfor %} ], datasets: [{ data: [ {% for expense in expenses_by_type %} {{ expense.total_amount }}{% if not forloop.last %}, {% endif %} {% endfor %} ], backgroundColor: [ 'rgba(255, 99, 132, 0.7)', 'rgba(255, 159, 64, 0.7)', // ... add more colors as needed ], }] }; var myPieChart = new Chart(ctx, { type: 'pie', data: data, }); </script> Here in this script, every DTL part is an error