Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
io.UnsupportedOperation: fileno
in django i want to receive a file from a form and then pass it to a function, then do some OCR with it. but i get the io.UnsupportedOperation: fileno error. here is part of views.py: @login_required(login_url='/profile/login/') def repairman_profile(request): user = request.user repairman = RepairmanUser.objects.get(user=user) if request.method == 'POST': plate_form = PlateForm(request.POST, request.FILES) if plate_form.is_valid(): plate = recognize_plate(request.FILES["plate_image"]) return HttpResponse(plate) else: plate_form = PlateForm() context = { "repairman": repairman, 'plate_form': plate_form, } return render(request, 'repairman/profile.html', context=context) here is the recognize_plate() function: def recognize_plate(plate): results = {} # load models model = Model.load("hezarai/crnn-fa-64x256-license-plate-recognition") license_plate_detector = YOLO('repairman/plate_recognition/best.pt') # load image # cap = cv2.imread(plate) frame = cv2.imread(plate) the line frame = cv2.imread(plate) is where the error happens. here is django log: Internal Server Error: /profile/ Traceback (most recent call last): File "D:\Tamirauto\WebApp\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "D:\Tamirauto\WebApp\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Tamirauto\WebApp\venv\Lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapper_view return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Tamirauto\WebApp\tamirauto\repairman\views.py", line 94, in repairman_profile plate = recognize_plate(request.FILES["plate_image"]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Tamirauto\WebApp\tamirauto\repairman\plate_recognition\main.py", line 18, in recognize_plate frame = cv2.imread(plate) ^^^^^^^^^^^^^^^^^ File "D:\Tamirauto\WebApp\venv\Lib\site-packages\ultralytics\utils\patches.py", line 26, in imread return cv2.imdecode(np.fromfile(filename, np.uint8), flags) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ io.UnsupportedOperation: fileno -
Did I write data migration for data type change in a correct way?
Say, I have a model TestModel: class TestModel(models.Model): field1 = models.CharField(max_length=255) field2 = models.IntegerField() def __str__(self): return f"{self.field1}" But I need to change the type of field2 to Text now. In order not to lose the data in TestModel model, I need to write a data migration. So I create a new model NewTestModel: class NewTestModel(models.Model): field1 = models.CharField(max_length=255) field2 = models.TextField() def __str__(self): return f"{self.field1}" Run python manage.py makemigrations command In 0006_newtestmodel.py migration file I add copy_data function and run it using migrations.RunPython(copy_data) from django.db import migrations, models def copy_data(apps, database_schema): TestModel = apps.get_model("data_migrations", "TestModel") NewTestModel = apps.get_model("data_migrations", "NewTestModel") for old_object in TestModel.objects.all(): new_object = NewTestModel( field1 = old_object.field1, field2 = old_object.field2 ) new_object.save() class Migration(migrations.Migration): dependencies = [ ('data_migrations', '0005_testmodel'), ] operations = [ migrations.CreateModel( name='NewTestModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('field1', models.CharField(max_length=255)), ('field2', models.TextField()), ], ), migrations.RunPython(copy_data) ] Then I delete TestModel model and run the migration commands. After that I rename NewTestModel to TestModel and once again run the migration commands. Everything worked out as it was supposed to. Did I do it right? -
How to show permissions in django admin project?
I have a django app. And I try in the admin panel of django restrict user permissions with the AUTHENTICATION AND AUTHORIZATION tab. But I noticed that something is missing in my existing django app on the AUTHENTICATION AND AUTHORIZATION tab. Because I installed a clean install from django. And the AUTHENTICATION AND AUTHORIZATION tab looked like: and the AUTHENTICATION AND AUTHORIZATION tab in my existing django app looks like: So as you can see in my existing django app the right part is missing of the user permissions. What I have done? Is checking the versions. And they are the same(clean version and exsting version) I am using django version: 5.0.6. and the libraries I checked the libraries installed with pip freeze of my exisiting version: anyio==4.2.0 asgiref==3.7.2 attrs==23.1.0 azure-common==1.1.28 azure-core==1.29.6 azure-storage-blob==12.19.0 azure-storage-common==2.1.0 certifi==2023.7.22 cffi==1.15.1 charset-normalizer==3.2.0 click==8.1.7 colorama==0.4.6 coreapi==2.3.3 coreschema==0.0.4 cryptography==39.0.0 defusedxml==0.7.1 Django==5.0.6 django-allauth==0.52.0 django-cors-headers==3.10.1 django-dotenv==1.4.2 django-filter==23.2 django-storages==1.14.2 djangorestframework==3.14.0 drf-spectacular==0.26.4 drf-yasg==1.20.0 exceptiongroup==1.2.0 gunicorn==21.2.0 h11==0.14.0 idna==3.4 inflection==0.5.1 isodate==0.6.1 itypes==1.2.0 Jinja2==3.1.2 jsonschema==4.19.0 jsonschema-specifications==2023.7.1 Markdown==3.4.4 MarkupSafe==2.1.3 oauthlib==3.2.2 packaging==23.1 Pillow==10.0.0 psycopg2==2.9.7 pycparser==2.21 PyJWT==2.6.0 pyrsistent==0.19.3 python-dateutil==2.8.2 python3-openid==3.2.0 pytz==2023.3.post1 PyYAML==6.0.1 referencing==0.30.2 requests==2.31.0 requests-oauthlib==1.3.1 rpds-py==0.10.2 ruamel.yaml==0.17.32 ruamel.yaml.clib==0.2.7 six==1.16.0 sniffio==1.3.0 sqlparse==0.4.4 typing_extensions==4.7.1 tzdata==2023.3 uritemplate==4.1.1 urllib3==2.0.4 uvicorn==0.23.2 waitress==2.1.2 And part of settings.py file of the existing app: LOGOUT_REDIRECT_URL … -
Error when displaying contents of a .csv in Django (backend in S3 AWS)
I'm having quite a trouble when displaying in JSON format the contents of a .csv file located in a S3 Bucket. I am able to do the GET method correctly, but I think that I'm doing something wrong when trying to display the contents of the previously mentioned file. It is not that I obtained something weird or an error, the label where the content should be just displays nothing. Current Python code is: def flightlogs(request): # configure boto3, this works csv_files = [] try: response = s3_client.list_objects_v2(Bucket=bucket_name) for obj in response.get('Contents', []): if obj['Key'].endswith('.csv'): csv_files.append(obj['Key']) except Exception as e: print(f"Error al listar archivos en el bucket: {e}") # this is for saving the content of the .csv csv_contents = {} # Itera sobre cada archivo CSV encontrado for file_key in csv_files: try: # Obtiene el objeto (archivo) desde S3 obj = s3_client.get_object(Bucket=bucket_name, Key=file_key) # Lee el contenido del archivo y lo decodifica como UTF-8 content = obj['Body'].read().decode('utf-8') # Lee el contenido CSV y lo convierte en una lista de diccionarios csv_reader = csv.DictReader(StringIO(content)) rows = list(csv_reader) # Convierte la lista de diccionarios a JSON con formato indentado csv_contents[file_key] = json.dumps(rows, indent=4) except Exception as e: # Manejo de errores … -
How to get a joined latest object in django ORM?
I have two tables 1:N related. I want to get only one latest deal model on each real_estate model. class RealEstate(gis_models.Model): class Meta: db_table = "real_estate" id = models.BigAutoField(primary_key=True, auto_created=True) name = models.CharField( help_text="부동산 이름", null=True, blank=True, max_length=30 ) build_year = models.SmallIntegerField( help_text="건축년도", null=False, blank=False ) regional_code = models.CharField( help_text="지역코드", null=False, blank=False, max_length=6, ) lot_number = models.CharField( help_text="지번(구획마다 부여된 땅 번호, 서울특별시 서초구 반포동 1-1)", null=False, blank=False, max_length=50, ) road_name_address = models.CharField( help_text="도로명 주소", null=True, blank=True, max_length=50 ) address = models.CharField( help_text="주소", null=True, blank=True, max_length=50 ) real_estate_type = models.CharField( help_text="부동산 타입", choices=REAL_ESTATE_TYPES, max_length=20, ) latitude = models.CharField( help_text="위도", null=False, blank=False, max_length=20 ) longitude = models.CharField( help_text="경도", null=False, blank=False, max_length=20 ) point = gis_models.PointField(geography=True, null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Deal(models.Model): class Meta: db_table = "deal" id = models.BigAutoField(primary_key=True, auto_created=True) deal_price = models.PositiveIntegerField( help_text="거래금액(전월세 보증금)", null=False, blank=False ) brokerage_type = models.CharField( help_text="중개/직거래(거래유형)", null=True, blank=True, choices=BROKERAGE_TYPES, max_length=10, ) deal_year = models.SmallIntegerField( help_text="계약년도(년)", null=False, blank=False ) land_area = models.CharField( help_text="대지권면적", null=False, blank=False, max_length=10 ) deal_month = models.SmallIntegerField( help_text="계약 월", null=False, blank=False ) deal_day = models.SmallIntegerField( help_text="계약 일", null=False, blank=False ) area_for_exclusive_use = models.CharField( help_text="전용면적(제곱미터)", null=False, blank=False, max_length=10 ) floor = models.CharField( help_text="층", null=False, blank=False, max_length=3 ) is_deal_canceled = models.BooleanField( help_text="해제여부(거래계약이 … -
I want to add chart in django for blog
I want to add chart in django blog using tinymce and i also use plugin but it doesnt work. i add this plugin in static/tinymce/plugins/chart_plugin/plugin.min.js file** tinymce.init({ selector: '#chart-result', height: 550, plugins: [ 'advlist autolink lists link image charmap print preview anchor', 'searchreplace visualblocks code fullscreen', 'insertdatetime media table contextmenu paste', 'highcharts highchartssvg noneditable' ], toolbar: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image' }); and i aslo add default conf in settings.py file: `TINYMCE_DEFAULT_CONFIG = { "entity_encoding": "raw", 'menubar': True, 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking contextmenu directionality searchreplace wordcount visualblocks visualchars code fullscreen autolink lists charmap print hr anchor pagebreak chart_plugin ''', "toolbar": "fullscreen preview | undo redo | bold italic forecolor backcolor | formatselect | image link | " "alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist checklist | fontsizeselect " "emoticons | ", 'width': '70%', 'height': 700, "custom_undo_redo_levels": 50, "quickbars_insert_toolbar": False, "file_picker_callback": """function (cb, value, meta) { var input = document.createElement("input"); input.setAttribute("type", "file"); if (meta.filetype == "image") { input.setAttribute("accept", "image/"); } if (meta.filetype == "media") { input.setAttribute("accept", "video/"); } input.onchange = … -
Django-CMS 4.1.1 Can't edit pages via Page menu or Toggle Structure button
Django 5.0.6 Django-CMS 4.1.1 Stock Install Following this "Install Django-CMS by Hand" tutorial I am unable to edit any pages I create. All edit options are grayed out under the "Pages" menu and the "Toggle Structure" is disabled. I am attempting these page edits using the superuser account I created during site installation. I even manually added all permissions to my superuser account just in case it was permissions issue. Also when I use the '?edit' option at the end of the page url an error is written to the log file: Method Not Allowed: /en/admin/djangocms_versioning/pagecontentversion/2/edit-redirect/ I am using the base.html template that was installed by default (I added 'load static'): {% extends "bootstrap5/base.html" %} {% load cms_tags sekizai_tags %} {% load static %} <html> <head> <title>{% page_attribute "page_title" %}</title> {% render_block "css" %} </head> <body> {% cms_toolbar %} {% placeholder "content" %} {% render_block "js" %} </body> </html> I am about to reinstall, any ideas? I tried to edit pages I created with Django-CMS using several different methodologies: Page Menu Toggle Structure ?edit parameter to url I am using a superuser account and should have all necessary privileges but all editing attempts failed as the options are grayed out. -
django: Sending JSON-Data from within main.js back to view for processing/updating database
I'm having trouble sending data from my main.js back to django so that it can be processed there and the database can be updated. The user who is logged in can manipulate the data given by the WorkshopMasterView within in the template/frontend. By submitting the data the current JSON-object needs to be send back to django for processing. I receive the following error messages: main.js:379 POST http://127.0.0.1:8000/workshop-master-view/ 404 (Not Found) sendJsonToServer @ main.js:379 (anonymous) @ main.js:420 Here is the underlying logic: path("workshop/", WorkshopMasterView.as_view(), name="workshop-master-view"), path('process_json/', ProcessJsonView.as_view(), name='process_json'), class WorkshopMasterView(generic.ListView): model = WorkshopSpaceRequest template_name = 'management/workshop_master.html' context_object_name = 'data' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) datum = self.request.GET.get('datum') try: date_obj = datetime.strptime(datum, '%d.%m.%Y').date() if datum else datetime.today().date() except ValueError: date_obj = datetime.today().date() workshop_spaces = WorkshopSpace.objects.all() current_user = self.request.user if current_user.is_authenticated: current_user_data = { "acronym": str(current_user.acronym), "cost_center": current_user.cost_center, "user_id": current_user.username, "user_first_name": current_user.first_name, "user_last_name": current_user.last_name, } else: current_user_data = { "acronym": 0, "cost_center": 0, "user_id": 0, "user_first_name": 0, "user_last_name": 0, } data = { "date": date_obj.strftime('%Y-%m-%d'), "current_user": current_user_data, "rooms": [] } for space in workshop_spaces: room_data = { "name": space.workshop_space_number, "workshop_space_size": str(space.workshop_space_size), "availability_electricity": str(space.availability_electricity), "availability_wifi": str(space.availability_wifi), "availability_lifting_ramp": str(space.availability_lifting_ramp), "availability_workplace": str(space.availability_workplace), "time_slots": { "0000-0300": 0, "0300-0600": 0, "0600-0900": 0, "0900-1200": 0, "1200-1500": 0, "1500-1800": … -
Problem with chrome web browsers and Django sign in
I have a problem that I can't get my head around. I guess that an answer is out there.... I have deployed an Django app. In local server (development) the user can regardless of browser sign in to the Django app. Now when I have deployed the app using AWS Lightsail, Nginx, and Gunicorn. I experience an issue with the Chrome browser. When user after "signed in" is redirected to the home page. The user get "signed out" from Django. I have logged (using print(self.request.user)) the sign in process and can see that the user/password is accepted and that the self.request.user is "signed in". But when the user is redirected, the self.request.user is None. What I have a hard time understanding is that the same Chrome browser window works with the local server but not on the deployed server. Gunicorn worker doesn't logg out so it shouldn't be a memory issue? I've been looking for similar questions, perhaps someone can direct me to them. Any coding that needs to be shared? -
ImageSequenceClip from moviepy library gives me Exception: ImageSequenceClip requires all images to be the same size
this is my function def create_image_sequence(images, fps=None, aspectRatio=None, resolution=None): ''' Takes request.FILE images and makes video sequence it finnaly transfers to gif DONT FORGET TO DELETE GIF ''' #STORING IMAGES INTO TMP FOLDER imagesTMPpaths = [] for key, value in images.items(): ext = photo_extension(value) tmp_image = tempfile.NamedTemporaryFile(delete=False, suffix=ext) tmp_image.write(io.BytesIO(value.read()).read()) tmp_image.close() imagesTMPpaths.append(tmp_image.name) print(f'{key}: {value}') #GETTING SMALLEST WIDTH -------- images_sizes = [] for image_tmp_path in imagesTMPpaths: with Image.open(image_tmp_path) as img: width, height = img.size #returns duplets images_sizes.append([width*height, width, height]) images_sizes.sort() #it automaticly sorts by its first value print('xxxxxxx\nSize resizing to: ', images_sizes[0], '\nxxxxxxx') #GETTING SMALLEST WIDTH end -------- #RESIZE IMAGES TO SMALLEST ONE -------- print('\nresizing proces\n-------') for image_tmp_path in imagesTMPpaths: #https://stackoverflow.com/a/4271003 (resize with black fillers/padding) with Image.open(image_tmp_path) as img: print('\noriginal size: ', img.size) imgModified = ImageOps.pad(Image.open(image_tmp_path), (images_sizes[0][1], images_sizes[0][2]), color='black') imgModified.save(image_tmp_path) print('modified size: ', imgModified.size) print('PASSED: ', imgModified.size == (images_sizes[0][1], images_sizes[0][2]), '\n') # Verify all images have been resized correctly for image_tmp_path in imagesTMPpaths: with Image.open(image_tmp_path) as img: img = Image.open(image_tmp_path) print('size: ', img.size) print('PASSED: ', img.size == (images_sizes[0][1], images_sizes[0][2]), '\n') print(imagesTMPpaths) print(type(fps)) print(f'fps: --{fps}--') print(fps not in [None,'']) # Creating image sequence clip if fps in [0, None, '']: fps = len(imagesTMPpaths) else: fps = int(fps) imageSequence = ImageSequenceClip(imagesTMPpaths, fps=fps) if resolution … -
Corsheaders: trying to connect my django api to a react project, help needed
I'm trying to connect a django Rest API to a react project, the API is deployed to heroku and seems to be working as intended, but when trying to signup on my react project I'm getting the following error message in the console: Access to XMLHttpRequest at 'https://productive-you-api-d9afbaf8a80b.herokuapp.com/dj-rest-auth/registration/' from origin 'https://3000-leighallend-productivey-5rpfnq7ldhc.ws.codeinstitute-ide.net' has been blocked by CORS policy: Request header field content-tye is not allowed by Access-Control-Allow-Headers in preflight response. My cors section in the api's settings.py file is this: CORS_ALLOWED_ORIGINS = [] CORS_ALLOWED_ORIGIN_REGEXES = [ r"^https://.*\.gitpod\.io$", r".codeinstitute-ide.net$", ] if 'CLIENT_ORIGIN' in os.environ: CORS_ALLOWED_ORIGINS = [ os.environ.get('CLIENT_ORIGIN') ] else: CORS_ALLOWED_ORIGINS.extend([ 'https://3000-leighallend-productivey-5rpfnq7ldhc.ws.codeinstitute-ide.net', 'https://productive-you-api-d9afbaf8a80b.herokuapp.com', ]) CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = list(default_headers) + [ 'Content-Type', ] I have no idea what any of this means I tried to connect my api to the react project as done in a tutorial for my course with Code Institute, I expected to be able to create a user but my corsheaders are causing issues. -
Django Media Files Not Found (404) on Render Deploy
I'm having trouble serving media files on my Django application deployed on Render. The media files are being created and stored (I think) correctly on the server, but accessing them through the browser results in a 404 error. Everything works fine in my local development environment. Project Setup: settings.py: import os from pathlib import Path import environ import dj_database_url # Initialize environment variables env = environ.Env( DEBUG=(bool, False) ) # Read .env file environ.Env.read_env(os.path.join(Path(__file__).resolve().parent.parent, '.env')) # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Static and Media files STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = '/var/data/media' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] # Static files finders STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] # Ensure static files are served using Whitenoise MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', 'allauth.account.middleware.AccountMiddleware', ] # Whitenoise storage STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # Other settings... # URL configuration urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) File Existence: I have verified that the media files are being created on the server: render@srv-cpoif12ju9rs738p174g-5f676c9f8c-bwxhd:~/project/src$ ls -l /var/data/media/subtitles/U-sEgjJRHcM_subtitles.json -rwxr-xr-x 1 render render 14995 Jun 22 14:53 /var/data/media/subtitles/U-sEgjJRHcM_subtitles.json URL Patterns: from django.contrib import admin from django.urls import path, include from django.conf import … -
Django Media Files Not Found (404) on Render Deployment
I'm having trouble serving media files on my Django application deployed on Render. The media files are being created and stored (I think?) correctly on the server, but accessing them through the browser results in a 404 error. Everything works fine in my local development environment. Project Setup: settings.py: # Initialize environment variables env = environ.Env( DEBUG=(bool, False) ) # Read .env file environ.Env.read_env(os.path.join(Path(__file__).resolve().parent.parent, '.env')) # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Static and Media files STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = '/var/data/media' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] # Static files finders STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] # Ensure static files are served using Whitenoise MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', 'allauth.account.middleware.AccountMiddleware', ] # Whitenoise storage STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # Other settings... # URL configuration urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) File Existence: I have verified that the media files are being created on the server: render@srv-cpoif12ju9rs738p174g-5f676c9f8c-bwxhd:~/project/src$ ls -l /var/data/media/subtitles/U-sEgjJRHcM_subtitles.json -rwxr-xr-x 1 render render 14995 Jun 22 14:53 /var/data/media/subtitles/U-sEgjJRHcM_subtitles.json URL Patterns: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Issue: Despite the file existing on the server, accessing it via the URL results in a … -
Getting this issue of no module named pip and says not likely an error with pip
My Django project was working fine...For some reason I delete my virtual environment. I created new virtual environment and activate it. But now, I am getting this issue all of a sudden...My python version 3.12.3 ... I changed it to Python 3.11.7 but it didnt solve...This error is for python 3.12.3 version..I also installed wheel package, but it didnt work. I also installed pip install zombie-imp What is the issue? error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [20 lines of output] Traceback (most recent call last): File "E:\kvwsmb\myvenv\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 353, in <module> main() File "E:\kvwsmb\myvenv\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 335, in main json_out['return_val'] = hook(**hook_input['kwargs']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\kvwsmb\myvenv\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 118, in get_requires_for_build_wheel return hook(config_settings) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Saroj\AppData\Local\Temp\pip-build-env-v7wrdfbd\overlay\Lib\site-packages\setuptools\build_meta.py", line 327, in get_requires_for_build_wheel return self._get_build_requires(config_settings, requirements=[]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Saroj\AppData\Local\Temp\pip-build-env-v7wrdfbd\overlay\Lib\site-packages\setuptools\build_meta.py", line 297, in _get_build_requires self.run_setup() File "C:\Users\Saroj\AppData\Local\Temp\pip-build-env-v7wrdfbd\overlay\Lib\site-packages\setuptools\build_meta.py", line 497, in run_setup super().run_setup(setup_script=setup_script) File "C:\Users\Saroj\AppData\Local\Temp\pip-build-env-v7wrdfbd\overlay\Lib\site-packages\setuptools\build_meta.py", line 313, in run_setup exec(code, locals()) File "<string>", line 7, in <module> ModuleNotFoundError: No module named 'imp' [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> … -
Docker can't connect my mysql container with djngo container
I have two separate container. When I am trying to connect MySQL with my Django container I am getting this error: django_farhyn | super().__init__(*args, **kwargs2) django_farhyn | django.db.utils.OperationalError: (2005, "Unknown server host 'mysql' (-2)") This docker compose file for mysql , phpmyadmin and using for others services: version: '3' services: mysql: image: mysql:8 container_name: mysql environment: MYSQL_ROOT_PASSWORD: test MYSQL_USER: test MYSQL_PASSWORD: test MYSQL_DATABASE: testdb ports: - "3306:3306" restart: always phpmyadmin: image: phpmyadmin/phpmyadmin container_name: phpmyadmin environment: PMA_HOST: mysql MYSQL_ROOT_PASSWORD: test ports: - "8080:80" depends_on: - mysql restart: always This docker compose file for only django project version: '3' services: django_farhyn: build: . container_name: django_farhyn command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" # Django application port mapping here my db settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': config('MYSQL_DATABASE', default=''), 'USER': config('MYSQL_USER', default=''), 'PASSWORD': config('MYSQL_PASSWORD', default=''), 'HOST': 'mysql', 'PORT': '3306', } } I don't know where I am doing mistake and struggling from few hours for connect mysql container with my django docker container. -
How to customize the message for inactive user in Djoser?
I am working on a Django project and I am using Djoser as my auth library. However, when a user is trying to create a jwt token it returns { "detail": "No active account found with the given credentials" } for when there is no user with the credentials and when there is a user but is inactive. After some research, I found the piece of code below which was used to override the TokenObtain in the simplejwt library which djoser was written on top of but I don't know how to actually go about it. I am fairly new to Djoser. from rest_framework import status, exceptions from django.utils.translation import gettext_lazy as _ from rest_framework_simplejwt.serializers import TokenObtainPairSerializer, TokenObtainSerializer class CustomTokenObtainPairSerializer(TokenObtainPairSerializer, TokenObtainSerializer): # Overiding validate function in the TokenObtainSerializer def validate(self, attrs): authenticate_kwargs = { self.username_field: attrs[self.username_field], 'password': attrs['password'], } try: authenticate_kwargs['request'] = self.context['request'] except KeyError: pass # print(f"\nthis is the user of authenticate_kwargs {authenticate_kwargs['email']}\n") ''' Checking if the user exists by getting the email(username field) from authentication_kwargs. If the user exists we check if the user account is active. If the user account is not active we raise the exception and pass the message. Thus stopping the user from getting … -
In VS code facing issue with RUN AND DEBUG for DJANGO
I am running RUN AND DEBUG with django. if i click the run and debug button, it starts and ends in 2 secs. Not showing any error, just stops. Not sure why. adding the launch.json for reference { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python Debugger: Django", "type": "debugpy", "request": "launch", "args": [ "runserver" ], "django": true, "autoStartBrowser": false, "program": "${workspaceFolder}\\manage.py" } ] } I tried changing the values of each key, no use. I am beginner for django. Please help me out -
Django REST Framework ValueError: Cannot query "John Smith": Must be "User" instance
I am working on a Django project with Django REST Framework, and I'm encountering a ValueError when trying to filter orders by customer ID. Here is the error traceback: Internal Server Error: /orders/ Traceback (most recent call last): File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/django/views/decorators/csrf.py", line 65, in _view_wrapper return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/rest_framework/viewsets.py", line 124, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/rest_framework/mixins.py", line 38, in list queryset = self.filter_queryset(self.get_queryset()) ^^^^^^^^^^^^^^^^^^^ File "/home/mango/Desktop/blessings/econ/AdnexumActio/views.py", line 264, in get_queryset return Order.objects.filter(customer_id=customer_id) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/django/db/models/manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/django/db/models/query.py", line 1476, in filter return self._filter_or_exclude(False, args, kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/django/db/models/query.py", line 1494, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/django/db/models/query.py", line 1501, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/django/db/models/sql/query.py", line 1613, in add_q clause, _ = self._add_q(q_object, self.used_aliases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/django/db/models/sql/query.py", line 1645, in _add_q child_clause, needed_inner = self.build_filter( ^^^^^^^^^^^^^^^^^^ … -
Remove products from the shopping cart
When removing the product from the shopping cart, the removing button does not work my view: class CartDeleteView(View): def get(self, request, id): cart = Cart(request) cart.delete(id) return redirect('cart:cart_detail') def delete(self, id): if id in self.cart: del self.cart[id] self.save() -
How to fetch dropdown from database in the Django ? (Uncaught TypeError: Cannot read properties of null (reading 'classList'))
I am fetching a dropdown from the the database in the Django, Everything is loading while I am inspecting it, but the dropdown is not opeing up. {% if part_data.part.has_ML_Model %} <div class="btn-group"> <button type="button" class="btn btn-success dropdown-toggle" id="dropdownMenuButton{{ forloop.counter }}" data-bs-toggle="dropdown" aria-expanded="false"> {{ part_data.dropdown.0.dropdown_label }} </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton{{ forloop.counter }}"> {% for dropdown in part_data.dropdown %} <li><a class="dropdown-item" href="#">{{dropdown.dropdown_item_one}}</a></li> <li><a class="dropdown-item" href="#">{{dropdown.dropdown_item_two}}</a></li> <li><a class="dropdown-item" href="#">{{dropdown.dropdown_item_three}}</a></li> {% endfor %} </ul> </div> {% endif %} ** My model : ** class CaseStudy_ML_Model(models.Model): case_study_part = models.ForeignKey(CaseStudy_Parts, on_delete=models.CASCADE, null=True) dropdown_label = models.CharField(max_length=255 ,default="") dropdown_item_one = models.CharField(max_length=255, default="") dropdown_item_two = models.CharField(max_length=255, default="") dropdown_item_three = models.CharField(max_length=255, default="") **My views : ** def casestudy(request, CaseStudy_id ): casestudy_object = get_object_or_404(CaseStudy_List, CaseStudy_id = CaseStudy_id) #for list casestudy_parts_obj = CaseStudy_Parts.objects.filter(case_study=casestudy_object).order_by('CaseStudy_order').distinct() #for accordians parts_data = [] #storing in a singlist to avoid duplicacy for part in casestudy_parts_obj: part_content = CaseStudy_Content.objects.filter(case_study_part = part) part_media = CaseStudy_Media.objects.filter(case_study_part = part) part_button = CaseStudy_Buttons.objects.filter(case_study_part = part) part_dropdown = CaseStudy_ML_Model.objects.filter(case_study_part = part) # # Logic to determine if button required for media # has_button_for_media = False # # You can modify this logic based on your specific criteria # if part_media.exists() and part_button.exists(): # Check for media and buttons # has_button_for_media = True parts_data.append({ … -
google ads not working in django (i have installed google ads ) yet it is not confirming the location
I'm working on a Django project where I need to use the Google Ads API. I've installed the google-ads library using pip install google-ads, but I keep encountering an import error when trying to import GoogleAdsClient. Here are the details of my setup and the steps I've followed: pip install google-ads pip list | findstr google-ads google-ads 24.1.0 from google.ads.googleads.client import GoogleAdsClient thisall of this is not working what to do now -
Python on Hosting, access localhost on client-side
I need your help. I have django application that running on hosting provider, and I have function that do requests to localhost application that running on my own computer. How to do requests to localhost application on my own computer? Because when I do requests to localhost its getting error because requests doing requests on the server side and not on client side. I dont want to install anything on my clientside. I want to get the code to solve my problem -
Implementing PHP into Django project
I have a project done in PHP format and I have to include Python Django to implement my machine learning algorithms such as SVM, random forest, logistic regression, and naive Bayes. Is it possible to do so? Can I use my Django project to include my PHP files? Also, my PHP files are under xampp htdocs while my Django project is under the C: folder Can you help me with the codings so I can put them in my Django project to include my PHP files? -
AssertionError in django project
I am trying to test a API to create a company but it gives me a assertion error, it says that i need to create a custom .create() method but I have already defined that but still getting the error. serializer.py ```python class TaxInformationSerializer(serializers.ModelSerializer): class Meta: model = TaxInformation fields = '__all__' def create(self, validated_data): return TaxInformation.objects.create(**validated_data) class CompanySerializer(serializers.ModelSerializer): tax_information = TaxInformationSerializer() class Meta: model = Company fields = ["brand_name", "legal_name", "mobile", "telephone_no", "fax", "status", "tax_information"] read_only_fields = ['user', 'created_at'] def create(self, validated_data): # Automatically set the user to the request user request = self.context.get('request') if request and hasattr(request, 'user'): validated_data['user'] = request.user return super().create(validated_data) # Create the tax information instance tax_information_data = validated_data.pop('tax_information') # tax_information = TaxInformation.objects.create(**tax_information_data) tax_information_serializer = TaxInformationSerializer(data=tax_information_data) tax_information_serializer.is_valid(raise_exception=True) tax_information = tax_information_serializer.save() # Create the company instance with the tax information instance = Company.objects.create(tax_information=tax_information, **validated_data) return instance and the error is AssertionError at /datamanagement/company The `.create()` method does not support writable nested fields by default. Write an explicit `.create()` method for serializer `datamanagement.serializers.CompanySerializer`, or set `read_only=True` on nested serializer fields. I have already defined a custom create method but still getting the error. -
Why are my django-allauth socialaccount template tags empty?
I am using Django 5.0.6 with django-allauth 0.63.3. I followed the allauth quick start guide to configure my settings.py and used pip install "django-allauth[socialaccount]" , and was able to setup google and github SSO providers through settings.py file. settings.py SOCIALACCOUNT_PROVIDERS = { 'github': {...}, 'google': {...}, } I confirmed they both show up and links work in "/accounts/login" endpoint from allauth. However, when making a custom login form, the template tags are empty allauth template reference. login.html {% load socialaccount %} {% get_providers as socialaccount_providers %} <div>{{socialaccount_providers}}</div> I have also tried configuring the providers through the django admin console, but that did not solve the issue. It just made the login page have conflicting duplicate links. I have also reinstalled the package through pip.