Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sending parts of react components from django server to be rendered in a react client server
I have a unique problem statement. I have a client side react server running on port 3000 and a django server of port 8000. Both the servers communicate through rest framework. But I have a situation where I cannot keep the UI code of react in the react frontend so I should send the react(html) code from the django backend(security reasons) so that I could only load that secure UI react component when I receive the html(react compiled) code from the django server(backend). I think we can use some way to compile the react code from an additional node.js server into html code and keep it in django server. When user with right permissions try to access that component only then the server send the react UI code to the frontend to temporarily display that component in the frontend. Can I know how this can be achieved if it cam be achieved. Feel free to ask any additional questions you have regarding the problem statement in the comments. -
How to create model instances from html form and save to AuraDb?
Most of the online tutorials and videos describe how to create and save model instances to the local database using Django. I found this medium article https://medium.com/swlh/create-rest-api-with-django-and-neo4j-database-using-django-nemodel-1290da717df9 explaining how to upload it to Neo4j. I tried to run the same project and this is what I got when I went to http://127.0.0.1:8000/person (see snapshot below). The "Person" object is a StructuredNode, defined as follows in models/person.py: from neomodel import StructuredNode, StringProperty, IntegerProperty,UniqueIdProperty, RelationshipTo from myapi.models.city import City class Person(StructuredNode): uid = UniqueIdProperty() name = StringProperty(unique_index=False) age = IntegerProperty(index=True, default=0) email = StringProperty(unique_index=True) # Relations : city = RelationshipTo(City, 'LIVES_IN') friends = RelationshipTo('Person','FRIEND') def __unicode__(self): return self.uid I want to get the details from a user through a form and save it as an instance of the Person object in my AuraDB: person.save() So in `views/forms.py' I created a form as such: from django import forms from splitjson.widgets import SplitJSONWidget from myapi.models import Person class testForm(forms.Form): attrs = {'class': 'special', 'size': '40'} data = forms.CharField(widget=SplitJSONWidget(attrs=attrs, debug=True)) class Meta: model = Person and I added it as a path to the urls.py: from django.urls import re_path as url from myapi.views import * from django.urls import path urlpatterns = [ path('', home, name='home'), … -
JS script is not included in Django project
I'm learning django and have a problem. JS script is not included in Django project. The path is correct, the page itself with the graph block works, but the output of a round or bar chart does not occur. index.html {% extends 'partials/base.html' %} {% block title %}Home Page{% endblock %} {% block content %} <div class="row "> <div class="col-md-6 my-4"> <div class="bg-white"> <div class="card-body"> <canvas id="myChart1" width="400" height="300"></canvas> <script src="{% static 'main.js' %}"></script> </div> </div> </div> <div class="col-md-6 my-4"> <div class="bg-white"> <div class="card-body"> <canvas id="myChart" width="400" height="300"></canvas> <script> var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: [{% for order in order %} '{{order.name}}',{% endfor %}], datasets: [{ label: 'Orders', data: [{% for order in order %} {{ order.order_quantity }}, {% endfor %}], backgroundColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] … -
Django doesn't override base admin template
I'm trying to add small customizations to my Django admin panel such as a favicon. I followed the official guide and have created a base_site.htmlfile in app/templates/admin/. base_site.html {% extends "admin/base_site.html" %} {% load static %} {% block branding %} <img src="{% static 'portal/img/favicon.png' %}" alt="Favicon"> {{ block.super }} {% endblock %} It seems like the template isn't being overridden at all as I don't see an error for not being able to find the favicon / incorrect src (works fine on other pages). urls.py from django.contrib import admin from django.urls import path, include from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib.sitemaps.views import sitemap from bmlabs.sitemaps import StaticViewSitemap from .views import robots sitemaps = { 'static': StaticViewSitemap, } urlpatterns = [ path('admin/', admin.site.urls, name="admin"), ] urlpatterns += staticfiles_urlpatterns() -
Can i run 2 django projects on 2 domains but on 1 ip?
I'm trying to run two django projects using nginx using these two configurations: upstream django { server unix:///home/hypebeeruser/HypeBeer/HypeBeerProject/HypeBeerProject.sock; } # configuration of the server server { server_name hypebeer.com.ua; charset utf-8; # max upload size client_max_body_size 75M; # Django media and static files location /media { alias /home/hypebeeruser/HypeBeer/HypeBeerProject/media; } location /static { alias /home/hypebeeruser/HypeBeer/HypeBeerProject/static; } # Send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/hypebeeruser/HypeBeer/HypeBeerProject/uwsgi_params; } } # the upstream component nginx needs to connect to upstream django_tobabox { server unix:///home/tobabox/TobaBox/TobaBox/TobaBox.sock; } # configuration of the server server { listen 80; server_name tobabox.com www.tobabox.com; charset utf-8; # max upload size client_max_body_size 75M; # Django media and static files location /media { alias /home/tobabox/TobaBox/TobaBox/media; } location /static { alias /home/tobabox/TobaBox/TobaBox/static; } # Send all non-media requests to the Django server. location / { uwsgi_pass django_tobabox; include /home/tobabox/TobaBox/TobaBox/uwsgi_params; } } I run uwsgi --socket HypeBeerProject.sock --module HypeBeerProject.wsgi --chmod-socket=666 and it runs my first site, but the second doesn't work with the same comand (yes, i changed the names of .sock and project.wsgi). It runs normally without any errors, but i still can't connect via domain name. Do I need to buy an additional IP or can I … -
Filter in Django Admin via a ManyToMany field with Through
My models.py: class Subject(models.Model): name = models.CharField(max_length=200) class Person(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE, blank=True, null=True) class PersonRole(models.Model): project = models.ForeignKey('Project', on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) class Project(models.Model): title = models.CharField(max_length=200) person = models.ManyToManyField(Person, through=PersonRole) Now, in my admin back-end I'd like to add a nice filtering with list_filter. This filter should make it possible to filter by the schools that a person is attached to a project. In other words, if John (belonging to school 'no. 1') is attached to project no. 3, I'd like the projects table on the backend to show only project no. 3. I suppose I should customise a simplelistfilter. First of all, though, I'm a bit stuck as to how to get the list of schools attached to the persons attached to a project. My attempt so far is: class PersonRole(models.Model): [...] def get_school(self): return self.person.school class Project(models.Model): @admin.display(description='PI School') def get_PI_school(self): return [p for p in self.person.get_school()] admin.py: class ProjectAdmin(admin.ModelAdmin): list_display = ("get_PI_school",) #This is just to see if the field is populated With this, I get 'ManyRelatedManager' object has no attribute 'get_school'. -
create django models using HTML form
i am working with django and trying to build a web app builder with pure django and grapesjs and django-tenant. i am wondering how to let the customer create his own database models separate from other customers and link these fields with django model in grapesjs. Models.py """" """" -
How to create pdf with multiple pages based on html using python pdfkit
I am trying to create a pdf with python using pdfkit library in my Django project, and I want to separate each content in a different page, how can I do it import pdfkit from django.template.loader import render_to_string my_contents = [ {'title':'Example 1', 'contents': ['Lorem ipsum dorer', 'Lorem ipsum']}, {'title':'Example 2', 'contents': ['Lorem ipsum dorer', 'Lorem ipsum']}, {'title':'Example 3', 'contents': ['Lorem ipsum dorer', 'Lorem ipsum']}, {'title':'Example 4', 'contents': ['Lorem ipsum dorer', 'Lorem ipsum']}, {'title':'Example 5', 'contents': ['Lorem ipsum dorer', 'Lorem ipsum']} ] final_html = '' for content in my_contents: data = { 'title': content['title'], 'contents': content['contents'], } final_html += render_to_string( 'pdfs/routines_handout.html', data) my_pdf = pdfkit.from_string(final_html, 'out.pdf') -
login with superuser not working in django admin panel
I was writing code, everything worked fine, all services were running via docker-compose, then the database crashed, I had to clean up the database files and recreate them using the same docker-compose. This time, I tried to create an admin user using python manage.py createsuperuser, I created it, but I can't authenticate with it in django/admin. Settings: from pathlib import Path import environ import os env = environ.Env(DEBUG=(bool, False)) # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' environ.Env.read_env(os.path.join(BASE_DIR, '.env')) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env('DEBUG') ALLOWED_HOSTS = [] INTERNAL_IPS = [ "127.0.0.1", ] AUTH_USER_MODEL = 'codenest.User' TAILWIND_APP_NAME = 'theme' # AUTHENTICATION_BACKENDS = [ # 'django.contrib.auth.backends.RemoteUserBackend', # 'django.contrib.auth.backends.ModelBackend', # ] SITE_ID = 1 INSTALLED_APPS = [ 'codenest.apps.CodenestConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tailwind', 'theme', 'django_browser_reload', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_browser_reload.middleware.BrowserReloadMiddleware', ] ROOT_URLCONF = 'learning_system.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { … -
Django Pytests in docker container not using temp sqlite3 database
I'm running pytest on a django app that lives in a docker container. Pytest is being run in the docker container after it's built. Normally the django app references a mysql container running on the same host. I've been trying to use a sqlite3 db instead for testing, but I've been having trouble getting it to use this instead of the mysql container. I've gotten it to work one way: test_settings.py: from .settings import * # Override the DATABASES setting to use SQLite for tests DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } pyproject.toml: [tool.pytest.ini_options] testpaths = ["tests"] addopts = [ "--ds=django_app.test_settings", ] [tool.pytest.ini_options.env] PYTHONPATH = "web" I don't want to do it this way because of the wildcard import (also my ruff linter doesn't like). I've tried to overwrite using conftest.py, but it seems to get overwritten again by the DJANGO_SETTINGS_MODULE env variable, which is set in the container's env file. How can I get my pytest to use sqlite3 without using this wildcard import on test_settings.py? Or without using test_settings.py at all? Thanks -
What are the best practices regarding SSR, Django and temprarly changed data?
I'm currently building a Django app using htmx. It's something like a journal with multiple entries per day. When a user changes one entry or adds another I don't want to store the data just yet in case the user cancels the input. This is no problem for a single change but when there are multiple changes it gets overly complicated because the current state is only correctly represented on the website and not in the DB object anymore. What would be the best practice to handle this problem? I'm using function based views, not classes. I'm thinking about adding a temporary object table where a copy of my journal week/days is added and changed and gets deleted after the user saves the real object. Is there a better way to do it? -
How to use SQL Alchemy models the same way than django models
I have been using fast api for a few days and passing the db session around is starting to bother me a bit. In my previous project I was using a django backend, where to make queries I only needed to import the model. Something like: from models import SomeModel class SomeRepository: def method(self): SomeModel.objects.filter(...) But in fast api, I need to take care of the db session object and pass it as argument, something like: from sqlalchemy.orm import Session from models import SomeModel class SomeRepository: def method(self, db: Session): db.query(SomeModel).all() Is there any way to make fast api and sql alchemy work like the way models work in Django? -
Authorization error with Django on Windows with IIS
Dear Django and Windows IIS experts, I am a medical physicist, trying to help a colleague set up a new installation of OpenREM version 1.0.0b2, an open source patient radiation dose management system (openrem.org). We have been following the documentation here: https://docs.openrem.org/en/1.0.0b2/install_windows.html. The system is running on Windows Server 2016 Datacenter. The OpenREM installation works perfectly when run using Django's built-in "python.exe manage.py runserver" command. However, it needs to be configured to run via Microsoft's IIS, and we cannot get this to work. There is an "Authorization" problem reported when I run "Test Settings" from the "Basic Settings" dialogue box in IIS: We have tried giving the OpenREM application pool read access to the site, but this did not work. Can any of you offer some help or advice with this? I have a fully-working Windows server installation of OpenREM 1.0.0b2 at my workplace, so have some experience of installing and configuring the system, but IIS on my colleague's server has me stumped. Many thanks in advance for any help you can offer. Kind regards, David -
Django socialaccount login with email instead of username
I am trying to implement google login in my Django app. In my standart class-based login view I am using the extended AbstractBaseUser model and it works fine: class AppUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' objects = CustomUserManager() def get_by_natural_key(self, email): return self.get(email=email) def set_password(self, raw_password): self.password = make_password(raw_password) In my settings.py I've added these: INSTALLED_APPS = [ ... 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ... ] SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email' ], 'AUTH_PARAMS': { 'access_type': 'online', } } } ... AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_PASSWORD_MIN_LENGTH = 8 SITE_ID = 1 LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' AUTH_USER_MODEL = "profiles.AppUser" This is the error message i received: FieldDoesNotExist at /accounts/google/login/callback/ AppUser has no field named 'username' ...Python\Python39\lib\site-packages\django\db\models\options.py, line 681, in get_field return self.fields_map[field_name] … Local vars During handling of the above exception ('username'), another exception occurred: ...Python\Python39\lib\site-packages\django\core\handlers\exception.py, line 55, in inner response = get_response(request) … Local vars ...Python\Python39\lib\site-packages\django\core\handlers\base.py, line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … Local vars ...Python\Python39\lib\site-packages\allauth\socialaccount\providers\oauth2\views.py, line 87, in view return self.dispatch(request, *args, **kwargs) … Local vars ...Python\Python39\lib\site-packages\allauth\socialaccount\providers\oauth2\views.py, line 171, … -
Display a filtered result from ManyToMany through model in Admin
This is my models.py: class Person(models.Model): surname = models.CharField(max_length=100, blank=True, null=True) forename = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return '{}, {}'.format(self.surname, self.forename) class PersonRole(models.Model): ROLE_CHOICES = [ ("Principal investigator", "Principal investigator"), [etc...] ] title = models.CharField(choices=TITLE_CHOICES, max_length=9) project = models.ForeignKey('Project', on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) person_role = models.CharField(choices=ROLE_CHOICES, max_length=30) def __str__(self): return '{}: {} as {}.'.format(self.project, self.person, self.person_role) class Project(models.Model): title = models.CharField(max_length=200) person = models.ManyToManyField(Person, through=PersonRole) def __str__(self): return self.title def get_PI(self, obj): return [p.person for p in self.person.all()] #I'll then need to filter where person_role is 'Principal investigator', which should be the easy bit. In my Admin back-end I'd like to display the person (principal investigator) in the main table: class ProjectAdmin(ImportExportModelAdmin): list_filter = [PersonFilter, FunderFilter] list_display = ("title", "get_PI") ordering = ('title',) You can see that I created my get_PI() in my models.py and references in my list_display. I'm getting Project.get_PI() missing 1 required positional argument: 'obj'. What am I doing wrong? -
migrate from django migrations to fastapi alembic
I had a Django service which had an app called "User". This app has 2 tables in, which are being migrated to the database using Django migration system. In order to change the architecture from monolith to micro-service, I broke down User app and add the models and APIs in another Fastapi project. But I didn't separate the database and during this time, I was changing User tables in database using my previous Django project migration system. But now I want to break down tables in the database and move them to the new database. What is the best practices of doing this? And how can I change migrations from Django to alembic? -
getting "Failed to create meeting error 401 Client Error: Unauthorized for url: https://api.zoom.us/v2/users/me/meetings"
I have added the client id and secrete key and if i am autharizing the app from postman its working but as soon as i tried to ping the api with my app it giving 401 error. how can i authorize my app into zoom app and can create meeting with dynamic token authrization_url = 'https://zoom.us/oauth/authorize' authrization_params = { 'client_id': zoom_client_key, 'response_type': 'code', 'redirect_uri': 'https://gensproject.supporthives.com/zoom', } auth_response = requests.post(authrization_url, data=authrization_params) if auth_response: # Obtain a new access token access_token_url = 'https://zoom.us/oauth/token' access_token_params = { 'grant_type': 'client_credentials', 'client_id': zoom_client_key, 'client_secret': zoom_client_secret, } try: response = requests.post(access_token_url, data=access_token_params) response.raise_for_status() access_token = response.json().get('access_token', '') except requests.RequestException as e: return Response({'message': 'Failed to obtain access token', 'error': str(e)}, status=500) # Create a Zoom meeting # user_id = "ops@supporthives.com" # create_meeting_url = f"https://api.zoom.us/v2/users/{user_id}/meetings" "https://zoom.us/oauth/authorize?client_id=MeGkVnUrQGG15c7ESPP1ZA&response_type=code&redirect_uri=https%3A%2F%2Fgensproject.supporthives.com%2Fzoom" create_meeting_url = 'https://api.zoom.us/v2/users/me/meetings' create_meeting_headers = { 'Authorization': f'Bearer {access_token}', # 'Authorization': f'Bearer eyJzdiI6IjAwMDAwMSIsImFsZyI6IkhTNTEyIiwidiI6IjIuMCIsImtpZCI6IjQ0NTYzNTg5LTA0YzAtNDY1ZC05NjBhLTljM2Y4YmI1ZjRmMyJ9.eyJ2ZXIiOjksImF1aWQiOiJiOTg4ZGQ4ZGNiYmQ0NTcyMjM0OWU4ZWE1ZGQ5NTVkMCIsImNvZGUiOiJ6V0tvUWhBREtuQWRHdVVuRkt5Uk15WXF2TjBYaXpDa0EiLCJpc3MiOiJ6bTpjaWQ6TWVHa1ZuVXJRR0cxNWM3RVNQUDFaQSIsImdubyI6MCwidHlwZSI6MCwidGlkIjowLCJhdWQiOiJodHRwczovL29hdXRoLnpvb20udXMiLCJ1aWQiOiI3RkRIdW16TFNMZW5xUVk0cDRFNDRnIiwibmJmIjoxNzExNDUyMTk0LCJleHAiOjE3MTE0NTU3OTQsImlhdCI6MTcxMTQ1MjE5NCwiYWlkIjoiMVpmNnBDYkRROHF2emU1RFB0VnQ0USJ9.2oTMkSwL0OrnOAswTJoscy8zOSJhVmplTHsE6gh3H5-z_7sznAanBF2XyL3wO9FLGpggsFSqWxB04MXQof7YDw', 'Content-Type': 'application/json', } event_datetime = datetime.combine(event.event_date, datetime.min.time()) start_time_utc = mktime(event_datetime.utctimetuple()) create_meeting_params = { 'topic': event.event_title, 'type': 2, # Scheduled meeting 'start_time': f'{start_time_utc}000', 'duration': 60, 'timezone': 'UTC', 'description': event.event_description, 'settings': { 'host_video': True, 'participant_video': True, 'waiting_room': False, 'join_before_host': True, 'mute_upon_entry': False, 'auto_recording': 'none', }, } try: create_meeting_response = requests.post(create_meeting_url, headers=create_meeting_headers, json=create_meeting_params) create_meeting_response.raise_for_status() meeting_link = create_meeting_response.json().get('join_url', '') event.event_link = meeting_link … -
My image show not found error but the link in terminal is able to locate the file
My image can't be load on page, the feedback shows Not Found: /auctions/static/auctions/images/Artboard_1_copy.png "GET /auctions/static/auctions/images/Artboard_1_copy.png HTTP/1.1" 404 3417 but when I ctrl and click on the link in feedback, I was able to open my image in my workspace. This is my settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '6ps8j!crjgrxt34cqbqn7x&b3y%(fny8k8nh21+qa)%ws3fh!q' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'auctions', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'commerce.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'commerce.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_USER_MODEL = 'auctions.User' # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # … -
Python: how to handle uploading and zipping large files into Minio
I have a Django GraphQL API. I'm trying to implement an endpoint that would download files from external urls, upload them to Minio bucket, create a Zip-file from the files and return the Zip-file to the user for download. All this is done in the backend. It works with relative small files but the problem is that some of the files I need to handle are pretty large, e.g. ~4GB and uploading files this big seems to fail pretty often and adding them to Zip-file usually freezes the whole server. This is how I download and upload the files: def download_and_upload_file(url: str, prefix: str, file_name: str) -> str: with requests.get(url, stream=True) as response: response.raise_for_status() with io.BytesIO() as file_buffer: for chunk in response.iter_content(chunk_size=8192): if chunk: file_buffer.write(chunk) file_buffer.seek(0) upload_url = upload_object_to_minio(file_buffer, prefix, file_name) return upload_url def upload_object_to_minio(stream: io.BytesIO, prefix: str, object_name: str): try: _ = MINIO_CLIENT.put_object( bucket_name=xxx, object_name=f"/{prefix}/{object_name}", data=stream, length=stream.getbuffer().nbytes, ) except Exception as e: print(e) return "minio-object-url" And this is how I zip the file: def create_zip_file(prefix: str, uploaded_urls: list[str]) -> str: try: zip_buffer = io.BytesIO() with zipfile.ZipFile(zip_buffer, "w") as zip_file: for uploaded_url in uploaded_urls: file_name = uploaded_url.split("/")[-1] # Retrieve the Minio object and its name minio_object, object_name = get_object_from_minio(uploaded_url) # … -
While using django-template the code is not automatically generated and even while pressing the enter key the code is not coming in the new line
{% extends "base.html" %} {% block title %}Home{% endblock title %} this is the sample code {% extends "base.html" %} {% block title %}About{% endblock title %} i want each line in the new next line even code suggestion is not shown -
Forbidden (CSRF cookie not set.): for django login from javascript
I am trying to access django server login from javascript axios.get('http://localhost:8010/get_csrf_token/').then((res)=>{ console.log(res.data['csrf_token']); var data = {username:'admin@test.com',password:'testtest', } axios.defaults.headers.common['X-CSRF-TOKEN'] = res.data['csrf_token'];// set csrf_token in header. axios.post('http://localhost:8010/login/',data).then(() =>{ console.log("test"); }) }) However this code shows the error below. I set the X-CSRF-TOKEN header but it requires cookie? This django server is not third-party but under my controle, so I can change the setting of djang server. How can I solve this? Forbidden (CSRF cookie not set.): /login/ [WARNING][240326 200329] Forbidden (CSRF cookie not set.): /login/ [26/Mar/2024 20:03:29] "POST /login/ HTTP/1.1" 403 2882 -
Celery worker shut down
My worker in celery automatically gets shut down and logs this message worker: Warm shutdown (MainProcess), and doesn't do anything, I'm running a long running AI/ML tasks in celery my celery config is something like this: **app.conf.update( result_expires=None, # Disable result expiration worker_max_tasks_per_child=500, # Disable limiting the number of tasks each worker can execute before it's replaced worker_prefetch_multiplier=0, # Disable prefetching tasks worker_concurrency=1, # Use all available CPU cores for concurrency worker_disable_rate_limits=True, # Disable rate limits for tasks task_track_started=True, # Track started tasks task_soft_time_limit=None, # Disable soft time limit for tasks task_time_limit=None, # Disable hard time limit for tasks worker_max_memory_per_child=None, # Disable memory limit for worker processes task_acks_late=True, broker_connection_retry_on_startup=True, # Enable broker connection retries on startup )** sometimes it shuts down and sometimes it does'nt can anyone say something -
Django admin page doesn't open, when I use Kong gateway
I use Kong gateway to make Django project accessible at localhost/python. I can see Django start page, but when I try to open localhost/python/admin it redirects to localhost/admin/login/?next=/admin/, so that isn't Django project anymore. What can I do to fix that? Thanks This is how Kong service and route looks like: { "enabled": true, "tls_verify": null, "tls_verify_depth": null, "port": 3000, "protocol": "http", "path": null, "client_certificate": null, "write_timeout": 60000, "connect_timeout": 60000, "retries": 5, "read_timeout": 60000, "id": "8da72803-ffea-4424-a568-31faa3782a6d", "name": "python-service", "host": "python-service", "updated_at": 1711390446, "created_at": 1711390446, "tags": null, "ca_certificates": null } route: { "next": null, "data": [ { "strip_path": true, "regex_priority": 0, "methods": null, "request_buffering": true, "response_buffering": true, "protocols": [ "http", "https" ], "service": { "id": "8da72803-ffea-4424-a568-31faa3782a6d" }, "https_redirect_status_code": 426, "tags": null, "paths": [ "/python" ], "headers": null, "id": "2c1fb24a-21dd-42f5-9784-a3bf95c6f7dc", "path_handling": "v0", "created_at": 1711390464, "updated_at": 1711390464, "name": null, "snis": null, "sources": null, "hosts": null, "preserve_host": false, "destinations": null } ] } -
Django signals debounce
In a project using Django's signal, when a series of UPDATEs of a particular model are executed, the processing of one SIGNAL is too heavy and causes discomfort to the user. The process fired by SIGNAL does not need to be executed for each update when multiple UPDATEs are executed. For example, if UPDATE of model A is executed 20 times in one minute, there is no need to fire signal 20 times. In light of the above, I think it would be better to implement something like debounce, where signal is fired only once even if multiple UPDATEs are executed in one minute. (We have already taken steps to reduce the number of signal firing conditions.) Is it possible to run a debounce-like process in Django? Or is there a library that can accomplish this? Thanks in advance. signal.py @receiver(post_save, sender=ModelA) def heavy_function1( sender: ModelA, instance: ModelA, *args, **kwargs ) -> None: result = calculate1(instance.attribute) update_modelB(result) @receiver(post_save, sender=ModelA) def heavy_function2( sender: ModelA, instance: ModelA, *args, **kwargs ) -> None: result = calculate2(instance.attribute) update_modelB(result) @receiver(post_save, sender=ModelA) def heavy_function3( sender: ModelA, instance: ModelA, *args, **kwargs ) -> None: result = calculate3(instance.attribute) update_modelB(result) We already use django-model-util's FilldTracker to perform heavy processing … -
how connect to models.py? Some Django views.py are not working
i am new with django/python. i have project in Django for calculate paper price. class Calculate(View): def get(self, request): if not request.user.is_authenticated: return redirect('signIn') user = request.user projects = Project.objects.all() p_info_list = [] u_info = UserInfo(user) user_in_projects = [] k_info_list = [] for p in projects: tasks = p.task_set.all() print(f"Project: {p.name}, Tasks: {tasks}") print(f"p object: {p}") for task in tasks: print(f"Task object: {task_object}") # Check the value before object creation if p.owner == user or user.id in p.get_members(): p_info = ProjectInfo(p) u_info.analyze_project(p) p_info_list.append(p_info) user_in_projects.append(UserInProject(user, p)) print(f"P Info object: {p_info}") for task in p.task_set.all(): print(f"Task object: {task}") # Print the entire task object print(f"Task: {task.name}, tipe_kertas: {task.tipe_kertas}") k_info_obj = KalkulatorInfo(task) # Or pass relevant data containing paper properties print(f"KalkulatorInfo object: {k_info_obj}") price = k_info_obj.calculate_price(task.tipe_kertas, task.gramatur_kertas, task.ukuran_kertas) k_info_obj.price = price # Assuming KalkulatorInfo has a price attribute k_info_list.append(k_info_obj) why task_object not working when i debugging from print() the entire for task in p.task_set.all() are not working. here is the models.py: class KalkulatorInfo: def __init__(self, task_object): self.tipe_kertas = task_object.tipe_kertas # Assuming task object has these attributes self.gramatur_kertas = task_object.gramatur_kertas self.ukuran_kertas = task_object.ukuran_kertas self.price = self.calculate_price() # Calculate price upon initialization def calculate_price(self): price_dict = { ("ap", "80", "a4"): 10000, ("bp", "100", "a4"): 12000, …