Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connecting to snowflake in django using proxy
I have deployed my django app on heroku and I want to connect to snowflake. But whenever I redeploy, IP changes and my app is not able to connect to snowflake(IP whitelisting issue). I have tried to use fixie as a proxy so that when I connect to snowflake, my IP doesnt change and I don't need to get it whitelisted. Below are two code snippets I have been using to connect to snowflake. But my app keeps trying to connect using my network IP and not the proxy. MY IMPORTS: from sqlalchemy import create_engine from sqlalchemy import text import requests import snowflake import snowflake.connector snippet 1: engine = create_engine( 'snowflake://{user}:{password}@{account}/{database}/{schema}'.format( user=connection_details["user"], password=connection_details["pw"], account=connection_details["account"], database=connection_details["database"], schema=connection_details["schema"], ), connect_args={ 'proxy': 'http://fixie:kT8kuyNpPbrbdx@velodroll.usefixie.com:80' }) snippet 2: engine = snowflake.connector.connect(user=connection_details["user"],password=connection_details["pw"],account=connection_details["account"],database=connection_details["database"],schema=connection_details["schema"],connect_args={'proxy': 'http://fixie:kT8djczxc14@velodsad.usefixie.com:80'}) and the error i keep getting : snowflake.connector.errors.DatabaseError: 250001 (08001): Failed to connect to DB: pv40812.east-us-2.azure.snowflakecomputing.com:443. IP address 169.169.169.69 is not allowed to access Snowflake. Contact your account administrator. For more information about this error, go to https://community.snowflake.com/s/ip-xxxxxxxxxxxx-is-not-allowed-to-access. I tried to connect to snowflake through fixie proxy but it keeps ignoring it -
Alternative Solutions for Syncing PostgreSQL Databases Across Machines
I possess two machines: My laptop, which operates on Ubuntu 22.04. OKD (Openshift container) that runs on CentOS 7. My objective is to synchronize a PostgreSQL database between these two machines. Initially, I planned to utilize Rsync to ensure that the PostgreSQL data directory remains consistent on both machines. However, this method is likely to fail due to the differences in configuration files between the two systems. An alternative approach involves using the psql_dump command to export the database from one machine and then importing it on the other. Are there any other solutions available for scenarios like this (Note that this database is used for a Django project)? -
Issue with creating different profiles in Django signals
I'm facing an issue in my Django application where I need to create different profiles, either Profile1 or Profile2, based on the value of user.is_manager. I'm utilizing signals to handle this logic. Here is a summary of the problem: I have two profile models: Profile1 and Profile2. Profile1 is intended for manager users, while Profile2 is for non-manager users. In my managers.py file, I set user.is_manager to True for manager users during the creation of a user. However, when I try to access instance.is_manager in my signals.py file, it consistently returns False, even though it should be True according to the value set in managers.py. Any suggestions or insights to resolve this issue would be greatly appreciated. # managers.py: from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): def create_user(self, phone, username, email, password): user = self.model(phone=phone, username=username, email=email) user.set_password(password) user.save(using=self.db) return user def create_superuser(self, phone, username, email, password): user = self.create_user(phone, username, email, password) user.is_admin = True user.is_manager = True user.save(using=self.db) return # apps.py: from django.apps import AppConfig class PanelConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'panel' def ready(self): import panel.signals # signals.py from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from .models import User, Profile1, Profile2 @receiver(post_save, sender=User, … -
Upload excel sheet and insert excel sheet data into database along with some custom fields from Django admin panel
I am at beginner level in django and trying to upload excel file from Django admin and want to insert it's data into the database with some other custom fields from Django Admin. However, I am able to create the final object with all data but on final insertion I am getting 'No reverse match error'. Actual Error Note : I didn't create any view or did any URL configurations as it is admin panel and whatever examples I saw didn't see any other configurations. I wrote the following code to achieve this. Thanks in advance for your help! # model.py from django.db import models from django.urls import reverse class tblform(models.Model): ALSName = models.CharField(max_length=100) Study = models.CharField(max_length=100) FormId = models.CharField(max_length=100,primary_key=True) DraftName = models.CharField(max_length=100) OID=models.CharField(max_length=100) Ordinal = models.IntegerField(blank=True,null=True) DraftFormName = models.CharField(max_length=100) DraftFormActive = models.BooleanField(default=False) HelpText = models.CharField(max_length=100,blank=True,null=True) IsTemplate = models.BooleanField(default=False) # forms.py from django import forms from .models import tblform class tblform_Form(forms.ModelForm): excel_file = forms.FileField(required=False) class Meta: model = tblform fields = ('ALSName','Study','DraftName') # admin.py from django.contrib import admin from .models import tblform from .forms1 import tblform_Form import openpyxl class ProductAdmin(admin.ModelAdmin): form = tblform_Form def save_model(self, request, obj, form, change): if 'excel_file' in request.FILES: excel_file = request.FILES['excel_file'] #form_data = self.get_form(request).cleaned_data field_names … -
Catch and send the Integrity error in the response in Django rest Framework
In the application I want to catch the Integrity error, format it and send to the user for which I am doing something like this: class ProductUploadAPIView(APIView): @transaction.atomic def post(self, request): owner = request.user.pk d = request.data.copy() d['owner'] = owner file_obj = request.FILES['document'] df = pd.read_excel(file_obj) df = df.reset_index() error_details = [] # List to store error details for index, row in df.iterrows(): try: product = Product.objects.create( name=row['name'], sku=row['sku'], product_unit_id=row['product_unit_id'], ..... rest of the code except IntegrityError as e: error_msg = str(e) print("error message", error_msg) detail = error_msg.split('DETAIL: ')[1] error_details.append({'row': index + 2, 'detail': detail}) except Exception as e: error_msg = str(e) error_details.append({'row': index + 2, 'detail': error_msg}) if error_details: return Response({'errors': error_details}, status=status.HTTP_400_BAD_REQUEST) return Response("File uploaded successfully") But it doesn't return any response and give the integrity error directly which is not very readable to the user What changes should be made to send the column and row of the origin of error? -
Custom DjangoModelPermissions not being applied
I have a Django app that allows a user to be a member of multiple Organizations. from django.conf import settings from app.shared.models import BaseModel class Organization(BaseModel): name = models.CharField(max_length=256) class OrganizationMember(BaseModel): ROLE_OPTIONS = ( (OrganizationMemberRole.admin.value, _('Admin')), (OrganizationMemberRole.editor.value, _('Editor')), (OrganizationMemberRole.view.value, _('View Only')), ) organization = models.ForeignKey( Organization, related_name='members', on_delete=models.DO_NOTHING, ) user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='user_role', on_delete=models.DO_NOTHING, ) I've also got a custom user model with a property that generates a list of Organization IDs for that user from django.contrib.auth.models import AbstractUser from django.db import models from .managers import CustomUserManager class User(AbstractUser): username = None email = models.EmailField(max_length=254, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email @property def user_organization_ids(self): """ Returns a list of Organization IDs. Converts UUID to str """ user_orgs_qs = self.user_role.all().values_list('organization_id', flat=True) return [str(i) for i in user_orgs_qs] There are other models in the database that will have a relationship with an Organization. For example, Widget from app.shared.models import BaseModel class Widget(BaseModel): organization = models.ForeignKey(Organization, on_delete=models.DO_NOTHING) I want to restrict CRUD operations based on OrganizationMember relationships. So, a user should only be able to perform CRUD operations on Widget if they are a member of the Organization. I've created from rest_framework.permissions import DjangoModelPermissions … -
Fatal error in launcher : when using Django
When running the command "pip install openpyxl" in PowerShell on Windows, I encountered the following error: Fatal error in launcher: Unable to create process using '"C:\Python311\python.exe" "C:\Python311\Scripts\pip.exe" install openpyxl': The system cannot find the file specified. How can I resolve this issue and successfully install the "openpyxl" package using pip? enter image description here I'm working on a Django project and I want to integrate Excel functionality. I'm trying to display data from my database, but I'm encountering the following error: "Fatal error in launcher: Unable to create process using '"C:\Python311\python.exe" "C:\Python311\Scripts\pip.exe" install openpyxl': The system cannot find the file specified." I believe this error is related to installing the openpyxl package using pip. Can someone please provide guidance on how to resolve this issue and successfully work with Excel in Django? Thank you in advance! -
How to send email to specific subscriber from the topic in AWS SNS
I have created one topic in AWS SNS. This topic contains many subscribers whose Protocol is Email and whose Endpoint is their email address. I have one API in Django which will send the email to the current user. So for this, I will fetch all the subscribers from the topic and match the email. If a match is found, I want to send an email to that particular subscriber. If a match is not found, I will create a new subscriber with that email address and send an email to it. I want to know how can we do that. What should be written in self.sns_client.publish() method. -
How to create a mobile app with django, with the same codebase?
I am trying to build an ERP system, same as TRYTN, ERPNEXT, ODDO. For the web version, I decided to go with Django and React. What I want is to have a mobile app of the same system too. Now my problem is to choose what tech stack to use for it. My company donot want to go with React Native for it. They want a solution with python itself. So I would like to know what option do I have , with python. This erp is really a data heavy software, there will be tens of thousand of records to be fetched at each api request. I looked at FLET(Write flutter app with python) framework, but it is really new. So any suggestion will be appreciated? I have tried to look at the code base of odoo/ tryton, but could not get any insight, as to how are they doing it. -
Facing a Cors error but that is already enabled in Django rest framework and react
I am facing one issue in my app which is developed in react and Django rest framework. In DRF api i am uploading the video and playing in react app. But video player slider not working then i have enabled the byte range request in my django rest app. But when i am enabling that setting then it giving a cors error in vtt Caption file. and also getting a cors error while downloading a pdf file from react app but when i am disabled the byte range request the video player slider not working but pdf downloading and video caption file working fine. Here is the code of byte range request in django rest app. byte range request code Please share your suggestions thanks i have enabled the byte range request in my django rest app. But when i am enabling that setting then it giving a cors error in vtt Caption file. and also getting a cors error while downloading a pdf file from react app but when i am disabled the byte range request the video player slider not working but pdf downloading and video caption file working fine. -
Could not find config for 'static files' in settings.STORAGES
This error occurs when running Django 4.2.The Default: django.contrib.staticfiles.storage.StaticFilesStorage has been deprecated. -
Problems to install Django in Windows
Now I'm using Windows10 and Python in vscode, When I tried to install Django by %pip install Django, there's the following error: Could not fetch URL https://pypi.org/simple/django/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/django/ (Caused by SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1131)'))) - skippingNote: you may need to restart the kernel to use updated packages. Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1131)'))) - skipping WARNING: Ignoring invalid distribution -orch (d:\program files\anaconda\lib\site-packages) WARNING: Ignoring invalid distribution -cipy (d:\program files\anaconda\lib\site-packages) WARNING: Ignoring invalid distribution -orch (d:\program files\anaconda\lib\site-packages) WARNING: Ignoring invalid distribution -cipy (d:\program files\anaconda\lib\site-packages) WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1131)'))': /simple/django/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1131)'))': /simple/django/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1131)'))': /simple/django/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLEOFError(8, 'EOF … -
User sign-in process in Django not working properly
I'm encountering an issue with the user sign-in functionality in my Django application. When attempting to sign in a user, I'm consistently receiving an error message stating "email and/or password is not valid!" instead of successfully logging in the user. I have verified that the email and password inputs are correct. I've also checked my code and ensured that I'm using the authenticate() and login() functions correctly. here is the code i tried, keep in mind that i am able to regester new users but not able to sign them in: def signup(request): # Extract data from form and assign it to variables. if request.method =='POST': username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] confirm_password = request.POST['confirm_password'] # Check if user exists. user_exsit = User.objects.filter(Q(username = username) | Q(email = email)).exists() if user_exsit: error_message= 'User name or email already exists!' return render(request, 'user_auth/signup.html', {'error_message': error_message}) # Check if the password match. ((JS)) if password != confirm_password: error_message = "Password does not match!" return render(request, 'user_auth/signup.html', {'error_message': error_message}) # Create new user. else: user = User.objects.create_user(username = username, email = email, password = password) user.set_password(password) user.save() return render(request, 'user_auth/signin.html') else: return render(request,'user_auth/signup.html') def signin(request): # Extract data from form. if … -
Trouble Getting Django to Access the Correct Static Directory
I'm having trouble getting Django/Wagtail to access the correct static directory. As a result, all static files are returning 404. This is in a local/dev environment. I currently have: PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(PROJECT_DIR) STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] STATICFILES_DIRS = [ os.path.join(PROJECT_DIR, "static"), ] STATICFILES_STORAGE = "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = "/static/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = "/media/" I'm using the following structure: my-project ├── apps │ └── app_1 │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py ├── myproject │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-35.pyc │ │ └── settings.cpython-35.pyc │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── media ├── static └── templates Django is trying to access: my-project\myproject\static which doesn't exist. When I try to move it to the correct directory, I get the following error: ?: (staticfiles.E002) The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting. For example, I've tried: STATICFILES_DIRS = [ os.path.join(PROJECT_DIR, "..", "static"), ] To get it to move up a dirrectory, but that results in the error above. Also, I've run collectstatic. -
ModuleNotFoundError: No module named 'projectName' - wsgi Django reployment
I am trying to run my Django Project using Apache. When I launch Apache I receive an 'Internal Server Error', inspecting the logs I have found that it fails to execute the wsgi.py for my project and throws the errors below. mod_wsgi (pid=5128): Failed to exec Python script file 'C:/Env/localassets/localassets/wsgi.py'., referer: http://localhost/ mod_wsgi (pid=5128): Exception occurred processing WSGI script 'C:/Env/localassets/localassets/wsgi.py'., referer: http://localhost/ Traceback (most recent call last):\r, referer: http://localhost/ File "C:/Env/localassets/localassets/wsgi.py", line 16, in <module>\r, referer: http://localhost/ application = get_wsgi_application()\r, referer: http://localhost/ File "C:\\Env\\Lib\\site-packages\\django\\core\\wsgi.py", line 12, in get_wsgi_application\r, referer: http://localhost/ django.setup(set_prefix=False)\r, referer: http://localhost/ File "C:\\Env\\Lib\\site-packages\\django\\__init__.py", line 19, in setup\r, referer: http://localhost/ configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)\r, referer: http://localhost/ File "C:\\Env\\Lib\\site-packages\\django\\conf\\__init__.py", line 102, in __getattr__\r, referer: http://localhost/ self._setup(name)\r, referer: http://localhost/ File "C:\\Env\\Lib\\site-packages\\django\\conf\\__init__.py", line 89, in _setup\r, referer: http://localhost/ self._wrapped = Settings(settings_module)\r, referer: http://localhost/ File "C:\\Env\\Lib\\site-packages\\django\\conf\\__init__.py", line 217, in __init__\r, referer: http://localhost/ mod = importlib.import_module(self.SETTINGS_MODULE)\r, referer: http://localhost/ File "C:\\Program Files\\Python310\\Lib\\importlib\\__init__.py", line 126, in import_module\r, referer: http://localhost/ return _bootstrap._gcd_import(name[level:], package, level)\r, referer: http://localhost/ File "<frozen importlib._bootstrap>", line 1050, in _gcd_import\r, referer: http://localhost/ File "<frozen importlib._bootstrap>", line 1027, in _find_and_load\r, referer: http://localhost/ File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked\r, referer: http://localhost/ File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed\r, referer: http://localhost/ File "<frozen importlib._bootstrap>", line 1050, in _gcd_import\r, … -
Can't get rid of modulenotfounderrror after moving project dirs around
when I run python manage.py runserver on myenv, I get the "modulenotfounderror" "no module named Quicpull" - which is my project Dir. I've tried multiple syntaxes in my installed apps, and I've updated the system env paths. -
Cannot create django superuser inside virtual environment
Firstly, if I missed finding a solution already posted, I apologize. I really did try figuring this out. So here is the command executed: "(VENV) user@server:/var/www/html/django-apps/GT1$ python manage.py createsuperuser The error returned is: Traceback (most recent call last): File "/var/www/html/django-apps/GT1/manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/var/www/html/django-apps/GT1/manage.py", line 22, in <module> main() File "/var/www/html/django-apps/GT1/manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? The virtual environment exists obviously because it's active when I'm trying. I've deleted the virtual and tried reinstalling. When I do that, I get a message that django is already installed. That message is: (VENV) darren@server:/var/www/html/django-apps$ sudo pip install django Requirement already satisfied: django in /usr/local/lib/python3.10/dist-packages (4.2.2) Requirement already satisfied: sqlparse>=0.3.1 in /usr/local/lib/python3.10/dist-packages (from django) (0.4.4) Requirement already satisfied: asgiref<4,>=3.6.0 in /usr/local/lib/python3.10/dist-packages (from django) (3.7.2) Requirement already satisfied: typing-extensions>=4 in /usr/local/lib/python3.10/dist-packages (from asgiref<4,>=3.6.0->django) (4.6.3) WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a … -
How can I optimize @property method by prefetching or caching an "unrelated" table
I have three model objects, two of which directly relate to each other. class Child(models.Model): date_of_birth = models.DateField() name = models.CharField(max_length=255) gender = models.CharField(max_length=10, choices=Gender.choices) @property def age(self): today = date.today() return age_on_date(date_calculating_on=today, date_of_birth=self.date_of_birth) class ChildBmiCheck(models.Model): home_bmi_check = models.ForeignKey(HomeBmiCheck, models.CASCADE, related_name="child_bmi_checks") child = models.ForeignKey(Child, models.PROTECT, related_name="bmi_checks") height_in_meters = models.DecimalField(max_digits=40, decimal_places=10, null=True) weight_in_kgs = models.DecimalField(max_digits=40, decimal_places=10, null=True) child_was_present = models.BooleanField(default=True) @property def zscore(self): if self.child_was_present is True: age = self.child.age * 12 # in months gender = self.child.gender # TODO this is slow because for every child bmi check we hit the DB # | # V matching_data = ReferenceZscoreData.objects.filter(sex=gender).get(age=age) return self.calculate_z_score(matching_data) else: return None And one that is used under the comment in the @property method above, which is not directly related through a foreign key relationship. class ReferenceZscoreData(models.Model): sex = models.CharField(max_length=1, choices=Sex.choices, db_index=True) age = models.IntegerField(db_index=True) property1ForZscore = models.FloatField() property2ForZscore = models.FloatField() property3ForZscore = models.FloatField() When I fetch Child BMI checks, I see that the DB is queried for the relavent ReferenceZscoreData every time this method is called. This makes the HTTP fetch in Django Rest Framework really slow. However, ReferenceZscoreData only changes once a year, so there is no reason to go to the database so often. I … -
Django Template: include another html template, but only once
How can I ensure that specific HTML files are not included multiple times in Django templates when passing metadata to different frontend frameworks? I am working on a project where we use Django templates and need to pass metadata from Django to various JavaScript frontend frameworks (currently React, but potentially refactor to others in the future). embed_data_foo.html {{ foo_data|json_script:"foo_data" }} some_page.html {% include "embed_data_foo.html" %} rendered <script id="foo_data" type="application/json">{"foo":"bar"}</script> Our templates are designed compositionally and relatively small, which makes it easy to avoid accidental duplication. However, I want to have guardrails in place to prevent these specific files from being included multiple times. So doing this multiple times potentially, in extended templates, should still only result in the only one being placed. some_page_but_with_whoopsies.html {% include "embed_data_foo.html" %} {% include "embed_data_foo.html" %} {% include "embed_data_foo.html" %} rendered <script id="foo_data" type="application/json">{"foo":"bar"}</script> <script id="foo_data" type="application/json">{"foo":"bar"}</script> <script id="foo_data" type="application/json">{"foo":"bar"}</script> In the C programming language, I would achieve this using the #ifndef, #define, #endif pattern. Is there a similar approach or technique that I can use in Django templates to ensure that files are included only if they have not been included before? Given that we will be onboarding many people in the near future, … -
How to apply custom validation on GenericTabularInline, TabularInline (related objects) in Django admin?
This is a question about GenericTabularInline, TabularInline, and admin.py. models.py class Chapters(models.Model): name = models.CharField(max_length=40, unique=True) class Projects(models.Model): name = models.CharField(max_length=40) class Courses(models.Model): name = models.CharField(max_length=30) is_active = models.BooleanField(default=False) chapters = SortedManyToManyField(Chapters, related_name="courses", blank=True, sort_value_field_name="chapter_number", base_class=CourseChapters) projects = models.ManyToManyField(Projects, related_name="courses", blank=True) # Here comes generic relations class QuestionsManager(models.Manager): def active(self): return self.get_queryset().filter(Q(fib__is_active=True) | Q(mcq__is_active=True) | Q(code__is_active=True)) class Questions(models.Model): chapter = models.ForeignKey(Chapters, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, limit_choices_to={ "model__in": ["fib", "mcq", "code"]}, on_delete=models.CASCADE ) object_id = models.PositiveIntegerField() fib_mcq_code = GenericForeignKey("content_type", "object_id") objects = QuestionsManager() class CODE(models.Model): name = models.CharField(max_length=36) chapter_question = GenericRelation("questions", related_query_name='code') is_active = models.BooleanField(default=False) class MCQ(models.Model): name = models.CharField(max_length=36) chapter_question = GenericRelation("questions", related_query_name='mcq') is_active = models.BooleanField(default=False) class FIB(models.Model): name = models.CharField(max_length=36) chapter_question = GenericRelation("questions", related_query_name='fib') is_active = models.BooleanField(default=False) admin.py class QuestionsChaptersInlineForm(forms.BaseInlineFormSet): def clean(self): pass class QuestionsChaptersInline(admin.TabularInline): model = Questions formset = QuestionsChaptersInlineForm extra = 0 readonly_fields = ['content_type', 'object_id', 'is_active', "modify"] def has_add_permission(self, request, obj): return False def has_delete_permission(self, request, obj): return False class ChapterAdminForm(forms.ModelForm): class Meta: model = Chapters fields = '__all__' def clean(self): cleaned_data = super().clean() if cleaned_data.get('is_active'): if not self.instance.questions_set.active().exists(): self.add_error('is_active', 'At least one question in this chapter must be active.') return cleaned_data class ChaptersAdmin(ImportExportModelAdmin, ImportExportActionModelAdmin, admin.ModelAdmin): form = ChapterAdminForm inlines = [QuestionsChaptersInline, CoursesChaptersInline] # =========================== class … -
Is there a way to filter multiple class objects in views.py and connect to eachother?
I have a Django project where I want to make 3 menus that can be accesed by clicking the select button in each main_menu(like mainfood) >> menu(pastas) >> items of pastas(bluh bluh) *main_menu is accesed from the homepage* I have created 3 classes in models.py called MainMenu, Menu, Item class MainMenu(models.Model): title = models.CharField(max_length=100) main_slug = models.SlugField(max_length=50,unique=True) created = models.DateTimeField("Date created", default=timezone.now) def __str__(self): return self.title class Menu(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=50,unique=True) created = models.DateTimeField("Date created", default=timezone.now) main_menus = models.ForeignKey(MainMenu,default="",verbose_name="Menus",on_delete=models.SET_DEFAULT, null=True) def __str__(self): return f"{self.title}||{self.main_menus}" class Meta: ordering = ['-created'] class Item(models.Model): title = models.CharField(max_length=100) price = models.CharField(max_length=12) description = models.TextField(blank=True) created = models.DateTimeField("Date created", default=timezone.now) menus = models.ForeignKey(Menu,default="",verbose_name="Menus",on_delete=models.SET_DEFAULT) def __str__(self): return f"{self.title}||{self.menus}" class Meta: ordering = ['-created'] and I have filtered objects in views.py def menus(request,main_slug): matching_menus = Menu.objects.filter(main_menus__main_slug=main_slug).all() return render( request=request, template_name='Menu.html', context={"objects": matching_menus} ) def items(request,slug): matching_items = Item.objects.filter(menus__slug=slug).all() return render( request=request, template_name='Item.html', context={"objects": matching_items} ) and the urls.py : urlpatterns = [ ... path('<slug:main_slug>', views.menus), path('<str:slug>', views.items), ] it kinda WORKS but only menu is filtered correctly. I can go from MainMenu to Menu and the Menus are filtered correctly, but I CANNOT access the items in the Menus. when I click a menu … -
How to programmatically test Django Auth0 protected api's?
I want to do unit tests for my Django app. I'm using the Django-oauth-toolkit library to protect my views, but I can't test my APIs because they are protected by a Bearer Token. def test_get_meeting_list(self): response = self.client.get('/meetings/') # (I need to pass a token, # but I won't have the token) self.assertEqual(response.status_code, 200) # (AssertionError: 401 != 200) So, how could I test that? I tried to make a fake authentication like the official lib tests https://github.com/jazzband/django-oauth-toolkit/blob/master/tests/test_application_views.py but I realized that's will be very complex. -
Django: How to show an admin user message if correction was made during model save?
I have an app, and am wanting to do some automatic corrections to geometry (GeoDjango with PostGIS) rather than simply reject the save operation, since the corrections are being done after the data is committed to the database through the "MakeValid" database operation. I would like to inform the admin user that the model was corrected and to verify their changed geometry, and this is where I am running into trouble. I am attempting the "MakeValid" through an additional query in the model's "save" method after the initial save has completed, but it appears that I can only get the message to show if I move that logic into the admin logic overriding "save_model" to call "obj.save()" and then do my post-processing. Is there a better way to pass information back to the admin view from the model save? -
Django REST Framework Custom Registration Serializer Not Being Called
I'm currently working on a Django project where I'm using Django REST Framework and dj-rest-auth for user authentication. I have a custom user model that includes an additional field for Date of Birth (DOB). I've created a custom registration serializer to handle the additional field during registration. However, I'm running into an issue: my custom serializer is not being called during the registration process, leading to HTTP 400 errors from the frontend. Goal: I want to allow users to register by providing an email, password, and DOB. Problem: When I attempt to register a user from the frontend, I receive a HTTP 400 error. I'm also noticing that print statements in my custom registration serializer aren't showing up in the console logs, which leads me to believe it's not being called at all. What I've tried: I have tried to override the registration process in dj-rest-auth by providing a custom serializer, and configuring REST_AUTH_REGISTER_SERIALIZERS in my settings. I've also checked my URL routing and it seems to be correct. Here are the key sections of my code: models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import gettext as _ class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): … -
Django tests: model name cannot be resolved, although site works
I have a website written in Django. Apart from main app, I have one called app and other users. In users I have implemented my CustomUser model, which I am also using inside models for app. When I run the website, it all works fine; however when I tried to create tests for the app I get: ValueError: Related model 'users.customuser' cannot be resolved (even though tests.py are empty now). And obviously, in app/tests.py I do from .models import CustomUser. I tried looking at the order of imports in settings.py but it seemed right to me: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'app', ] I have also done migrations for both apps.