Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to change the functionality of the base Django Group model?
I have a Django app with the following architecture; a Company model that holds multiple users (the user is a custom user extending AbstractUser). Each user can only be a member of one Company. We are using the base Django Group model and the base Django permissions as well. We extended the user model, so we can add the company field to it, and make the username unique per company, instead of unique globally. This allows us to have multiple users with the same username, as long as they are not a part of the same company. We want to do the same thing with the groups; be able to have multiple groups with the same name, as long as they are not tied to the same company. At one point, we extended the group model, by inheriting from the base Group model, and added the company field to it, which creates a one to one relationship between our CustomGroup and the base Group. This all works fine. The issue is we cannot find a way to change the logic of the Group model, so that the company and name field are unique together, as opposed to the name being … -
Configuration of docker when deploying react app to choreo
Can someone help me please? I am trying to deploy a react+Django app with choreo but unfortunately when deploying the backend , docker build fails , I don't know what to do**** I did not set up a dockerfile in my project because I thought that choreo would do that for me . Now I don't know how to proceed -
How can i connect my LDAP authentication for Django?
I am currently implementing LDAP authentication to Django. I created the Windows Server VM, and pinged it on my main pc and viceversa, also used ldapsearch -x -H ldap://192.168.0.136 -D "Administrator@statuspage.com" -W -b "DC=statuspage,DC=com" and everything works as it should, however when I try to login on django admin page with the code provided on the ldap documentation it doesn't work, neither on python manage.py shell nor on the localhost/admin page. I've been using STATUSPAGE\Administrator, Administrator@statuspage.com and Administrator alone for username, none works, here is the code I used: import ldap from django_auth_ldap.config import LDAPSearch import logging logger = logging.getLogger('django_auth_ldap') logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.DEBUG) AUTH_LDAP_SERVER_URI = "ldap://192.168.0.136" AUTH_LDAP_BIND_DN = "dc=statuspage,dc=com" AUTH_LDAP_BIND_PASSWORD = "my_password" #in the code I actually put the server password AUTH_LDAP_USER_SEARCH = LDAPSearch( "ou=Users,dc=statuspage,dc=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)" ) AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail", } AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600 AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) Everytime I log with the user on shell I get this error: Caught LDAPError while authenticating STATUSPAGE\jdoe: INVALID_CREDENTIALS({'msgtype': 97, 'msgid': 1, 'result': 49, 'desc': 'Invalid credentials', 'ctrls': [], 'info': '80090308: LdapErr: DSID-0C090439, comment: AcceptSecurityContext error, data 57, v4563'}) -
drf_spectacular not picking up complex objects
I have a serializer that looks something like this (greatly simplified) class MySerializer(serializers.Serializer): parameters = Parameters(many=True, default=[]) class Parameters(BaseSerializer): param_name = serializers.CharField(required=True, allow_blank=False) param_count = serializers.IntegerField(required=True) The drf_spectacular annotations are @extend_schema( request=None, responses={ 200: MySerializer, 400: ErrorResponseSerializer, 500: ErrorResponseSerializer }, description="Load all data" ) The swagger that is being generated for the parameters field is "parameters": [], How can I get it to generate the contents of the list with a sample parameter object. Why isn't drf_spectacular picking it up from the serializers? -
Using Wagtail with the contrib_Table_block doesn't seem to work the same as other fields
I've been following the reference in the wagtail docs on the Table_block contrib setup. The suggested method is to make this an insert to StreamField, which works fine for me for every type of block or field except TableBlock().When using Table_block via either the docs or inserting it into an already working tutorial, it doesn't hook into the database data. In other words, most of my pages will be populated from database fields into tables. So, using the Table_Block() or TypedTableBlock() blocks makes the most sense. Whenever I do that, I get table setup info rather than data in the table. I took a simple Streamfield tutorial and inserted TableBlock() as an insert into StreamField as the reference suggests. Here is my code: ` from django.db import models from wagtail import blocks from wagtail.models import Page from wagtail.search import index from wagtail.fields import StreamField from wagtail.admin.panels import FieldPanel from wagtail.contrib.table_block.blocks import TableBlock class ScriptsPage(Page): template = 'scripts/scripts.html' script_content = StreamField([ ('paragraph', models.Scripts()), ], ) content_panels = Page.content_panels + [ FieldPanel('script_content'), ] class Scripts(TableBlock): table = ( [ # ('script_select', blocks.CharBlock(max_length=20)), ('script_name', blocks.CharBlock(max_length=20)), ('script_desc', blocks.CharBlock(max_length=200)), # body = blocks.RichTextBlock(blank=True, name="body") ('script_path', blocks.CharBlock(max_length=20)), ('script_file', blocks.CharBlock(max_length=20)), ('script_args', blocks.CharBlock(max_length=100)), ('script_output_json', blocks.CharBlock(max_length=200)), ('script_on_demand', blocks.CharBlock(max_length=50)), ('script_sched_name', … -
Apache LimitRequestBody not taking effect when using ProxyPass
I'm developing an application with Django and I'm using gunicorn and apache to deploy it. The application allows submitting images as a multipart form. I have put in place a mechanism to limit the size of the image and the dimension at Django level. I would like to limit the file size that are passed to Django at Apache level. Images are stored and retrieved with Django, so apache is not serving nor storing these uploaded images. This is the apache configuration: <VirtualHost *:443> ServerName myserver.com ServerAdmin email@example.com # limit size of the body to 10mb LimitRequestBody 10485760 Alias "/static" "/path/to/static/" <Directory /path/to/static/> Require all granted </Directory> ProxyPass /static ! # set this header to allow gunicorn to know if request is https or not RequestHeader set X_FORWARDED_PROTO 'https' env=HTTPS ProxyPreserveHost On ProxyPass / http://127.0.0.1:8500/ ProxyPassReverse / http://127.0.0.1:8500/ SSLEngine on SSLCertificateFile /path/to/certificate.pem SSLCertificateKeyFile /path/to/privatekey.pem LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\" %{ms}T" combined_with_time CustomLog ${APACHE_LOG_DIR}/path/to/logs/access.log combined_with_time ErrorLog ${APACHE_LOG_DIR}/path/to/logs/error.log </VirtualHost> With the apache configuration provided, I would expect that uploading a file bigger than 10mb (I'm using a file of about 200mb to test things) apache would return a 413 Request Entity Too Large. But the file is … -
configure django storages with sftp server , docker local project
I was trying to configure django-storages to use sftp server to upload static and media to the sftp, however when I do collectstatic it shows "timeout" error here is my django conf. USE_NNUH = os.environ.get('USE_NNUH') == 'TRUE' if USE_NNUH: STATICFILES_STORAGE = "storages.backends.sftpstorage.SFTPStorage" # SFTP Storage settings SFTP_STORAGE_HOST = 'cdn.???.org' SFTP_STORAGE_ROOT = '/var/www/html/static/' SFTP_STORAGE_PARAMS = { 'username': '', 'password': '', 'allow_agent': False, } STATIC_URL = 'http://cdn.????.org/static/' else: STATIC_URL = os.path.join(PROJ_DIR, 'public/static/') DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage' STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' I have installed paramiko ( latest version) and I have debug the code, it always stick on connect method and return Timeout error. another note: my local project works by docker, so when I do the command "collectstatic" I use it inside docker container.. so I think the docker is not able to reach the sftp server... and this is my docker conf for the network: networks: default: ipam: config: - subnet: 192.168.181.0/24 any help would be appreciated ? on how to connect my web app to the sftp server.. I'm trying from days with no luck... -
iOS QR Code Scan Results in Timeout Error, Works Fine on Android
I am working on a web application where users can scan a QR code to proceed with a transaction. The following JavaScript functions handle the QR code scan status and redirect the user based on the status: postScanStatusAndRedirect() is called after a QR code is scanned. checkQRStatus() periodically checks the status of the QR code. The problem I'm encountering is that when scanning a QR code on iOS devices (Safari browser), I get a timeout error, and the following SweetAlert message is shown: "Your transaction time has expired. Please scan the QR code again". However, the same code works perfectly fine on Android devices and other browsers. async function postScanStatusAndRedirect() { try { const cacheBuster = new Date().getTime(); // Prevent caching with a unique query parameter const response = await fetch(`https://stg-api.goldatm.in/api/qrcode-status?cb=${cacheBuster}`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' // More aggressive cache prevention }, body: JSON.stringify({ status: 1 }), credentials: 'same-origin' // Include credentials if needed }); if (!response.ok) { throw new Error(`Network response was not ok: ${response.statusText}`); } const data = await response.json(); console.log('Scan status posted', data); setTimeout(() => { console.log('Redirecting to:', "{% url 'login' %}"); window.location.href = "{% url 'login' %}"; }, 100); // Adjust delay … -
django-import-export Customize admin import forms do not insert value
I am using django-import-export to manage CSV uploads. I have vanilla import working and now want to insert 'retailer' via admin interface. I can select values, but when I submit data, it does not insert. #admin.py @admin.register(Product) class CustomProductAdmin(ImportMixin, admin.ModelAdmin): resource_class = ProductResource import_form_class = ProductImportForm confirm_form_class = ProductConfirmImportForm def get_confirm_form_initial(self, request, import_form): initial = super().get_confirm_form_initial(request, import_form) if import_form: initial['retailer'] = import_form.cleaned_data['retailer'].id return initial def get_import_data_kwargs(self, request, *args, **kwargs): """ Prepare kwargs for import_data. """ form = kwargs.get("form", None) if form and hasattr(form, "cleaned_data"): kwargs.update({"retailer": form.cleaned_data.get("retailer", None)}) return kwargs def after_import_instance(self, instance, new, row_number=None, **kwargs): if "retailer" in kwargs: instance.retailer = kwargs["retailer"] #forms.py class ProductImportForm(ImportForm): retailer = forms.ModelChoiceField( queryset=Retailer.objects.all(), required=True) class ProductConfirmImportForm(ConfirmImportForm): retailer = forms.ModelChoiceField( queryset=Retailer.objects.all(), required=True) #resource.py class ProductResource(resources.ModelResource): class Meta: model = Product code is simplified I want to choose the retailer myself when importing data -
Django override datetime format in browsers [closed]
I am unable to set a datetime format to my django app and the datetime format does not look the same in different browsers. How to set datetime field format in Django? Currently the datetime field looks like: in MS EDGE datetime field in microsoft edge in Google CHROME datetime field in google chrome I have tried setting datetime field formats in forms.py and I have changed the parameter USE_I18N = False setting.py file. What else could I try to set a datetime field format in my django app? -
Django: managment command for project
I have a django project with several apps; I have registered custom management commands for several of the apps and that works as intended. However now I would like to add a management command for the entire site which is not related to any specific app - is that possible? Have tried putting a managment command in site/management/commands but then manage.py did not find my command. -
Django Rest Framework Token Authentication Not Working in production
I have deployed the Django Application on VPS server with following configuration. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "rest_framework", "rest_framework.authtoken", "stocks", "stock_api", ] # REST Framework Configurations REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.TokenAuthentication", ], 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } I have tested the following code on my local machine and it works well. But in production, it shows an error as Credential not provided. import requests headers = {"Authorization": "Token 0f2c3e612ffba7d7b45164b8c8567dc56c113347"} response = requests.get(endpoint, headers=headers) print(response.status_code) print(response.json()) Error status_code : 401 { "detail": "Authentication credentials were not provided." } I have tested the same Code on my local machine, but it is showing ok status. -
FieldError: Cannot resolve keyword 'username' into field
Using Django 4.2.5, Django-cms 4.1.2, python3.11 I was in the process of trying to enter the content for a static_alias field when I got this error: Internal Server Error: /en/admin/djangocms_alias/alias/1/change/ django.core.exceptions.FieldError: Unsupported lookup 'username' for BigAutoField or join on the field not permitted. django.core.exceptions.FieldError: Cannot resolve keyword 'username' into field. Choices are: created_usergroups, created_users, djangocms_usersettings, email, filer_clipboards, filer_folder_permissions, filer_owned_folders, first_name, globalpagepermission, groups, id, is_admin, is_staff, is_superuser, last_login, last_name, locking_users, logentry, owned_files, pagepermission, pageuser, password, statetracking, student, teacher, user_permissions, version I am using an abstract user model: Models.py class UserProfile(PermissionsMixin, AbstractBaseUser): email = models.EmailField(_('Email Address'), unique=True) password = models.CharField(_('Password'), max_length=255) is_admin = models.BooleanField(default=False, verbose_name='Is Admin') is_staff = models.BooleanField(default=False, verbose_name='Is Staff') first_name = models.CharField( default='', max_length=255, verbose_name='First Name') last_name = models.CharField( default='', max_length=255, verbose_name='Last Name') is_superuser = models.BooleanField( default=False, verbose_name='superuser') USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = UserProfileManager() class Meta: verbose_name = _('User Profile') def __str__(self): return self.email Managers.py class UserProfileManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def _create_user(self, email, password, **extra_fields): """ Create and save a user with the given email, and password. """ if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user … -
how to filter model by foreignkey in django's admin forms?
I'm using django 3.2 I have those models. When adding an item to database through django's admin I'd like to be able to after choose the Disciplina (discipline) item, when I'd choose the assunto(subject) the assunto would be filtered by the subjects of the Discipline chosen above. How to do it in pure django (without javascript)? from django.db import models # Create your models here. class Base(models.Model): criacao = models.DateTimeField(auto_now_add=True) atualizacao = models.DateTimeField(auto_now=True) ativo = models.BooleanField(default=True) class Meta: abstract = True class Disciplina(Base): ORIGEM_CHOICES = [ ('PT', 'Exame Nacional Português'), ('BR', 'ENEM Brasil'), ('SUPERIOR', 'Nível Superior'), ] nome = models.CharField(max_length=100, unique=True) origem = models.CharField(max_length=8, choices=ORIGEM_CHOICES) def __str__(self): return f"{self.nome} ({self.get_origem_display()})" class Assunto(Base): nome = models.CharField(max_length=100) disciplina = models.ForeignKey(Disciplina, on_delete=models.CASCADE, related_name='assuntos') def __str__(self): return f"{self.nome} ({self.disciplina.nome})" class Questao(Base): disciplina = models.ForeignKey(Disciplina, on_delete=models.CASCADE) assunto = models.ForeignKey(Assunto, on_delete=models.CASCADE) latex_text = models.TextField(blank = True, null=True) # Novo campo para texto em LaTeX math_jax = models.TextField(blank = True, null = True) gabarito = models.CharField(max_length = 200) dificuldade = models.CharField(max_length = 10, choices=[ ('FACIL', 'Fácil'), ('MEDIO', 'Médio'), ('DIFICIL', 'Difícil'), ]) imagem = models.BooleanField(default = False) link_imagem = models.URLField(blank =True, null=True) link_bucket = models.URLField(blank = True, null=True) def __str__(self): return self.latex_text admin.py from django.contrib import admin from … -
Mailgun in Django Projekt einbinden
Ich versuche die Mailgun Api in mein Django React Projekt einzubinden. enter image description here Dies ist meine Api view: enter image description here und das meine url: enter image description here Wenn ich in dem Browser die url öffne und die email als parameter eingebe kommt dieser fehler: enter image description here Kann mir dabei jemand helfen, die Fehlermeldung wegzubringen. Vielen Dank im Voraus. -
Set admin field short_description dynamically in Django, without trigerring APPS_NOT_READY_WARNING_MSG
I'm encountering the APPS_NOT_READY_WARNING_MSG after updating to Django 5.0. The warning appears in the admin when using a custom field description set via @admin.display(). I need to include these custom columns in my list_display, where they are dynamically calculated based on the current_year retrieved from the database. Here’s an example from my admin mixin: from app.models import FiscalYear class MyAdmin(admin.Modeladmin): current_fiscal_year = FiscalYear().get_current_fiscal_year() @admin.display(description=f"FY{current_fiscal_year}") def total_exercice_courant(self, obj): total_exercice_n = obj.get_montant_exercice_n(year_n=0) return format_number_euro(total_exercice_n) if total_exercice_n else "-" To determine whether the column should be labeled FY24, FY25, etc., I currently make a database call (current_fiscal_year = FiscalYear().get_current_fiscal_fiscal_year()). However, this call during initialization is causing the issue. How can i update my admin field short_description later than at import ? -
Adding percentage of student marks in display table in a crud program in Django
<table> {% for data in result %} <tr> <td>{{ data.id }}</td> <td>{{ data.name }}</td> <td>{{ data.marks1 }}</td> <td>{{ data.marks2 }}</td> <td>{{ data.marks3 }}</td> <td>{{ data.marks4 }}</td> <td> {% with data.marks1|add:data.marks2|add:data.marks3|add:data.marks4 as total %} {{ total }} {% endwith %} </td> </tr> {% endfor %} </table> //show.html(above code) - This is without the math-filters function //views.py from django.http import HttpResponse from django import template from django.shortcuts import render from .models import Student def add(request): if request.method == 'POST': if request.POST.get('name') and request.POST.get('marks1'): stud = Student() stud.name = request.POST.get('name') stud.marks1 = request.POST.get('marks1') stud.marks2 = request.POST.get('marks2') stud.marks3 = request.POST.get('marks3') stud.marks4 = request.POST.get('marks4') stud.save() return render(request, 'add.html') else: return render(request, 'add.html') def show(request): data = Student.objects.all() return render(request, 'show.html', {'result': data}) register = template.Library() @register.filter def div(value, arg): try: return float(value) / float(arg) except (ValueError, ZeroDivisionError): return None I tried adding this after the td tag which has the total function hoping it would work but it ends up displaying an error. {% load math_filters %} <td> {% with total=data.marks1|add:data.marks2|add:data.marks3|add:data.marks4 %} {{ total|div:"4"|floatformat:2 }} {% endwith %} </td> enter image description here Image of the error that occurs. -
Superadmin login is asking for staff account
I am trying to create a custom user model in my Django project. Here are my code: models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager ############# Handles the creation of regular users and # superusers (admin users) with custom logic. ############ class MyAccountManager(BaseUserManager): # Creates a regular user with the necessary fields def create_user(self, first_name, last_name, username, email, password=None): if not email: raise ValueError('User must have an email address') if not username: raise ValueError('User must have a username') user = self.model( email = self.normalize_email(email), # This line normalizes the email address #that means it converts the domain part of the email address to lowercase. username = username, first_name = first_name, last_name = last_name, ) user.set_password(password) user.save(using=self._db) return user # Creates a superuser with the necessary fields def create_superuser(self, first_name, last_name, username, email, password=None): user = self.create_user( # This line calls the create_user method to create a regular user. email = self.normalize_email(email), username = username, first_name = first_name, last_name = last_name, ) user.is_admin = True user.is_staff = True user.is_active = True user.is_superadmin = True user.save(using=self._db) return user ######################## This is a custom user model that represents a user # with fields that go beyond the default Django user model.################# … -
Django User as foreignKey has strange behaviour
I am building a restful API in Django and I have noticed something quite odd! This is my Topic Model: class Topic(models.Model): """ Topic base model""" owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=150, blank=False, null=False) content = models.CharField(max_length=500, blank=False, null=False) date_added = models.DateTimeField(auto_now_add=True, editable=False) def __str__(self): return self.title And this is my serializer: class TopicSerializer(serializers.ModelSerializer): """Serializer for the Topic model""" user = serializers.ReadOnlyField(source='owner.username') class Meta: model = Topic exclude = ['owner'] extra_kwargs = {'pk': {'read_only': True}, 'owner': {'read_only': True}} As you can see owner is excluded, but when I make a get request /api/topics/1/ at my Topic ModelViewSet, I get: {"id":1,"user":"Javad","title":"a","content":"b","date_added":"2024-08-25T19:57:00.712475Z"} And when I include owner in my serializer I get: {"id":1,"user":"Javad","title":"a","content":"b","date_added":"2024-08-25T19:57:00.712475Z","owner":"90f8d3d9-08c2-4890-9ba6-3e6f912b10ee"} So why exactly does Django add a "user" field to my model? I guess this must be intentional and unique to user Model, right? Can I control this? -
Cannot resolve "missing" python package (it isn't missing!) when trying to run open source AI program
I'm rather new to python and AI. I want to use the popular package label-studio to build training data using images that I'll apply the AI labelling steps on. The problem is that after cloning the repo from github and following all the instructions, I'm getting the following error: Traceback (most recent call last): File "/Users/markalsip/label-studio/label_studio/manage.py", line 11, in from django.conf import settings ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/markalsip/label-studio/label_studio/manage.py", line 18, in raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? The first problem is that django IS installed and my PYTHONPATH environment variable, by all means at my disposal, is correct: django-admin --version returns: 3.2.25 echo $PYTHONPATH returns: /Users/markalsip/label-studio/env/lib/python3.12/site-packages: I should point out the instructions for this program indicate I should run it in what I believe to be a virtual environment. I have done this (my current root folder is Marks-MBP:label-studio, thus the text shown in the prompt): Marks-MBP:label-studio markalsip$ source /Users/markalsip/label-studio/env/bin/activate (env) Marks-MBP:label-studio markalsip$ python --version returns: Python 3.12.0 To run the python … -
"detail": "Authentication credentials were not provided." drf
I'm doing a pet project. And I need to make that only authorized users can make POST/PATCH requests, and that only the owners of items can change/delete them. views.py(item_app) class CreateItemView(APIView): serializer_class = CreateItemSerializer authentication_classes=[OwnAuthentication] permission_classes=[IsAuthenticatedOrReadOnly, IsOnwerOrReadOnly] ... code ... permissions.py(item_app) from rest_framework import permissions class IsOnwerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.owner == request.user authentication.py(auth_app) from django.contrib.auth.models import User from rest_framework import authentication from rest_framework import exceptions class OwnAuthentication(authentication.BaseAuthentication): def authenticate(self, request): username = request.data.get('username') if not username: return None try: user= User.object.get(username=username) except User.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') return (user, None) settings.py AUTH_USER_MODEL = "auth_app.Users" REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES':[ 'rest_framework.parsers.JSONParser', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], } [Authorization is done via JWT tokens, at login I get access token and copy it and paste it into header “Authorization” in postman, and when I enable this header there is still an errorenter image description here]1 -
How to handle custom error message for Django Admin panel save_model method?
I've overwritten a save_model method for ModelAdmin. Let's say like below: def save_model( self, request, obj, form, change, ): if not change: try: if True: raise exceptions.ValidationError( _(f"Oh no, record can't be created for serious reason!") ) except exceptions.ValidationError as err: messages.set_level(request, messages.ERROR) self.message_user(request, err.message, level=messages.ERROR) return super().save_model(request, obj, form, change) I can't use Form, since I need database access to validate business logic. This almost worked, nevertheless I get redirect to main admin panel screen with I don't really like. Moreover, there is ADDITIONAL message displayed, that object does not exist (of course it doesn't exist, since it wasn't created). I will appreciate any tips how to stay on current screen and display just a custom message or at least be redirect to main admin panel screen, but without displaying additional message (just my custom one). -
Trying to run django for the first time
I can't access files in my app hello in my template, rendering them does not work. Here is my github repo to understand the issue https://github.com/Firiceee/Bug_django . I tryed to understand where does the problem come from as u can see with the exept, and effectively it triggers the except, furthermore, the last render, simpler does already not work, it's like , I can't access my directory "templates"... -
Session ID Returns None After Setting Session Data in Django with React Frontend
I'm working on a Django backend with a React frontend and using sessions to manage user authentication. After successfully logging in a user, I'm setting session data (e.g., user_id, name, email, etc.), but the session ID is returning as None despite the session data being correctly stored. I've configured SESSION_ENGINE to use the database and set SESSION_SAVE_EVERY_REQUEST = True. CORS headers are properly configured with CORS_ALLOW_CREDENTIALS = True. Despite these settings, the session ID isn't being generated or returned correctly, which is causing issues with session management on the client side. How can I resolve this issue and ensure the session ID is properly generated and accessible after login?(https://i.sstatic.net/EawnCfZP.png) I configured Django's session settings to use database-backed sessions, set SESSION_SAVE_EVERY_REQUEST = True, and enabled CORS with credentials. I expected the session ID to be generated and returned after a user logs in, allowing for proper session management. However, the session ID is returning as None, even though the session data is correctly stored and accessible. I’ve also verified that CORS and session settings are properly configured but still face the issue.enter image description here -
Integrating Strapi with existing backend and database
I’m working on a website that uses a Django backend with NextJS frontend. The database used is PostgreSQL. The website can be considered as an affiliate marketing platform. So a lot of features involving brands and products are present. Now a new Strapi CMS was decided to be added to the website for handling brand and products. So the django backend will be used for all the other functions while the direct CRUD of the brands and products will be handled by Strapi. But strapi flushes the entire connected database and I don’t want to set the entire database schema in strapi since it uses only brands and products - two tables. While the current backend has about 50 tables. So this means that Strapi would require a new database instance. Now, product and brand data is also needed by the existing django backend for some functions. So is there a way that I can just use Strapi for its frontend and further plugins while I can continue to use Django as the backend.