Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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, … -
Request in test APIClient fails after authenticating twice
After upgrading to django 5, our test suite started showing odd behavior. We are using DRF's APIClient and authentication does not work as expected anymore. Certain API requests return rest_framework.exceptions.NotAuthenticated with status code 403 (by the way, if someone could explain why this status is 403 and not 401, I'd appreciate). This is seemingly arbitrary. Among 2 requests to views which are implemented identically in terms of user permissions etc, one returns 403 during testing only. Executing the same calls in Postman does not reproduce the error. Thus, some of the exact same test cases which used to pass under django 4 do not pass anymore under django 5 due to above error. I did not manage to reproduce these cases in a minimal example. What I did reproduce however, is the following: client.force_authenticate(user) client.get(url) # the user does not have permissions. response is 403, as expected client.force_authenticate(None) # "log out" user.user_permissions.add(permission) client.force_authenticate(user) response = client.get(url) # the now has permissions. response 200 is expected assert response.status_code == 200 # response status is 403 Package versions are django==5.0.3 djangorestframework==3.15.0 pytest==7.4.3 pytest-django==4.7.0 I have made a minimal project where this can be observed. As far as I managed to test it, … -
Uncaught TypeError: $.ajax is not a function in jQuery
I'm encountering an issue with jQuery's $.ajax function in my web application. When I try to make an AJAX request using $.ajax, I'm getting the error "Uncaught TypeError: $.ajax is not a function" in the browser console. Here's the relevant code snippet: $.ajax({ url: "/add-to-wishlist", data: {"id": product_id}, dataType: "json", beforeSend: function(){ console.log("Adding to wishlist"); }, success: function(response){ this_val.html("👍🏼"); if (response.bool === true) { console.log("Added to wishlist"); } }, error: function(xhr, errmsg, err){ console.log(xhr.status + ": " + xhr.responseText); console.log(errmsg); } }); I've ensured that jQuery is properly included in my HTML file before including my JavaScript file. However, I'm still encountering this error. Could anyone help me understand why I'm getting this error and how to resolve it? Any insights or suggestions would be greatly appreciated. Thank you! I'm facing a problem with adding products to the wishlist feature in my Django web application. Here's the relevant: View (add_to_wishlist): def add_to_wishlist(request): product_id = request.GET['id'] product = Product.objects.get(id=product_id) context = {} wishlist_count = wishlist.objects.filter(product=product, user=request.user).count() print(wishlist_count) if wishlist_count > 0: context = { "bool": True } else: new_wishlist = wishlist.objects.create( product=product, user=request.user ) context = { "bool": True } return JsonResponse(context) HTML Button: <button class="btn-action" data-product-item="{{ p.id }}"> <ion-icon name="heart-outline"></ion-icon> … -
How to optimize and implement infinite comments through prefetch with django orm?
I'm implementing the comment function and I can leave a big message in the comments. It was easy to implement the function, but it's causing n+1 queries. Please tell me how to solve this problem python Prefetch( 'comments', queryset=PlaceReviewComment.objects.select_related( 'user', ).prefetch_related( Prefetch( '_comments', queryset=PlaceReviewComment.objects.select_related( 'user', 'parent_comment', ).prefetch_related( '_comments', '_comments__user', ).filter( removed_at__isnull=True ), to_attr='child_comments' ), ).filter(parent_comment=None, removed_at__isnull=True), to_attr='_comments' ), ).filter( id=review_id, If I do this, I'll only get one depth's comment Should I implement a function that does prefetch as much as depth? But I also think to check that there is a _comment and add prefetch, but I don't know how -
No data posted to Django rest api when button is pressed
I have a form with text inputs, and I have created a button as well which when pressed, should post the input field data into a Django Api. But when I press the button, nothing happens and there seems to be no error as well. This is sample from my code: class MyForm extends StatefulWidget { @override _MyFormState createState() => _MyFormState(); } class _MyFormState extends State<MyForm> { final String url = 'http://127.0.0.1:8000/api/?format=json'; final TextEditingController nameController = TextEditingController(); final TextEditingController phoneController = TextEditingController(); final TextEditingController purposeController = TextEditingController(); final TextEditingController addressController = TextEditingController(); final TextEditingController visiteeController = TextEditingController(); final TextEditingController dateController = TextEditingController(); String result = ''; Future<void> _postDataToDjango() async { try { final response = await http.post(Uri.parse(url), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, dynamic> { 'visitor_name': nameController.text, 'visit_date': dateController.text, 'Time_in': (TimeInputField()._selectedTime).toString(), 'Time_out': Null, 'Department': (DropdownMenuExample().dropdownValue).toString(), 'Visitee_name': visiteeController.text, 'Address': addressController.text, 'Phone': phoneController.text, 'Purpose_of_visit': purposeController.text }), ); if (response.statusCode == 201) { final responseData = jsonDecode(response.body); print('Post successful'); setState(() { result = 'id: ${responseData['id']}\nvisitor_name: ${responseData['visitor_name']}\nvisit_date: ${responseData['visit_date']}\nTime_in: ${responseData['Time_in']}\nTime_out: ${responseData['Time_out']}\nDepartment: ${responseData['Department']}\Visitee_name: ${responseData['Visitee_name']}\nAddress: ${responseData['Address']}\nPhone: ${responseData['Phone']}\nPurpose_of_visit: ${responseData['Purpose_of_visit']}'; }); } else { throw Exception('Failed to submit'); } } catch (e) { setState(() { result = 'Error: $e'; }); } } And below is the … -
ImportError for django-simple-history in VS Code: "Import 'simple_history.models' could not be resolvedPylance"
I'm currently working on a Django project and want to use django-simple-history to track changes on my models. However, I'm facing an issue with importing the HistoricalRecord model from simple_history.models. Whenever I try to import it in my code, Visual Studio Code underlines the import statement and shows the error message "Import 'simple_history.models' could not be resolvedPylance". Here are the steps I've taken to troubleshoot the issue: I activated my virtual environment where django-simple-history is installed and then using pip freeze, I confirmed that django-simple-history==3.5.0 is listed. I also used pip show django-simple-history to ensure the package details are correct, and it shows the expected information. I deleted the virtual environment and recreated it, but the problem persists. I checked the location where the virtual environment saves the library-specific data (venv\Lib\site-packages\simple_history), and I can see the HistoricalRecords model there. Despite these efforts, I'm still unable to resolve the import error in VS Code. Could anyone suggest what might be causing this issue and how I can fix it? Any help or guidance would be greatly appreciated. Here is the error: (https://i.stack.imgur.com/mzpZQ.png) Thank you! -
Unable to Resolve jQuery ReferenceError: $ is not defined in JavaScript File
I'm encountering an issue with my JavaScript file where I'm getting the error "Uncaught ReferenceError: $ is not defined" in the browser console. I'm using jQuery in my JavaScript code, but it seems like jQuery is not being recognized. Here's the relevant portion of my JavaScript file (address.js): console.log("Hi"); $(document).ready(function(){ $(document).on("click",".make-default-address",function(){ let id = $(this).attr("data-address-id") let this_val = $(this) console.log("Id is:", id); console.log("Element is:", this_val); $.ajax({ url:"/make-default-address", data: { "id":id }, dataType: "json", success: function(response){ console.log("Address Made default....."); if (response.boolean == True){ $(".check").hide() $(".action_btn").show() $(".check"+id).show() $(".button"+id).hide() } } }) }) }) I've ensured that jQuery is loaded before this script in my HTML file: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="{% static 'assets/js/address.js' %}"></script> However, I'm still getting the error. Can someone please help me understand what might be causing this issue and how I can resolve it? Any assistance would be greatly appreciated. Thank you!