Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to override django wagtail joyous
How to add a field or override model from joyous? I try extend like wagtail models but doesnt work. class CustomCalendarPage(ProxyPageMixin, CalendarPage): @route(r"^all/$") def serveAll(self, request): """all events list view.""" myurl = self.get_url(request) today = timezone.localdate() monthlyUrl = myurl + self.reverse_subpage('serveMonth', args=[today.year, today.month]) weekYear, weekNum, dow = gregorian_to_week_date(today) weeklyUrl = myurl + self.reverse_subpage('serveWeek', args=[weekYear, weekNum]) listUrl = myurl + self.reverse_subpage('serveAll') allEvents = self._getAllEvents(request) eventsPage = self._paginate(request, allEvents) cxt = self._getCommonContext(request) cxt.update({ 'weeklyUrl': weeklyUrl, 'monthlyUrl': monthlyUrl, 'listUrl': listUrl, 'events': eventsPage }) cxt.update(self._getExtraContext("all")) return TemplateResponse(request, "joyous/calendar_list_all.html", cxt) I want add a view where list all events (past and future) Thanks! -
Django: FileNotFoundError: No such file or directory
I'd just like to check if my Django model works or not(By trying create a new model instance on admin page). However I get FileNotFoundError at /admin/appname/modelname/add/ [Errno 2] No such file or directory: '/home/user/PycharmProjects/myproject/media/file_I_wanna_upload.file' (It's an absolute path where the uploaded file should be situated after saving my new model instance). In my settings.py: MEDIA_ROOT = 'media' MEDIA_URL = '/media/' In my project's urls.py: from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) And finally my models.py from PIL import Image as I class Image(models.Model): galery = models.ForeignKey(Galery, on_delete=models.CASCADE) image = models.ImageField(upload_to='photos') def save(self, *args, **kwargs): img = I.open(self.image.path) img.resize(size=(300, 300)) img.save(self.image.path) return super(Image, self).save(*args, **kwargs) Everything seems be working good. However it doesn't. Here is another model that I have no problems with: class UserProfile(models.Model): user = models.OneToOneField(CustomUser, related_name='userprofile', on_delete=models.CASCADE) username = models.CharField(max_length=30, unique=True) slug = models.SlugField(unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) avatar = models.ImageField(default="default.png", upload_to='avatars', blank=True) description = models.TextField(max_length=10 ** 4, blank=True) def __str__(self): return self.username def save(self, *args, **kwargs): self.slug = slugify(self.username) return super().save(*args, **kwargs) What am I doing wrong? Help me please. -
Optimizing User Authentication Flow: Google OpenID to Notion API Integration in Chrome Extension
iam currently developing a chrome extension that involves user authentication using Google OpenID. Following the initial authentication, the user is directed to the Notion API where a second authentication step is required to grant permissions from their Notion page to my extension. I am exploring ways to optimize this process by transmitting the information obtained during the extension's authentication to the Notion API, facilitating automatic user authentication without the need for a second manual step. Is there a method or best practice for securely transmitting and utilizing the authentication data from the Google OpenID process to seamlessly authenticate the user in the Notion API? I would greatly appreciate any insights, code examples, or recommended approaches to achieve a more streamlined authentication experience for the user. -
Could someone guide me on how to efficiently save multiple records simultaneously using the FilteredSelectMultiple widget within a Django admin form?
I want to save multiple record at a time using admin form. admin.py class QFE_BENG_LANGUAGE_ModelAdmin(QFE_BaseModelAdmin): form = adminModelFilterForm def get_form(self, request, obj=None, **kwargs): # debug(request.POST,"request") form = super().get_form(request, obj, **kwargs) selected_question_ids = request.POST.getlist('question_id') selected_exam_id = request.POST.get('exam_id') # Create QUESTION_FOR_EXAM instances for each selected_question_id if obj is None: for question_id in selected_question_ids: check = QUESTION_FOR_EXAM.objects.filter(exam_id__id = selected_exam_id, question_id__id=question_id) if not check: question_instance = QUESTION_FOR_EXAM.objects.create( exam_id_id=selected_exam_id, question_id_id=question_id ) return form def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'question_id': kwargs['queryset'] = BENG_LANGUAGE.objects.filter(topi_name__id=1) kwargs['widget'] = admin.widgets.FilteredSelectMultiple('Question ID', is_stacked=False) kwargs['required'] = False return super().formfield_for_foreignkey(db_field, request, **kwargs) admin.site.register(Q_FOR_EXAM_BENG_LANGUAGE,QFE_BENG_LANGUAGE_ModelAdmin) form.py class adminModelFilterForm(forms.ModelForm): subject_name = forms.ChoiceField(choices=select_subject,required=False) class Meta: model = QUESTION_FOR_EXAM fields = ('subject_name', 'exam_id', 'question_id') Model.py class QUESTION_FOR_EXAM(models.Model): exam_id = models.ForeignKey(EXAM, blank=False, on_delete=models.CASCADE, verbose_name="Exam ID") question_id = models.ForeignKey(BENG_LANGUAGE,blank=False, on_delete=models.CASCADE, verbose_name="QUESTION ID") When I click on save button it shows: After successfully saving a record in the QUESTION_FOR_EXAM table, how can I redirect the user to initiate a new insertion or navigate to another page? -
embedding a syntax highlighted textarea in django admin
I want to make a syntax highlighted area in django admin. My first approach using highlightjs failed miserably and I tried copying the code from ace.io with some, but definitely not outstanding success: my admin/base.html: {% extends "admin/base.html" %} {% block extrahead %} <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.32.1/ace.min.js"></script> {% endblock %} I also edited the admin/change_form.html so it can find a specific field: ... {% if field.is_checkbox %}{{ field.field }}{{ field.label_tag }}{% else %} {{ field.label_tag }} {% if field.is_readonly %}<div class="readonly">{{ field.contents }}</div> {% else %} {% if "thefield:" in field.label_tag %} <style type="text/css" media="screen"> #editor { position: relative; width: 460px; height: 380px; } </style> <div id="editor"> {{ field.field }} </div> <script> var editor = ace.edit("editor"); editor.setTheme("ace/theme/monokai"); editor.session.setMode("ace/mode/python"); </script> {% else %}{{ field.field }} {% endif %} {% endif %} {% endif %} so far I can see that the js is doing some job, but I cannot get the position right - how it looks: what i want: I also feel that changed data in the textarea is not saved any more. -
Signal not triggering after save method is called
I have a signal set up to alert subscribers after the Food object has been updated. This helps to let them know if something changed about the food they are subscribed to. I have everything set up correctly according to the Django configuration but nothing happens after the Food object is updated. The Food object is in the models.py file of my meals app. I also added the meals app to INSTALLED_APPS. # meals/signals.py @receiver(post_save, sender=Food) def alert_subscribers(created, instance, **kwargs): If not created: # My logic to alert subscribers Thank you for your help -
Why LoginPemissionMixin redirects to the wrong url
I make my project with Django. I want to let only logged user to access URL. When my class uses LoginRequiredMixin to redirect to login view, after successful login it redirects to URL "main". views.py class LoginView(FormView): form_class = LoginForm template_name = "tavern_app/login.html" success_url = reverse_lazy("main") def form_valid(self, form): user = form.user login(self.request, user) return super().form_valid(form) class CreateSessionBaseView(LoginRequiredMixin, View): login_url = '/log-in/' def get(self, request): return render(request, "tavern_app/create_session_base.html") urls.py path("log-in/", LoginView.as_view(), name="login"), path("create-session/", CreateSessionBaseView.as_view(), name="create-session-base"), at this moment, when I enter CreateSessionBaseView as not logged user it redirects to log-in with URL: http://127.0.0.1:8000/log-in/?next=/create-session/ But after successful login it redirects to "main" as it's defined in LoginView. How to redirect it back to my "create-session-base" page. I still want my "login" view to redirect to "main" in other cases. -
How to find the function of an executed celery task when it has a custom name?
I am building an app that is recording and analyzing celery task runs, e.g. to produce statistics. The task runs are recorded through celery signals, so I get a lot of detailed information about each task run including it's ID and name. Task names can be set to a custom value or - if no value is set - are set to the qualified name of the task's function by default. (e.g. my_app.tasks.my_task). For my app I'd like to keep track of the packages a task belongs to. That is easy to extract when the task's name is the qualified name, but not when it is a custom name. I looked through the data structures provided in each signal call (e.g. sender, request), but could not find any reference to the function that created the task. I also tried the registered method in the inspect API, but it appears to contain the same task names and no reference to their functions. How can I get a reference to the function that created a task from the result of a celery signal or other parts of it's API? -
How to show data using API in django data table
i have created models.py inside profile_management app. import requests from django.db import models from datetime import date from package_management.models import Package from api_url_config import CREATE_CONNECTION_API_URL class ClientProfile(models.Model): id = models.AutoField(primary_key=True, editable=False) profile_name = models.CharField(max_length=50, default="default_profile") active_status = models.BooleanField(choices=[(True, 'Yes'), (False, 'No')], default=True) subscribed_package = models.ForeignKey(Package, related_name='client_profiles_subscribe', on_delete=models.PROTECT, default=1) plugin_platform = models.CharField(max_length=15, blank=True, null=True) expire_date = models.DateField(default=date.today) company_email = models.EmailField(unique=True, null=True) company_phone = models.CharField(max_length=15, blank=True, null=True) website = models.CharField(max_length=50, null=True) company_address = models.TextField(max_length=255, blank=True, null=True) main_client = models.BooleanField(choices=[(True, 'Yes'), (False, 'No')], default=True) def profile_auto_increment_id(self): if self.pk: return f"#{self.pk}" else: return "(Not saved)" profile_auto_increment_id.short_description = 'ID' def __str__(self): return self.profile_name def save(self, *args, **kwargs): self.send_data_to_api() def send_data_to_api(self): api_url = CREATE_CONNECTION_API_URL data = { "profile_name": self.profile_name, "active_status": self.active_status, "subscribed_package": self.subscribed_package.id, "plugin_platform": self.plugin_platform, "expire_date": str(self.expire_date), "company_email": self.company_email, "company_phone": self.company_phone, "website": self.website, "company_address": self.company_address, "main_client": self.main_client, } try: response = requests.post(api_url, json=data) response.raise_for_status() except requests.exceptions.RequestException as e: print(f"Error sending data to API: {e}") here i have send data to a API without saving on database. previously i stored data on my local database. therefore i could show them on admin. like this, from django.contrib import admin from django.urls import reverse from django.utils.html import format_html from profile_management.models import ClientProfile @admin.register(ClientProfile) class ProfileAdmin(admin.ModelAdmin): list_display = ( 'profile_auto_increment_id', … -
Django djdt_flamegtaph blank?
enter image description here Django djdt_flamegtaph blank? Django 4.2.7 django-debug-toolbar 4.2.0 djdt-flamegraph 0.2.13 Dear friend, why is the page empty? Use python3 manage.py runserver --noreload --nothreading to start django -
How to use both MySQL and MongoDB in Django backend [closed]
I'm going to build a simple user post backend using Django with MySQL and MongoDB. But Django provides SQLite by default and I don't know how to hybrid MySQL and MongoDB and use them in development. Is there anyone who can help me with end-to-end guide? -
cannot accept the name from user input and the file does not enter the image directory located in the scanner directory App
So this program runs smoothly status code 200 and Developer Status does not show error code, I have checked in the models, views, and forms files but the logic of running the system I think is correct. I really appreciate all the help. I alrd try debug from this project Links scanner.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Scanner</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous" /> <style> body { display: flex; flex-direction: column; min-height: 100vh; margin: 0; } main { flex: 1; padding: 20px; } </style> </head> <body> <!-- Navbar --> <nav class="navbar bg-primary-subtle navbar-expand-lg border border-black"> <div class="container-fluid d-flex justify-content-evenly"> <div class="container-fluid d-flex justify-content-start align-items-center"> <i class="fa-brands fa-python fa-2xl pt-0"></i> <p class="fw-bold fs-4 pt-2">Tubes Citra Digital</p> </div> <div class="navbar-collapse collapse d-flex align-items-start"> <ul class="navbar-nav"> <li class="nav-item "> <a class="icon-link icon-link-hover link-offset-2 link-offset-3-hover link-underline link-underline-opacity-0 link-underline-opacity-75-hover" style="--bs-icon-link-transform: translate3d(0, -.125rem, 0);" href="{% url 'home:home_page' %}"> <i class="fa-solid fa-right-to-bracket bi" aria-hidden="true"><use xlink:href="#clipboard"></use></i> Home </a> </li> </ul> </div> </div> </nav> <main> <!-- From file--> <!-- {% url 'cartoon:cartoon_result' %}, Ubah action disini menjadi app dan urls pada setiap APP--> <form id="cartoon-form" action="{% url 'scanner:scanner_page' %}" method="post" class="validate container-fluid d-flex justify-content-center flex-column gap-3" enctype="multipart/form-data" > {% csrf_token %} … -
Transaction atomic with Django signals
Inside the transaction atomic block am updating table1 and creating table2. Where table2 use foreign key of table1. Table1 is updated successfully and table 2 is created. But when django signals of table2 is called, am getting the old instance of table1. I need the latest instance of table1 inside Django signals. -
AWX + Hashicorp Vault django.request Bad Request
In order to improve my AWX management for my team, i'm currently trying to configure Hashicorp Vault Credentials but i'm having some errors and doubt. Usually in my Ansible project I run from a Debian server, I'm used to set up Vault secrets using lookup like this (works in var file or within vars:) ### Vault Configuration ansible_hashi_vault_token="{{ lookup('env','VAULT_ANSIBLE') }}" my_secret="{{ lookup('community.hashi_vault.vault_kv2_get', 'my_secret', engine_mount_point='kv/', token=ansible_hashi_vault_token) }}" #### Credentials (compte de service ansible) #### ansible_user="{{ my_secret.secret.ansible_user_from_vault}}" Ansible will seek for an environment variable which is called 'VAULT_ANSIBLE' that is the result token of an AppRole call to my vault server. It allows to run playbook without writing any token in the code. Now after adding project in AWX, i'm trying to make the Vault part working => I created Credentials with HashiCorp Vault Secret Lookup as you can see here. Simply add Server URL + Token for testing. When I click on Test, no matter what secrets I want to retrieve I always have this error Here's my questions : which log file can give me more information about the credentials/api call to Vault? Is there any thing I miss for this peculiar configuration ? I tried to add my root.CA … -
Psycopg2 - Django 3.0.5
I am trying to makemigrations in my project with Django using postgresql. But I have been having the following error: (agenda_api) C:\Users\felip\OneDrive\Escritorio\Managment\Cursos\Django\agendadj\agenda>python manage.py makemigrations Traceback (most recent call last): File "C:\Users\felip\OneDrive\Escritorio\Managment\Cursos\Django\agenda_api\lib\site-packages\django\db\backends\postgresql\base.py", line 25, in <module> import psycopg2 as Database File "C:\Users\felip\OneDrive\Escritorio\Managment\Cursos\Django\agenda_api\lib\site-packages\psycopg2\__init__.py", line 51, in <module> from psycopg2._psycopg import ( # noqa ImportError: DLL load failed while importing _psycopg: No se puede encontrar el módulo especificado. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\felip\OneDrive\Escritorio\Managment\Cursos\Django\agendadj\agenda\manage.py", line 21, in <module> main() File "C:\Users\felip\OneDrive\Escritorio\Managment\Cursos\Django\agendadj\agenda\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\felip\OneDrive\Escritorio\Managment\Cursos\Django\agenda_api\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\felip\OneDrive\Escritorio\Managment\Cursos\Django\agenda_api\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\felip\OneDrive\Escritorio\Managment\Cursos\Django\agenda_api\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\felip\OneDrive\Escritorio\Managment\Cursos\Django\agenda_api\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\felip\OneDrive\Escritorio\Managment\Cursos\Django\agenda_api\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\felip\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\felip\OneDrive\Escritorio\Managment\Cursos\Django\agenda_api\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\felip\OneDrive\Escritorio\Managment\Cursos\Django\agenda_api\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> class … -
Django Production Deployment Issue: Blog Articles Stacking and Unexpected <strong> Tags
I'm facing a rather perplexing issue with deploying a Django site on which I'm working. I'm using Django version 4.2.5, and my development environment is on Windows. The production deployment is on O2Switch using CPanel. To deploy the code, I'm using CPanel's Python Application Manager and fetching the code via push/pull from GitHub. The problem I'm encountering is as follows: after the production deployment, the blog articles are not displaying correctly. Instead of appearing side by side, they are stacking on top of each other. This issue doesn't occur locally, and upon investigation, I noticed that <strong> tags are being generated with each iteration, disrupting the styling I've implemented. Screen of code with inspector Screen of code with inspector Screen render in prod Screen render in prod I tested the site in a pre-production environment on a test URL (on the same server but in a different directory), and everything works correctly. However, once in production, the issue arises. Do you have any ideas about the possible cause of this unexpected behavior during production deployment? Thanks in advance for your assistance and suggestions! Additional context: Development environment: Windows Production environment: O2Switch with CPanel Django version: 4.2.5 I've included screenshots of … -
Django change fuzzy threshold while running makemessages
When Im running python manage.py makemessages I have fuzzy lines in my django.po file, for example : #, fuzzy #| msgid "Last Month" msgid "Last Year" msgstr "Dernier mois" This is due to the gettext.merge command used by django as explained here : https://hexdocs.pm/gettext/Mix.Tasks.Gettext.Merge.html#module-options To solve this issue, I should use the --no-fuzzy tag or reduce the --fuzzy-threshold. But my issue is that there is no way to do that using django makemessages command (at least I can't find it) Is there a workaround I can use to fix my problem please? -
How to overwirte Django Backend?
I would like to give access to the backend of a Django project for all my users who is registered in a specified Azure AD group. I use django_microsoft_auth package to handle SSO Usage — django-microsoft-auth When I log for the 1st time with an account from Azure AD, the account is created in Django. But I would like to : change the loggin (by default is using the email address as loggin), force is_staff = True and add the user to a django group. I think I must overwrite the authenticate method from BaseBackend. I did follow the doc DjangoProject but I having trouble to make it work urls.py urlpatterns = [ path('admin/', admin.site.urls), path('microsoft/', include('microsoft_auth.urls', namespace='microsoft')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py INSTALLED_APPS = […, 'django.contrib.admin', 'django.contrib.auth', 'microsoft_auth, 'django.contrib.sites' …] AUTHENTICATION_BACKENDS = ["microsoft_auth.backends.MicrosoftAuthenticationBackend","django.contrib.auth.backends.ModelBackend","myproject.signals.SettingsBackend"] ADMIN_LOGIN = env(“my_login”) ADMIN_PASSWORD = env(“my_password_h”) In signals.py (located in the same directory of settings.py) I used the code from the django doc and I try to add a groupe to the user. from django.conf import settings from django.contrib.auth.backends import BaseBackend from django.contrib.auth.hashers import check_password from django.contrib.auth.models import User, Group, Permission class SettingsBackend(BaseBackend): def authenticate(self, request, username=None, password=None): login_valid = settings.ADMIN_LOGIN == username pwd_valid = check_password(password, … -
Why the CSS Styles not working for h1 in home.html file? is there any special method to do styling of for loop elements in django?
[[enter image description here](https://i.stack.imgur.com/jnAJN.png)](https://i.stack.imgur.com/PTYbY.png) I am trying to apply some styling to the list of elements but nothing is working for loop elements. Base.html is working fine i checked there is no error in that. Thanks for your help -
Django models.py I want a function go to a variable
I want the def remain and the result of it to go to the field d_remain but whatever I use the function it doesn't show anything, it shows only negative numbers, this is my code, this is the base code give me a way to make it happen thank you. class sub(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key = True, editable = False) provider = models.CharField(max_length=70) tier = models.CharField(max_length=40) date_started = models.DateField(auto_now=False, auto_now_add=False) date_end = models.DateField(auto_now=False, auto_now_add=False, ) author = models.ForeignKey(User, on_delete=models.CASCADE) price = models.DecimalField(max_digits=7, decimal_places=2, default=0) d_remain = models.IntegerField()#I want the value of def remain go to this filed def remain(self): today = date.today() remaining_days = (self.date_end - today).days return(remaining_days) def get_absolute_url(self): return reverse('sub-detail', kwargs={'pk':self.id}) -
Frontend + backend on aws lightsail
So I have a webapp with reactjs as frontend and django as backend and mysql as database. Now I have my django deployed on heroku which i want to put on my lightsail server as well. My frontend is also deployed on lightsail same as my mysql instance (I did not use containers). It for now only has 1 page as the webapp was not yet ready. Now that everything is ready I want to deploy everything on the Lightsail server. It has 2gb of RAM and 1vCPU. I was wondering what the best way is to go about the deployment of this. My main concern is about concurrent users, with the biggest concern being the backend (not sure how many concurrent users it can hold). So my questions is can this server hold many concurrent users (i know you need more information to calculate this so approximation is fine) I look forward to hearing everyones ideas thanks! -
How can localhost and 127.0.0.1 share the same request in Django/Vue?
In my Django application, I'm authenticating a user on the backend, with port 8000. Upon success, the user is redirected to the frontend on port 5173. After configuring CORS and CSRF correctly, I was able to successfully reproduce this when I accessed localhost:8000/login. It redirected to localhost:5173/ and the authenticated content was provided. The issue is however, when the user attempts to access the URL provided by Django (127.0.0.1:8000), it gets redirected to the localhost:5173 origin, meaning they don't share the same resources as they are different URLs. Are there any practices or workaround in this scenario? Or is it assumed that the user should always be accessing localhost? I tried to execute the same_site= None option, however, I believe that is for HTTPS which I have not configured yet -
Can I generate token using DRF after I validate the user using LDAP?
In the beginning I will ask everyone to excuse me if my question is wrong/not properly framed because I am new starting something new which I am totally not aware of, I need to learn this as it is very much needed for my work. Question goes as below, I am planning to develop a framework using Django, to authenticate users to use my framework I need to validate user using my org LDAP. In my framework I have multiple API endpoints (as I am developing API end points using Django), for each end point I need user to have permission/authentication. Here is the catch, when I am trying to authenticate user using LDAP I am not able to generate tokens (access or refresh). If I generate token I am not able to authenticate user using LDAP. I tried integrating both part but I am getting error ( may be I dont know how to integrate as I am new to Django). I need help from you guys like....I need to validate user using LDAP and after validation I need to generate token (access and refresh). Please help me with this... Below is my code snippet. Code of LDAP validation: … -
how to automatically kill sessions on postgres db in python django, before django tests recreate the db
django recreates our postgres test database on start, however in some cases there are sessions open. I can kill the sessions with SELECT 'SELECT pg_terminate_backend(' || pg_terminate_backend(pg_stat_activity.pid) || ');' FROM pg_stat_activity WHERE pg_stat_activity.datname = 'MY_DBNAME' AND pg_stat_activity.pid <> pg_backend_pid(); but currently, I do that manually as needed from SquirrelSQL. How can this be done automatically before django recreates the DB (very early in the test setup process). THis is needed because otherwise the delete DB fails due to connected sessions. -
Can't figure out how to make a simple "add to favourite" view with Django and HTMX
In my streaming app (for portfolio), I've been trying desperately to make a very simple function to add a film to a user's list. The simple thing : a heart, when you click it adds or removes the film to your list and change the heart colour. I'm trying to make it with a class based view and with HTMX. All of the similar application I found online were made with function based views and older version of Django. I don't want and copy/paste weird code, I want to understand. But whatever I do (just spent 2 hours with ChatGPT, trying a million thing), I keep on getting one of two errors : a Method Not Allowed or a NoReverseMatch. Whatever I do, I get one of these. I've tried many different things, but right now, this is my code : My view : class AddToFavoriteView(CustomLoginRequiredMixin, UpdateView): model = Film fields = ["favorite"] template_name = "includes/heart.html" http_method_names = ["get", "post"] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.object.favorite.filter(id=self.request.user.id).exists(): context["is_favorite"] = True else: context["is_favorite"] = False print(f"is_favorite: {context['is_favorite']}") return context def post(self, request, *args, **kwargs): self.object = self.get_object() print("Trying to add to favs.") film = Film.objects.get(pk=self.object.pk) print(f"{film.title}") if film.favorite.filter(id=request.user.id).exists(): film.favorite.remove(request.user) is_favorite …