Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Session Persistence Issue Between Two Django Projects Using Both JWT and Session Authentication
Background Project A Legacy system Django full-stack server based on a template language Using sessions for authentication Python version 3.8 Django version 3.2 Project B New project JSON-based Django RESTful API server Using both JWT and sessions for authentication Python version 3.11 Django version 5.0 Database: MariaDB Currently, we are migrating from the legacy Project A to Project B. During this process, we have switched the authentication method to JWT, but since the entire legacy system has not been migrated yet, we are maintaining the session method alongside it. Both projects use UserenaAuthenticationBackend and utilize django.contrib.auth.authenticate and django.contrib.auth.login for login. In this state, users might log in using either Project A or Project B, which shares the same database. The following issues arise: AS-IS Logging into A from one browser -> Logging into B from another browser -> User gets logged out from A in the first browser. Logging into B from one browser -> Logging into A from another browser -> User gets logged out from B in the first browser. Logging into A from one browser -> Logging into A from another browser -> User remains logged into A in the first browser. Logging into B from one … -
routers doesn't look like a module path-- django error
First time building a django site and keep running into this error with my index.html file for one of the sites that'll hold a list of plants. The error I keep getting is: routers doesn't look like a module path--. Any tips? Here's the html: <!-- plants/templates/index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>List of Plants</title> </head> <body> <h1>Plants</h1> <ul> {% for plant in plants %} <li>{{ plant.name }}</li> <li>Scientific Name: {{ plant.scientific_name }}</li> <li>Description: {{ plant.plant_description }}</li> <li>Price: ${{ plant.price }}</li> <li>Water Needs: {{ plant.water }}</li> <li>Light Needs: {{ plant.light }}</li> <li>Humidity Needs: {{ plant.humidity }}</li> <li>Temperature Needs: {{ plant.temp }}</li> <li>Toxicity: {{ plant.toxic }}</li> <li>Fun Fact: {{ plant.fun_fact }}</li> <br> {% endfor %} </ul> </body> </html> Here's the view: from django.shortcuts import render from .models import Plant # Make sure to import your model def index(request): plants = Plant.objects.all() return render(request, 'index.html', {'plants': plants}) and here's my model: from django.db import models class Plant(models.Model): objects = models.Manager() plant_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) scientific_name = models.CharField(max_length=200) plant_description = models.CharField(max_length=500) price = models.DecimalField(max_digits=10, decimal_places=2) image_name = models.CharField(max_length=256, blank=True, null=True) water = models.CharField(max_length=500) light = models.CharField(max_length=999) humidity = models.CharField(max_length=999) temp = models.CharField(max_length=999) toxic = models.CharField(max_length=999) fun_fact = models.CharField(max_length=999) … -
How to retrieve object of foreign key in many-to-many
I have a many-to-many relationship class Module(BaseModel): name = models.TextField(unique=True, null=False) groups = models.ManyToManyField(ModuleGroup, db_table='module_group_members') class ModuleGroup(BaseModel): name = models.TextField(unique=True, null=False) I want to retrieve the list of modules and their associated groups, something like this: {[ { 'name' : 'name1' 'groups' : ['group1', 'group2'] }, 'name' : 'name2' 'groups' : ['group6', 'group7'] } ]} Tried this modules = Module.objects.filter(is_active=True) print('values_list', list(modules.values('name', 'groups'))) which gives e [{'name': 'name1', 'groups__name': 'group2'}, {'name': 'name1', 'groups__name': 'group2'}, {'name': 'name2', 'groups__name': 'group6'}, {'name': 'name2', 'groups__name': 'group7'}, ] Is there any way to group the same modules together so that the group names are in a list? -
Why is django-ninja PUT endpoint not using the value from the request body but instead returning the default value for field to be updated?
Goal I'm trying to use a Django Ninja API endpoint (with Django Ninja's ModelSchema) to update the time zone preference (tz_preference*) field on my Django app's user model. *Note: The tz_preference field has a default value and is limited to a list of choices. Problem When I test out the API endpoint using /api/docs, the response keeps returning the tz_preference field's default value ("America/Denver") even though I give it other valid values in the request body ("Pacific/Honolulu", "America/Chicago", etc.). I know that my tz_preference field has a default value of "America/Denver", so this is most likely why the response body is {"tz_preference": "America/Denver"}, but I'm not sure why it's sticking with the default instead of using the value I give it in the request body. Code models.py from django.db import models from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.validators import ASCIIUsernameValidator from django.utils.translation import gettext_lazy as _ from timezone_field import TimeZoneField from zoneinfo import ZoneInfo TZ_CHOICES = [ (ZoneInfo('Pacific/Honolulu'), 'Pacific/Honolulu'), (ZoneInfo('America/Anchorage'), 'America/Anchorage'), (ZoneInfo('America/Los_Angeles'), 'America/Los_Angeles'), (ZoneInfo('US/Arizona'), 'US/Arizona'), (ZoneInfo('America/Denver'), 'America/Denver'), (ZoneInfo('America/Chicago'), 'America/Chicago'), (ZoneInfo('America/New_York'), 'America/New_York'), ] class TerpUser(AbstractBaseUser, PermissionsMixin): username_validator = ASCIIUsernameValidator() username = models.CharField( _("username"), max_length=150, unique=True, db_index=True, validators=[username_validator], error_messages={ "unique": _("A user with that username already exists."), }, ) email = models.EmailField( _("email … -
Django display ValidationError on the page instead of getting a yellow screen
Settings.py has DEBUG=True. Without changing that how can I display the ValidationError on the page instead of getting a yellow death screen? forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField(max_length = 30) last_name = forms.CharField(max_length = 30) class Meta: model = User fields = ['email', 'first_name', 'last_name', 'password1', 'password2'] def check_email(self): isemail = self.cleaned_data.get("email") if User.objects.filter(email=isemail).exists(): raise ValidationError({"email":"An account already exists."}) return isemail views.py @csrf_protect def user_register(request): form = UserRegisterForm() if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.check_email() Yellow screen message ValidationError at /register {'email': ['An account already exists.']} -
Running separate python code to access Django models
Is there a way I can run a stand-alone Python module to access my Django models? For instance, I might want to initialize some tables, or read tables outside of the Django server -
Django LDAP authentication CONNECT_ERROR
I've been trying to connect my app with LDAP server and have been struggling for around a week. These are my settings.py configs: AUTH_LDAP_SERVER_URI = 'ldap://10.xx.xx.1:389' AUTH_LDAP_BIND_DN = 'cn=djangouser,ou=django,ou=groups,dc=xx,dc=xx' AUTH_LDAP_BIND_PASSWORD = 'xx' AUTH_LDAP_USER_SEARCH = LDAPSearch( "dc=xx,dc=xx", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)" ) AUTH_LDAP_GROUP_SEARCH = LDAPSearch( 'dc=xx,dc=xx', ldap.SCOPE_SUBTREE, '(objectClass=groupOfNames)' ) AUTH_LDAP_GROUP_TYPE = PosixGroupType(name_attr="cn") AUTH_LDAP_MIRROR_GROUPS = True AUTH_LDAP_USER_ATTR_MAP = { 'first_name': 'givenName', 'last_name': 'sn', 'email': 'mail', 'username': 'sAMAccountName', 'password': 'userPassword', } AUTH_LDAP_PROFILE_ATTR_MAP = { 'home_directory': 'homeDirectory' } AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_TIMEOUT = 3600 AUTH_LDAP_START_TLS = True AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) import logging logger = logging.getLogger('django_auth_ldap') logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.DEBUG) Worth to mention i've tried: AUTH_LDAP_USER_DN_TEMPLATE = "sAMAccountName=%(user)s,dc=xx,dc=xx" And I've also tried mentioning the OU like: AUTH_LDAP_USER_SEARCH = LDAPSearch( "ou=store,dc=redesejus,dc=local", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)" ) AUTH_LDAP_GROUP_SEARCH = LDAPSearch( 'ou=store,dc=redesejus,dc=local', ldap.SCOPE_SUBTREE, '(objectClass=groupOfNames)' ) In all occasions I get the error below when trying to connect through django's admin Panel: Caught LDAPError while authenticating xx: CONNECT_ERROR({'result': -11, 'desc': 'Connect error', 'ctrls': [], 'info': '(unknown error code)'}) "POST /admin/login/?next=/admin/ HTTP/1.1" My AD is Windows server and this is the Structure: GROUPS -> DJANGO -> DJANGOUSER STORE -> GVIX -> USERS NORTH -> USERS SOUTH -> USERS Also worth mentioning I've tested the binding and the connection and everything … -
How to put apache superset as an application in a django project
How to put apache superset as an application in a django project I tried to install the tool using docker, but I want to use the superset tool with the django project so that it becomes an application among the applications in the django project.. -
Initializing tables with fixtures in Django
I have some tables that contain static data. So I want to be able to initialize them. I created a fixture to do this, but it seems that if I run the fixture more than once, it tries to insert the same data. Is there a way I can clear the table first? Similar to the flask drop_all, command, is there a way to drop and re-create all the tables from scratch? Or at least delete all the records. Also, how can I initialize the join table in a many-to-many relationship? -
Show/Hide the menu on another page while clicking radio button on another html page. I want to do this in Django framework
<ul class="navigation" role="navigation"> <li><a href="#"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li> <li><a href="{% url 'asset_list' %}"><i class="fas fa-box"></i> Assets</a></li> <li><a href="#"><i class="fas fa-chart-bar"></i> Reports</a></li> </ul> In the above html code i want to hide asset_list menu. <thead> <tr> <th></th> <th>Privilege Update</th> <th>Report Download</th> <th>Assign Asset</th> <th>Asset History</th> <th>View</th> <th>Edit</th> <th>Delete</th> <th>Add</th> </tr> </thead> <tbody> <tr> <td>Assets</td> <td> </td> <td> </td> <td> <label class="switch"> <input type="checkbox"> <span class="slider round"></span> </label> </td> hide the asset menu when clicking a radio button in another page . Here both dashboard and switch are in two separate html pages.hide the asset menu when clicking a radio button in another page. -
How to express the reverse of a Many-to-One in Django
I realized that Django has Many-to-One and not One-to-Many, but how to you express the opposite relationship? I have a table which has 2 foreign keys to another table. The table Validation_Run has 2 foreign keys to Calibration_Run Django complains that that the reverse relationship has a conflict calibration.ValidationRun.calibration_run_pk: (fields.E304) Reverse accessor 'CalibrationRun.validationrun_set' for 'calibration.ValidationRun.calibration_run_pk' clashes with reverse accessor for 'calibration.ValidationRun.calibration_run_pk_tune_parameters'. HINT: Add or change a related_name argument to the definition for 'calibration.ValidationRun.calibration_run_pk' or 'calibration.ValidationRun.calibration_run_pk_tune_parameters'. How do I define the reverse relationship (from Calibration_Run to Validation_Run), so there is no conflict? -
How to pass the selected value of select2 element as parameter in htmx?
I want to do GET request with query parameter. However, the query parameter need to be taken from select2 elements. How do I pass the selected value of select2 to htmx? Below is the simplified overview of my code. <select id="filter">...</select> <select id="filter2">...</select> ... <button hx-get="{% url 'filter-data'}" hx-trigger="click" hx-include="#filter, #filter2" hx-target="targetDiv" >Filter</button> <script> $(document).ready(function () { $('#filter').select2() $('#filter2').select2() } </script> I've tried to search for similar problem but none were found. Any pointer is appreciated. -
Django subquery with static VALUES expression
Is it possible using the Django ORM to write a subquery which SELECTs from a set of fixed values? SELECT id, name, ( SELECT new_ages.age FROM (VALUES ('homer', 35), ('marge', 34)) AS new_ages(name, age) WHERE new_ages.name = ages.name ) AS new_age FROM ages ; The output from such a query might be something like: person_id name age 1 homer 35 42 marge 34 99 bart null I know that the Django code would look something like this: from django.db.models import OuterRef, Subquery from my_app.models import Person Person.objects.annotate(age=Subquery(...(name=OuterRef("name"))) But what goes in the ...? -
How to connect a dockerized django application to a non dockerized postgres database?
I have a dockerized django application and It works fine to connect it to a dockerized postgres database. I would like to modify the settings.py to connect to a local database in my machine or in the network but I just do not know how to map it. shall I use a network. there is not documentation for this. In fact the policy of my company is not to dockerize databases, but we are encouraged to dockerize applications. please help. I used the following dockerfile. # Start with the official Python image FROM python:3.11 # Set work directory WORKDIR /home/app # Preventing python from writing # pyc to docker container ENV PYTHONDONTWRITEBYTECODE 1 # Flushing out python buffer ENV PYTHONUNBUFFERED 1 # Install dependencies RUN pip install --upgrade pip COPY requirements.txt . #RUN ..\bin\activate. RUN pip install gunicorn RUN pip install --no-cache-dir -r requirements.txt # Copy project files COPY . . # Expose the localhost port on docker image on the port below. This is not used for mapping it but to expose it for comunication. EXPOSE 8000 # Run the Django server . we will run django on port 8000 CMD ["python", "manage.py", "runserver", "127.0.0.1:8000"] ###############settings.py######################## DATABASES = { … -
Django - Uploaded images are not found in production
I have a problem uploading images in production in my Django project. In development it works as expected, but in production, I get 404 images not found. Folder Structure website/ | |- core/ | |- settings.py | |- urls.py | ... | |- management/ | |- models.py | ... | |- static/ | |- images/ | |- uploads/ | |- sketch/ | ... | ... | |- manage.py |- media/ | |- uploads/ | |- sketch/ | ... settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [ BASE_DIR / 'static', ] MEDIA_ROOT = BASE_DIR / 'media' STATIC_ROOT = BASE_DIR / 'staticfiles' models.py class OrderSketch(models.Model): img = models.ImageField(upload_to='uploads/sketch/') def __str__(self): return f'Sketch - {self.order.id}' index.html <div class="sketch-gallery"> {% for sketch in order.ordersketch_set.all %} <img class="gallery-image {% if forloop.first %}active{% endif %}" src="{{ sketch.img.url }}" alt="Order Sketch {{ forloop.counter }}"> {% endfor %} </div> urls.py from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('base.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Note: my website is hosted in Microsoft Azure -
How do we separate django project into multiple docker containers
I have a django project right now that allows users to login and register an account. Sort of like a blog. All the views are separated and have their own static html file. The project works running locally and all. Users data is currently running with the default sqlite3 database currently i am able to put the whole project into a single docker container and it works when I run it. I use commands: docker compose up --build I am trying to separate my docker project into multiple docker containers. I want separate containers for the frontend and backend. a lot of tutorials online show how to have multiple containers using only postgressql, but I couldn't find much on sqlite3(django default database). I want to be able to do this with a sqlite3. Is this a way to do this. I have a requirements file, .dockerignore, Dockerfile, and a docker-compose.yml file. Any help would be appreciated. docker-compose.yml: eversion: "3" services: django: image: django-docker:0.0.1 build: . ports: - "8000:8000"``` Dockerfile: FROM python:3.12.3 ENV PYTHONUNBUFFER=1 WORKDIR /code COPY requirements.txt . RUN pip install -r requirements.txt COPY . . EXPOSE 8000 CMD ["python", "manage.py","runserver"] -
Prefill modelform based on url
I'm struggling around Django form. I'm not really comfortable with this part of the framework. Here is the case. I have a ModelForm containing a OneToOneField. I would like to prepopulated the ModelChoice Field with the object referenced in the URL. Ex: catalogue/location/add/7 to add a location to the product with pk=7 NB: if the PK is not included, the form is just not prefilled models.py class Product(models.Model): pass class ProductLocation(geo_models.Model): product = geo_models.OneToOneField(Product, verbose_name=_('Product'), on_delete=geo_models.CASCADE, null=True,) geo_point = geo_models.PointField(verbose_name=_('Location'), blank=True) address = geo_models.CharField(verbose_name=_('Address'), max_length=255) urls.py urls += [ re_path(r"^location/add/(?P<product_pk>\d+)/$", self.add_update_location.as_view(), name='catalogue-product-location-add'), # Prepopulate product ModelChoiceField path("location/add", self.add_update_location.as_view(), name='catalogue-location-create' # Empty product ModelChoiceField ), path("location/<int:pk>", self.add_update_location.as_view(), name='catalogue-location-update') # Edit an existing Location ] views.py class LocationCreateUpdateView(generic.UpdateView): form_class = ProductLocationForm creating = True product = None def get_object(self, queryset=None): """ Extend the role of get_object to retrieve the product specified in the url """ self.creating = "pk" not in self.kwargs if self.creating: if self.kwargs.get("product_pk"): self.product = get_object_or_404(Product, pk=self.kwargs["product_pk"]) return None else: return super().get_object(queryset) # Try this way def get_form_kwargs(self): kwargs = super().get_form_kwargs() if self.product and not self.request.POST.get('product'): kwargs["product"] = self.product return kwargs # Or this way def get_initial(self): initial = super().get_initial() if self.product: initial["product"] = self.product return initial forms.py class ProductLocationForm(forms.ModelForm): … -
Celery Task Not Executing for Scheduled Reminder Emails in Django Project
I'm working on a Django project where I need to send confirmation emails upon registering for an event. The immediate confirmation emails are being sent correctly, but the scheduled reminder emails which I am using Celery for are not working. Below is my setup and the relevant parts of my project. event_management/celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'event_management.settings') app = Celery('event_management') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') event_management/init.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) Task Definition: emails/tasks.py import logging from celery import shared_task from django.core.mail import send_mail from django.template.loader import render_to_string from main.models import ReminderEmailNotification logger = logging.getLogger(__name__) @shared_task def send_reminder_email(email_notification_id, recipient_email): try: logger.info(f"Task started: send_reminder_email for email_notification_id {email_notification_id} to {recipient_email}") email_notification = ReminderEmailNotification.objects.get(id=email_notification_id) masthead_url = email_notification.masthead.url if email_notification.masthead else None print(f'recipient_email: {recipient_email}') context = { 'masthead_url': masthead_url, 'email_subject': email_notification.subject, 'email_message': email_notification.message, 'email_footer': email_notification.footer, } logger.info(f"Email context prepared: {context}") html_message = render_to_string('emails/email_template.html', context) logger.info(f"HTML Message: {html_message}") send_mail( email_notification.subject, '', 'example@example.com', [recipient_email], fail_silently=False, html_message=html_message ) logger.info(f"Email sent to {recipient_email}") except Exception as e: logger.error(f"Error in send_reminder_email: {str(e)}", exc_info=True) Settings: event_management/settings.py # Celery settings CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE … -
Custom class via {% element %} template django allauth
I'm trying to use the following scheme below: example of my template elements/h1.html {% comment %} djlint:off {% endcomment %} {% load allauth %} <h1> {% default slot %}{% endslot %} </h1> It is possible to declare the h1 in another template, via {% element h1 %} {% trans "Sign In" %} {% endelement %} for example, do I pass the name of a class? This way I can customize forms and other elements via .css. <h1 class="login-title"> Sign-in </h1> -
CesiumJS Container shutting down on Windows
I'm building an application, that consists of three different docker containers. The first is a CesiumJS (frontend container), the second a Django App, the third a PostgreSQL (3DCityDB, citydb container) database. The idea is to load data from Cesium in a standardized manner. The apps built just fine, but as soon as I open the page in a local setting on Windows I get the following error. The same network builds just fine on PopOS. And the application is running as requested. Why is the application not running on Windows? I'm using Windows 11 Pro and docker verson 26.1.4 frontend | /usr/src/app/node_modules/finalhandler/index.js:279 frontend | res.statusMessage = statuses.message[status] frontend | ^ frontend exited with code 1 frontend | frontend | TypeError: Cannot read properties of undefined (reading '404') frontend | at Array.write (/usr/src/app/node_modules/finalhandler/index.js:279:41) frontend | at listener (/usr/src/app/node_modules/finalhandler/node_modules/on-finished/index.js:169:15) frontend | at onFinish (/usr/src/app/node_modules/finalhandler/node_modules/on-finished/index.js:100:5) frontend | at callback (/usr/src/app/node_modules/ee-first/index.js:55:10) frontend | at IncomingMessage.onevent (/usr/src/app/node_modules/ee-first/index.js:93:5) frontend | at IncomingMessage.emit (node:events:519:28) frontend | at endReadableNT (node:internal/streams/readable:1696:12) frontend | at process.processTicksAndRejections (node:internal/process/task_queues:82:21) frontend | at process.processTicksAndRejections (node:internal/process/task_queues:82:21) frontend | frontend | Node.js v21.7.0 Full docker log: 2024-07-01 13:43:52 citydb | 2024-07-01 13:43:52 citydb | PostgreSQL Database directory appears to contain a database; Skipping initialization 2024-07-01 … -
Gunicorn cant find working directory on a remote Ubuntu machine (Django+nginx+gunicorn)
I have django application deployed on ubuntu machine, but it doesn't work because of error in gunicorn.service (it can't find work dir I wrote). My working directory is in /home/ubunut/project. gunicorn.service: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/ubuntu/project ExecStart=/home/ubuntu/project/env/bin/gunicorn --workers 3 --bind unix:/run/gunicorn.sock project.wsgi:application [Install] WantedBy=multi-user.target I went into nginx logs: 2024/07/01 11:04:08 [error] 1906#1906: *23 connect() to unix:/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream, client: myipaddress, server: ipaddress, request: "GET /en/ HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/en/", host: "ipaddress" So i typed the sudo journalctl -u gunicorn.service -f to see logs in real time: Jul 01 11:29:17 landingpage (gunicorn)[2472]: gunicorn.service: Changing to the requested working directory failed: No such file or directory Jul 01 11:29:17 landingpage systemd[1]: gunicorn.service: Main process exited, code=exited, status=200/CHDIR Jul 01 11:29:17 landingpage systemd[1]: gunicorn.service: Failed with result 'exit-code'. Jul 01 11:29:17 landingpage systemd[1]: gunicorn.service: Start request repeated too quickly. Jul 01 11:29:17 landingpage systemd[1]: gunicorn.service: Failed with result 'exit-code'. Jul 01 11:29:17 landingpage systemd[1]: Failed to start gunicorn.service - gunicorn daemon. I've tried to go to my project root and copy path with pwd command, checked all the permissions. Still doesn't work. How do i fix gunicorn? -
User Logout on Django without logging into admin
I have recently deployed a REST API for a user authentication and authorization system using Django and Django REST Framework. The system should support user registration, authentication, token refresh, logout, and allow users to retrieve and update their personal information. I have done everything, but one thing remains: the user logout: `Endpoint: /api/logout/ Method: POST Body: {"refresh_token": "eb0464c2-ed6e-4346-a709-042c33946154"} Response: {"success": "User logged out."} curl -X POST http://localhost:8000/api/logout/ -d '{"refresh_token": "eb0464c2-ed6e-4346-a709-042c33946154"}' -H "Content-Type: application/json" I have written the code for logout, it's on github: https://github.com/AnakinSolo1983/RESTful-API-for-User-Authentication.git.` So, after I have deployed the app, I have made the following discovery: no matter which browser you're using, a user cannot access logout page unless he's registered on admin. The logout page shows the message "Authentication Credentials Not Provided" as shown in the caption below: enter image description here But if I login on to admin and try to logout a user that I have created, it works: enter image description here The code on GitHub is public, so be free to take a look at it. If there is somehow to fix this problem, and you know the solution, please let me know, thank you. I tried to add AllowAny to the permission classes, … -
ajax jquery request disappearing the data on the web page of the website created using django
this is my views.py file this is my ajax jquery code in html file in my properies.html file's web page there is some data about properties. I applied some filters which will work through ajax request. when clicking the objects on the page, the ajax request is working and the data on the page is getting disappeared. -
django-angular Access to XMLHttpRequest has been blocked by CORS policy
When trying to commit a POST request to the django server I get the following error: Obj:1 Access to XMLHttpRequest at 'http://localhost:8000/api/' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response. This is the code where I make the request: return this.http.post(url, data, {headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Accept': 'application/json', 'Access-Control-Allow-Headers': 'Content-Type', })} ) And this is my django settup for corsheaders: CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_HEADERS = ["access-control-allow-origin"] Any insight on the problem and how to improve the question will be thanked -
how to impelement notifications-hq ?: relation "notifications_notification" already exists
i try to implement notification-hq in django and when i send notify i got same error relation "notifications_notification" already exists sender=User.objects.using("default").get(username=request.user.username) receiver = User.objects.using("default").all() notify.send(sender=sender, recipient=receiver, verb='Message', description='message') and i got this traceback Traceback (most recent call last): File "/home/azizi/Documents/Ufmeeg_Projects/Gmao/Gmao-env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/azizi/Documents/Ufmeeg_Projects/Gmao/Gmao-env/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/azizi/Documents/Ufmeeg_Projects/Gmao/Gmao/Gmao/views.py", line 41, in home notify.send(sender=sender, recipient=receiver, verb='Message', description='message') . . . . return self.cursor.execute(sql, params) File "/home/azizi/Documents/Ufmeeg_Projects/Gmao/Gmao-env/lib/python3.9/site-packages/django/db/utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/azizi/Documents/Ufmeeg_Projects/Gmao/Gmao-env/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/azizi/Documents/Ufmeeg_Projects/Gmao/Gmao-env/lib/python3.9/site-packages/psycopg/cursor.py", line 737, in execute raise ex.with_traceback(None) django.db.utils.ProgrammingError: relation "notifications_notification" does not exist LINE 1: INSERT INTO "notifications_notification" ("level", "recipien... ^ [01/Jul/2024 09:14:04] "POST / HTTP/1.1" 500 184506 please help me