Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
0 static files copied to 'C:\Users\Reynald\Desktop\Test\cdo_portal\staticfiles', 2365 unmodified
Hello everyone might someone here know how to fix this i just trying to run the py manage.py collectstatic but when i run the sytsem all of the design was a mess and when i check the collecstatic "0 static files copied to 'C:\Users\Reynald\Desktop\Test\cdo_portal\staticfiles', 2365 unmodified." not sure of that I already tried another way to fix this but still not working -
%20 in my url to static javascript file in django application
I have base template core/layout.html and it contains scripts block in it: <script type="text/javascript" src="{% static "core/js/tinymce/tinymce.min.js" %}"></script> <script src = "{% static "core/js/flowbite.min.js" %}"></script> <!-- <script src = "{% static "core/js/index.js" %}"></script> --> {% block scripts %} {% endblock scripts %} So the problem is in url to javascript file (index.js). If I include it in layout.html (base template) everything works perfect, but when i put it in my child template: {% block scripts %} <script src="{% static 'core/js/index.js' %}"></script> {% endblock scripts %} it throws an error: GET 127.0.0.1:8000/static/%20core/js/index.js net::ERR_ABORTED 404 (Not Found) I even have tried to hard code it, still the same problem. -
Mark a view function as being exempt from the CSRF view protection
(function) def csrf_exempt(view_func: _F@csrf_exempt) -> _F@csrf_exempt Mark a view function as being exempt from the CSRF view protection. Make sure disabling CSRF protection is safe here. sonarlint(python:S4502) How to fix this issue on sonarcloud?. (function) def csrf_exempt(view_func: _F@csrf_exempt) -> _F@csrf_exempt Mark a view function as being exempt from the CSRF view protection. Make sure disabling CSRF protection is safe here. sonarlint(python:S4502) -
why does my SQLlite database in django does not show the same records when I run it on a different machine; (running the server on Local Host)
So I am trying to build a basic Task managing app. The main issue is with the database, me and my friend have the exact same code we pulled from the rep, when he and I run the server on local host and try using the website, like creating account and adding tasks, but when we open the admin panel I can only see my tasks and the accounts in the User Database that were created on my machine, and my friend can see the accounts and tasks created on his machine, though our databases are same, they are not displaying the same records, this wasn't an issue before, if he would add a task and create account I can see it in my admin panel thru my machine and vice versa, I don't exactly know what happened. its like the databases are not synced are being emptied everytime you run the website on a different machine. this is giving us trouble, because we are working on an invite feature when you can enter a users email in a specific task then that user would start seeing the task on his machine, since the databases are not in sync the … -
Django model field "null together or not at all" constraint
I need a way to create either a validator or a constraint at model level to evaluate two or more fields to be able to be null/blank only if all of them are null/blank at the same time. For example, in the next model: from django.db import models class Example(models.Model): A = models.CharField(max_length=16,blank=True) B = models.DateField(null=True,blank=True) C = models.FileField(uploadto='/',null=True) if I try to create a new Example with either B or C values empty it should raise a ValidationError; but if both of them are empty it should be OK. -
SynchronousOnlyOperation Error in Django Class Based Views
I am making a Django app, but I can't use async views, I installed uvicorn and asgi, but I get this error: SynchronousOnlyOperation at /chatbot/chat/ You cannot call this from an async context - use a thread or sync_to_async. @method_decorator(login_required(login_url=settings.LOGIN_URL), name='dispatch') @method_decorator(never_cache, name='dispatch') class ChatView(View): async def get(self, request, *args, **kwargs): """ This method return our chatbot view """ response = await sync_to_async(render)(request, 'chatbot/chat.html') return response -
cv2.error: OpenCV(4.10.0) D:\a\opencv-python\opencv-python\opencv\modules\objdetect\src\qrcode.cpp:32: error: (-215:Assertion failed) !img.empty()
i write a bot to decode qr-codes from user's message and send im data back. now i have an error cv2.error: OpenCV(4.10.0) D:\a\opencv-python\opencv-python\opencv\modules\objdetect\src\qrcode.cpp:32: error: (-215:Assertion failed) !img.empty() in function 'cv::checkQRInputImage' code: @decode_router.message(lambda message: True) async def decode(message: Message): await main.bot.send_message(message.chat.id, "Decoding...") fl = main.bot.download_file(message.photo, f"qrcode{message.from_user.id}.png") fl = FSInputFile(f"qrcode{message.from_user.id}.png", f"qrcode{message.from_user.id}.png") img = cv2.imread(f"qrcode{message.from_user.id}.png") detector = cv2.QRCodeDetector() data, vebb, f = detector.detectAndDecode(img) await message.reply(data) what that error means and what should i do to fix it? -
Google authentication with django-allauth fails due to "OAuth2Error: Invalid id_token"
I am trying to set-up Google authentication for my DRF + Next.js web app. I've been following this guide. I am using django-allauth 0.61.1 and dj-rest-auth 6.0.0. If I try to pass both access and it tokens: ... const SIGN_IN_HANDLERS = { credentials: async (user, account, profile, email, credentials) => { return true; }, google: async (user, account, profile, email, credentials) => { try { const response = await axios({ method: "post", url: process.env.NEXTAUTH_BACKEND_URL + "auth/google/", data: { access_token: account["access_token"], id_token: account["id_token"], }, }); account["meta"] = response.data; return true; } catch (error) { console.error(error); return false; } }, }; const SIGN_IN_PROVIDERS = Object.keys(SIGN_IN_HANDLERS); export const authOptions = { pages: { signIn: "/login", }, secret: process.env.AUTH_SECRET, session: { strategy: "jwt", maxAge: BACKEND_REFRESH_TOKEN_LIFETIME, }, providers: [ CredentialsProvider({ name: "Credentials", credentials: {}, async authorize(credentials, req) { console.log("here"); try { const response = await axios({ url: process.env.NEXTAUTH_BACKEND_URL + "auth/login/", method: "post", data: credentials, }); const data = response.data; if (data) return data; } catch (error) { console.error(error); } return null; }, }), GoogleProvider({ clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, authorization: { params: { prompt: "consent", access_type: "offline", response_type: "code", }, }, }), ], callbacks: { async signIn({ user, account, profile, email, credentials }) { if (!SIGN_IN_PROVIDERS.includes(account.provider)) … -
How to add permissions in django admin panel for user?
I have a django app. And I added in the admin panel of django the following permission: Accounts | account | Can view account And in the code of admin.py of the accounts app. I added this: from django.contrib.auth import get_user_model from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType from .models import Account User = get_user_model() user = User.objects.get(email='n@n.nl') content_type = ContentType.objects.get_for_model(Account) permission = Permission.objects.get( codename='view_account', content_type=content_type) user.user_permissions.add(permission) class AccountAdmin(UserAdmin): list_display = ( "email", "first_name", "last_name", "username", "last_login", "date_joined", "is_active", ) list_display_links = ("email", "first_name", "last_name") filter_horizontal = ( 'groups', 'user_permissions', ) readonly_fields = ("last_login", "date_joined") ordering = ("-date_joined",) list_filter = () User = get_user_model() user = User.objects.get(email='n@n.nl') content_type = ContentType.objects.get_for_model(Account) permission = Permission.objects.get( codename='view_account', content_type=content_type) user.user_permissions.add(permission) admin.site.register(Account, AccountAdmin) And when I start the django app. I don't get any errors. But when I login with the account with the user permission. I still see the message: You don’t have permission to view or edit anything. And the permissions: Is active Is staff are selected Question: how to add permissions for users? -
how to force a maximum map extent for geonode docker?
I’m running geonode docker, how do I need to modify the .env file to force a maximum map extent (e.g. Italy)? This is my local installation procedure using the default .env git clone -b 4.0.2 https://github.com/GeoNode/geonode.git cd .\geonode\ docker compose build docker compose up -d I modify the .env and run docker compose down and docker compose up -d (https://docs.geonode.org/en/master/install/basic/index.html#customize-env-to-match-your-needs) ADMIN_PASSWORD=admin4 # works and takes effect DEFAULT_MAP_ZOOM=10 # works and takes effect DEFAULT_MAP_CENTER_X=50 # does not work (if this does not work how can max force extent work) DEFAULT_MAP_CENTER=50 # does not work What are variable names and how to use them to force a maximum map extent ? -
Django random can't connect to mysql
In django I'm getting can't connect to mysql randomly it works fine and just gives it to me and on refresh it works fine, completely random, I can't even reproduce it. any ideas? compose file: networks: my_network: driver: bridge ipam: config: - subnet: 172.16.238.0/24 gateway: 172.16.238.1 services: web: extra_hosts: - "host.docker.internal:host-gateway" networks: my_network: ipv4_address: 172.16.238.6 restart: always depends_on: - db env_file: - ./backend/.env image: project-api build: context: . dockerfile: backend/Dockerfile.dev command: bash -c "python manage.py migrate && python manage.py collectstatic --noinput && gunicorn project.wsgi -b 0.0.0.0:9001" volumes: - ./backend:/code - ./backend/logs:/logs db: image: mysql:8.0 command: mysqld --default-authentication-plugin=mysql_native_password restart: always volumes: - ./backend/data:/var/lib/mysql - ./db/init.sql:/docker-entrypoint-initdb.d/init.sql networks: my_network: ipv4_address: 172.16.238.9 environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: dev_db MYSQL_USER: dev_db_user MYSQL_PASSWORD: root -
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 ╰─> …