Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I encounter an error during the initial access, but subsequent accesses are normal
django.urls.exceptions.NoReverseMatch: Reverse for 'problem_detail' with arguments '(Undefined,)' not found. 1 pattern(s) tried: ['problem/(?P[^/]+)$'] this is my (codehttps://www.ideone.com/464jH9) in urls.py and this is my url : ltoj.edu.vn/problem/xau2 -
Django Invalid OTP Error - Two step login System in Django
This is my login view: def login_view(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: if user.is_active is False: messages.error(request, 'Your account has not been verified yet. Please verify your account!') return redirect(reverse('account_login')) mail_subject = "One Time Password - OTP" message = render_to_string('registration/otp_verify_email.html', { 'user': request.user, 'otp': get_otp(request), }) to_email = user.email try: send_mail( subject=mail_subject, message=message, from_email=settings.EMAIL_HOST_USER, recipient_list=[to_email], fail_silently=False ) request.session['username'] = username messages.success(request, "OTP has been sent to your mail!") return redirect('verifyotp') except Exception as e: messages.error(request, "Error occurred while sending mail. Please try again.") return render(request, 'registration/login.html') else: messages.error(request, "Invalid username or password!") return render(request, 'registration/login.html') This is otp verify view: def otp_view(request): if request.method == "POST": otp = request.POST.get('otp') username = request.session['username'] otp_secret_key = request.session['otp_secret_key'] otp_valid_until = request.session['otp_valid_until'] if otp_secret_key and otp_valid_until is not None: # Convert the stored timestamp string back to a datetime object valid_until = datetime.fromtimestamp(float(otp_valid_until)) if valid_until > datetime.now(): totp = pyotp.TOTP(otp_secret_key, interval=60) if totp.verify(otp): user = get_object_or_404(User, username=username) login(request, user) del request.session['otp_secret_key'] del request.session['otp_valid_until'] return redirect('home') else: messages.error(request, "Invalid OTP") else: messages.error(request, "OTP has been expired!") else: messages.error(request, "Something bad happened! Please try again!") return render(request, 'registration/otp_verify.html') I'm generation otp … -
Trouble in hosting Django project. Spacy nlp = spacy.load("en_core_web_sm")
I am hosting a small Django project. The project is running perfectly on my local machine but on the deployed site, it says OSError at / [E050] Can't find model 'en_core_web_sm'. It doesn't seem to be a Python package or a valid path to a data directory. The error is occuring in my views.py file where I had writted, import spacy nlp = spacy.load("en_core_web_sm") This is my requirements.txt file. (for hosting) asgiref==3.4.1 Django==3.2.8 python-dateutil==2.8.2 six==1.16.0 sqlparse==0.4.2 tzdata==2021.5 gunicorn==20.1.0 spacy==3.1.3 I already tried adding en-core-web-sm==3.1.0 but it's giving another error and frankly it's redundant because we already included spacy==3.1.3 I'm don't understand that error as everything is working fine when I run the project on my local machine. But it's not in the deployed site. Here are the github repo and the hosted site links, GitHub Repo Hosted site (Vercel) If you're trying out the website, upload the file and click generate masked text. Then you'll see the error. -
How to save PDF quickly
1 There are many images stored on the server, and the necessary images are selected from them. 2 Afterwards, each image is arranged in the form of a worksheet and saved. Frontend - Vue Backend - Django database - PostgreSQL Currently, PDFs are being generated from the Django queue using a PDF API. However, the generation speed is slow, and I wonder if you could tell me how to generate 40 pages of images within 3 seconds. There are many images. enter image description here enter image description here PDFs are being generated from the Django queue using a PDF API. The speed is considerably slow. -
Can't access "on_delete" argument of model field using _meta class (Django)
Title. I'm trying to access the on_delete argument of the field "org" here: class OrgLocation(models.Model): org = models.OneToOneField( Org, primary_key=True, on_delete=models.CASCADE, blank=True ) And I'm trying to access it with: OrgLocation._meta.get_field("org").on_delete But when I run this, I get an attribute error: AttributeError: 'OneToOneField' object has no attribute 'on_delete' Trying to access primary_key works just fine though (and same for blank). Not sure what's going on. Any suggestions? -
django-saml2-auth authenticates user but I get anonymous user in my view
I am using django-saml2-auth to authenticate my users. I see that the authentication is successful but in my view, the request.user is an anonymous user. Additional Info: I see that the call to /saml2/acs/ - request includes sessionid(a) and redirect to / with another request sessionid(b) The next HTTP call - to / - includes the received sessionid(b), but response includes sessionid with empty string enter image description here Here are django & django-saml2-auth version Django 4.2.7 grafana-django-saml2-auth 3.12.0 django-saml2-auth 2.2.1 Why is the user anonymous even after successfully logging in?' -
Search and pagination in Django
How do i ensure that the original search query is maintained when navigating to the next pagination page in Django? I attached if statement in my template to include the search query in the Url if it exists but it doesn't work -
How to make Django translations accessible from Javascript?
How do you make all of the Django app locale/<lang>/django.po translations accessible from Javascript so you can dynamically translate text in Javascript widgets? According to these docs you need to add a URL pattern to your urls.py like: urlpatterns += i18n_patterns( path("jsi18n/", JavaScriptCatalog.as_view(packages=['myapp1', 'myapp2', ....]), name="javascript-catalog"), and then in your base template's <head> add the includes: <script type="text/javascript" src="{% url 'admin:jsi18n' %}"></script> <script type="text/javascript" src="{% url 'javascript-catalog' %}"></script> I've done this, and I have Japanese locale/ja/django.po (and their compiled .mo) files for every app in my project. However, when I access the URLs generated by {% url 'admin:jsi18n' %} (/admin/jsi18n/) and {% url 'javascript-catalog' %} (/ja/jsi18n/) it doesn't contain any of my custom translations. Why is this? What step in the docs am I missing preventing my translations from being accessible in the Javascript catalog? -
CORS problem with django running on GCP compute engine code-server
I am working on a Django project. For that, I work both in my personal laptop as well on a remote code-server instance (VS Code Remote) running on GCP compute engine. I run code-remote on https://dev.myweb.com (fake url) and when running the django server via python manage.py runserver in port 8000 the built in proxy allows me to connect via https://dev.myweb.com/proxy/8000 I can get to the first page (base.html) without problem (no forms or request in that page). But when I click on login (which would bring a POST request, that I think is the problem?), I get a error like this: Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: Origin checking failed - https://dev.myweb.com does not match any trusted origins. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template’s render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you … -
Signal receivers must accept keyword arguments (**kwargs) when using pre_delete signal in Django
I am trying to make a destructor-similar signal in django to be called before any children of the class Base are deleted. The reason is that I need to change something on another models's field when this is deleted as part of cleaning up, and I want this to run when for example deleting the instance from Admin. I have this in my models.py: @receiver(pre_delete, sender = Base) def delete_shot_script(sender, instance, **kwargs): print("Calling the destructor") do_something... I am getting the error ValueError: Signal receivers must accept keyword arguments (**kwargs), why? Is the approach valid otherwise? I have tried adding **kwargs, but the error seems to persist. -
Django - PropertyFilterSet - How to filter on a property when the property refers to a model
How can I filter on a model's property with django_property_filter package given the following Django models: # models.py from django.db import models class Manager(models.Model): name = models.CharField(max_length=35) class Plan(models.Model): name = models.CharField(max_length=35) manager = models.ForeignKey(Manager, on_delete=models.CASCADE) class Member: name = models.CharField(max_length=35) plan = models.ForeignKey(Plan, on_delete=models.CASCADE) @property def manager(self): return self.plan.manager # filters.py from django_property_filter import PropertyFilterSet class Meta: model = Member fields = [] class MemberFilter(PropertyFilterSet): manager = ???( field_name='manager', ) I tried the PropertyMultipleChoiceFilter and PropertyChoiceFilter with no success. Choices was set to [(m.pk, m.name) for m in Manager.objects.all()]. -
Update mehod not working correctly in the serilizer (django rest framework)
here is the code my code i tried diffrent solution none of them work i also added function to add new question if the id is not here i think it didnt see the id and i tried logging it it says none i dont know why its not seeing my if but when i do get method i get the id in response so idont know what to do i hope i provided enough code for you thanks in advance for help serializer.py from rest_framework import serializers from .Models.QuizMaker import QuizMake from .Models.Answers import Answers from .Models.Questions import Questions import string, secrets def generate_quiz_session_token(): alphabet = string.ascii_letters + string.digits token = ''.join(secrets.choice(alphabet) for _ in range(8)) return token class AnswersSerializer(serializers.ModelSerializer): class Meta: model = Answers fields = ['id','answer', 'is_correct'] read_only_fields = ['id'] class QuestionSerializer(serializers.ModelSerializer): answers = AnswersSerializer(many=True) class Meta: model = Questions fields = ['id','question', 'description', 'image', 'answers'] read_only_fields = ['id'] class QuizSerializer(serializers.ModelSerializer): questions = QuestionSerializer(many=True) quiz_session_token = serializers.CharField(max_length=8, required=False) class Meta: model = QuizMake fields = ['id','name', 'req_time', 'fk_teacher_id', 'quiz_session_token', 'questions'] read_only_fields = ['id'] def create(self,validated_data): questions_data = validated_data.pop('questions') quiz = QuizMake.objects.create( name = validated_data['name'], req_time = validated_data['req_time'], fk_teacher_id = validated_data['fk_teacher_id'], quiz_session_token = generate_quiz_session_token(), ) for question_data in … -
Retrieve data from Django to Select Option through Datatable
I have a problem which I can't call Django data which is payrolled_list into select option after rendered datatable or it triggers. I just want the data from Django to reflect to select option but Im using Datatable to triggers and then reflect can anyone have an idea to regarding to my problem , I appreciate it a lot! What I tried populate data to select but don't know how to call it it is necessary using "{{payrolled_list}}" since it django and reflect to select2 ? drawCallback: function (settings) { let myDataTable = $('#tbl-box-a').DataTable(); let payrolledListData = []; $('#payroll-name').empty(); // Add an empty option $('#payroll-name').append('<option></option>'); // Populate options based on payrolled_list data for (let i = 0; i < payrolledListData.length; i++) { $('#payroll-name').append('<option value="' + payrolledListData[i].id + '">' + payrolledListData[i].name + '</option>'); } } html select <select id="payroll-name" name="PayrollName" class="form-select employee" data-allow-clear="true" ><option></option></select> Django payrolled_list = serialize('json', TevIncoming.objects.filter(status_id=4).order_by('first_name')) response = { 'data': data, //data is list 'payrolled_list': payrolled_list //this data I want to populate it to select option } return JsonResponse(response) This is my whole code datatable const table2 = $('#tbl-box-a'); if ($.fn.DataTable.isDataTable('#tbl-box-a')) { table2.DataTable().destroy(); } dataTable2 = table2.DataTable({ processing: true, serverSide: true, ajax: { url: "{% url 'employee-dv' %}", … -
Extract a subtree from the tree structure returned by DecisionTreeRegressor (recursive & iterative versions)
Given A starting root node and a certain depth, I want to extract the subtree from the scikit-learn's DecisionTreeRegressor tree. For that I want to implement and test both the iterative and the recursive versions which I have written and paste here below. The problem is that they don't return the same results (I suspect the recursive version is buggy). #recursive def get_subtree_from_rt(subtree, root_start, max_depth): if max_depth == 1: return [] nodes = [root_start] if root_start == -1: nodes.extend([root_start]) return nodes else: children = [child for child in [subtree.children_left[root_start], subtree.children_right[root_start]]] nodes.extend(child for child in children if child not in list(filter(lambda a: a != -1, nodes))) for child in children: nodes.extend(child for child in get_subtree_from_rt(subtree, child, max_depth - 1) if child not in list(filter(lambda a: a != -1, nodes))) return nodes #iterative def get_subtree_from_rt_iter(subtree, root_start, max_depth): return breadth_first_traversal(subtree, root_start, max_depth) def breadth_first_traversal(tree, root_start, t_depth): sub_tree = [] stack = deque() stack.append(root_start) sub_tree.append(root_start) while stack: current_node = stack.popleft() if current_node !=-1: left_child = tree.children_left[current_node] right_child = tree.children_right[current_node] children_current_node = [left_child, right_child] stack.extend(children_current_node) for child in children_current_node: sub_tree.append(child) current_depth = int(math.log2(len(sub_tree) + 1)) if current_depth == t_depth: break else: continue return sub_tree Could you tell me where is the bug/bugs in those snippets … -
Get the ID of the current logged-in user into a standalone script in Django?
I have a standalone script in Django that receives messages from a Redis server. Each incoming message is coded with a topic. Users of the site will indicate which topics they are interested in receiving messages for. Their preferences are stored in a database as True or False for each topic. I’m currently stuck trying to figure out a way to obtain the currently logged in user’s id so that I can reference their topic preferences against each incoming message’s topic. I can’t figure out how to get the ID of the currently logged in user into the standalone script. Does anyone know how to do this? I've been stuck on this for days so any insights would be greatly appreciated! -
Bringing a Django Model to a HTML Table
I am very new to Django and I am working on my first training project. I want to document every month a set of meters (water, electricity, and more) and I want to see those meters in a html table like: Nov 2023 Dec 2023 Jan 2024 Meter 1 500 510 Meter 2 1000 1300 Meter 3 100 110 120 I am using 4 models in models.py: model metertype -> electricity, water, and other types of meters model meter -> name/description of the meter model readingdate -> date of the reading, normally last day of month model readingsvalue -> the values I read from the meters from django.db import models class meterType(models.Model): meterType = models.CharField(max_length=100) class meter(models.Model): meterName = models.CharField(max_length=100) meterType = models.ForeignKey( meterType, on_delete=models.CASCADE) class readingDate(models.Model): date = models.DateField() class readingsValue(models.Model): readingsValue = models.DecimalField(max_digits=10, decimal_places=2) meter = models.ForeignKey(Zaehler, on_delete=models.CASCADE) readingDate = models.ForeignKey(Ablesedatum, on_delete=models.CASCADE) After this done (it seams to work in the admin area). I put up a view.py which is very basic: from django.shortcuts import render from .models import readingsValue, meter, meterType, readingDate def index(request): readingsValue = readingsValue.objects.all() meter = meter.objects.all() meterType = meterType.objects.all() readingDate = readingDate.objects.all() return render(request, "meters/index.html", {"meter": meter, "readingsValue": readingsValue, "meterType": meterType, "readingDate": readingDate, … -
Django ArrayField. How to save JSON in array from Django Admin?
I have an ArrayField in my model. My model looks like this: class UserProfile(UUIDPrimaryKeyModel): canceled_plans_data = ArrayField(models.JSONField(), default=list, blank=True) When I append python dict in this field, it gets saved and later fetched easily. But as soon as I open this model in Django Admin and without any change in any field of this model, click on save button, it gives me error. Error is following: Item 1 in the array did not validate: Enter a valid JSON. Item 2 in the array did not validate: Enter a valid JSON. I am not sure what's wrong. I have just shown this field in Admin Model like this: class UserProfileAdmin(admin.ModelAdmin): fields = ('user', 'canceled_plans_data',) How I can fix this problem? -
When I want the file schema.yml make with spectacular show in error assert isinstance(model_field, models.Field)
I want with using drf-spectacular to django But I get this error : File "/usr/local/lib/python3.11/site-packages/drf_spectacular/openapi.py", line 515, in _resolve_path_parameters schema = self._map_model_field(model_field, direction=None) File "/usr/local/lib/python3.11/site-packages/drf_spectacular/openapi.py", line 565, in _map_model_field assert isinstance(model_field, models.Field) AssertionError REST_FRAMEWORK = { "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema", } versions: python = "^3.11" django = "^5.0.0" pillow = "^10.1.0" djangorestframework = "^3.14.0" djangorestframework-simplejwt = "^5.3.1" celery = "^5.3.6" flower = "^2.0.1" mysqlclient = "^2.2.1" django-filter = "^23.5.0" pycryptodome = "^3.19.0" gunicorn = "^21.2.0" whitenoise = "6.6.0" django-cors-headers = "^4.3.1" drf-spectacular = "^0.27.0" -
In Celery, how to use autoretry and run some code after the last retry?
In Celery, I want to take advantage of autoretry_for and retry_backoff arguments. But I also want to report the exceptions manually to Sentry, to add a scope with the level of the error. I know I can add the scope with something like this: except Exception as e: try: raise self.retry(exc=e) except MaxRetriesExceededError: with sentry_sdk.push_scope() as scope: scope.level = 'critical' sentry_sdk.capture_exception(e) But if I do that, the exponential backoff does not work. Is there any other way to add the scope of the error without having to implement the backoff by myself? -
django.core.exceptions.FieldError: Cannot resolve keyword 'transactions' into field. Choices are: amount, created_at, id, received_transfers, sent_
class Transaction(models.Model): CHARGE = 1 PURCHASE = 2 TRANSFER_RECEIVED = 3 TRANSFER_SENT = 4 TRANSACTION_TYPES_CHOICES = ( (CHARGE, 'Charge'), (PURCHASE, 'Purchase'), (TRANSFER_SENT, 'Transfer sent'), (TRANSFER_RECEIVED, 'Transfer received'), ) user = models.ForeignKey(User, related_name='transactions', on_delete=models.RESTRICT) transaction_type = models.PositiveSmallIntegerField(choices=TRANSACTION_TYPES_CHOICES, default=CHARGE) amount = models.BigIntegerField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.user}: {self.get_transaction_type_display()} -> {self.amount} Rial' @classmethod def get_report(cls): positive_transactions = Sum('transactions__amount', filter=Q(transactions__transaction_type__in=[cls.CHARGE, cls.TRANSFER_RECEIVED])) negative_transactions = Sum('transactions__amount', filter=Q(transactions__transaction_type__in=[cls.PURCHASE, cls.TRANSFER_SENT])) users = User.objects.all().annotate( transactions_count=Count('transactions__id'), balance=Coalesce(positive_transactions, 0) - Coalesce(negative_transactions, 0) ) return users @classmethod def get_total_balance(cls, user): query_set = cls.get_report() return query_set.aggregate(Sum('balance')) @classmethod def user_balance(cls, user): positive_transactions = Sum('amount', filter=Q( transactions__transaction_type__in=[cls.CHARGE, cls.TRANSFER_RECEIVED])) negative_transactions = Sum('amount', filter=Q( transactions__transaction_type__in=[cls.PURCHASE, cls.TRANSFER_SENT])) user_balance = user.transactions.all().aggregate( balance=Coalesce(positive_transactions, 0) - Coalesce(negative_transactions, 0)) return user_balance.get('balance', 0) class UserBalance(models.Model): user = models.ForeignKey(User, related_name='balance_records', on_delete=models.RESTRICT) balance = models.BigIntegerField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.user}: {self.balance} - {self.created_at}' @classmethod def record_user_balance(cls, user): user_balance = Transaction.user_balance(user) instance = cls.objects.create(user=user, balance=user_balance) return instance @classmethod def record_all_users_balance(cls): for user in User.objects.all(): cls.record_user_balance(user) when i run UserBalance.record_all_users_balance() in console i get this error: >>>UserBalance.record_all_users_balance() Traceback (most recent call last): File "*\plugins\python\helpers\pydev\pydevconsole.py", line 364, in runcode coro = func() File "<input>", line 1, in <module> File "*\Python\PythonWebProjects\djangoProject01\transaction\models.py", line 76, in record_all_users_balance cls.record_user_balance(user) File "*\Python\PythonWebProjects\djangoProject01\transaction\models.py", line 68, in record_user_balance user_balance = Transaction.user_balance(user) … -
link to a different admin object in an admin template
I don't want to get my hands dirty with js. I have two models, car and model. How can I manually add a link from a car to it's model in a custom admin template? I can do: <a href="{% url 'admin:appname_carmodels_changelist' %}">access changelist</a> But how would I access the model with pk=42? I tried: <a href="{% url 'admin:appname_carmodels_change' 42 %}">access changeform</a> But I end up with a NoReverseMatch at /admin/appname/carmodel/.../change/. Is this possible? Or do I have to use some extra_context that can carry the reverse function? -
nothing gets logged at logging for a 500 error (Django)
I have copied pasted this at the settings.py (but done nothing else) I am in production and debug is set to False because I have read that his how you have to do it I have placed the log file in a place where the owner of the application can write, yet nothing is written. The error comes after I try to save a form. The form has 3 tables, address, property and pictures. address and property are saved perfectly, pictures saves nothing. The app works in my local computer perfectly. Without any reason, it fails here in production. I copy pasted this but it doesn't save anything to the file LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { # Include the default Django email handler for errors # This is what you'd get without configuring logging at all. 'mail_admins': { 'class': 'django.utils.log.AdminEmailHandler', 'level': 'ERROR', # But the emails are plain text by default - HTML is nicer 'include_html': True, }, # Log to a text file that can be rotated by logrotate 'logfile': { 'class': 'logging.handlers.WatchedFileHandler', 'filename': '/home/bills/alvar/myapp/dapp.log' }, }, 'loggers': { # Again, default Django configuration to email unhandled exceptions 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': … -
How can i connect my django uploads to the firebase storage?
this is my first time using firebase storage for file upload. I don't know if this is the way to structure and do it but. currently I have my product models and other related models to product as given below: #product/models.py import os from django.db import models from dripshop_apps.core.abstract_models import AbstractItem from dripshop_apps.category.models import Category from dripshop_apps.brand.models import Brand from django.contrib.contenttypes.fields import GenericRelation from django.utils import timezone from django.dispatch import receiver from django.db.models.signals import pre_save, pre_delete from dripshop_apps.core.receivers import slugify_pre_save, publish_state_pre_save, update_featured_on_publish, update_visibility_on_publish from .tasks import upload_to_firebase from .utils import product_thumbnail_upload_path, product_image_upload_path, sanitize_for_directory_name class Product(AbstractItem): price = models.DecimalField(max_digits=10, decimal_places=2) category = models.ForeignKey(Category, on_delete=models.SET_NULL,related_name='product_category', null=True, blank=True) brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, related_name='product_brand', null=True, blank=True) thumbnail = models.ImageField(upload_to=product_thumbnail_upload_path, blank=True, null=True, max_length=255) visible = models.BooleanField(default=True, editable=False) stock = models.PositiveIntegerField(default=0) objects=ProductManager() class Meta: verbose_name = "Product" verbose_name_plural = "Products" def __str__(self): return self.title class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField(upload_to=product_image_upload_path, blank=True, null=True, max_length=255) updated = models.DateTimeField(auto_now=True) pre_save.connect(publish_state_pre_save, sender=Product) pre_save.connect(slugify_pre_save, sender=Product) pre_save.connect(update_featured_on_publish, sender=Product) and I am using the functions product_thumbnail_upload_path and product_image_upload_path to upload the image to the desired directory structure to the firebase with the use of a celery task which is also given below it #product/utils.py import os from django.utils import timezone … -
ValueError: Expected n_neighbors <= n_samples (mismatch between the number of neighbors specified and the number of samples in the data)
I want to implement multi-view spectral clustering. The supervised_multi_view_spectral_clustering function takes multiple views of feature matrices (X_views), a target variable (y), and clustering parameters, and performs spectral clustering on the concatenated features. The second function finds the optimal number of clusters based on silhouette scores when given a list of mixed representations. The final part of the code uses these functions to determine the optimal number of clusters and performs multi-view spectral clustering on the provided data (mixed_representation_all). By design, the input latent_representations_train_nmf is a dictionary of numpy array, whereas y is a multi-variate dataframe. The error indicates that there is a mismatch between the number of neighbors specified and the number of samples in the data. This is despite ensuring that n_neighbors is always less than or equal to the number of samples. Code: from sklearn.preprocessing import LabelEncoder from sklearn.cluster import SpectralClustering from sklearn.metrics import accuracy_score def supervised_multi_view_spectral_clustering(X_views, y, n_clusters, affinity='nearest_neighbors', max_neighbors=10): # Check if y is already encoded if isinstance(y.iloc[0, 0], str): # Assuming the first element of the dataframe is a string if not encoded # Encode labels if they are not numerical label_encoder = LabelEncoder() y_encoded = label_encoder.fit_transform(y) else: # Use the provided encoded y directly … -
Django - Oracle Cloud Bucket integration with django-storages
I have configured the django-storages to point to OCI bucket. Below is the configuration: AWS_S3_ACCESS_KEY_ID = env('AWS_BUCKET_KEY') AWS_SECRET_ACCESS_KEY = env('AWS_BUCKET_SECRET') AWS_BUCKET_NAMESPACE = env('AWS_BUCKET_NAMESPACE') AWS_STORAGE_BUCKET_NAME = env('AWS_BUCKET_NAME') AWS_S3_BUCKET_REGION = env('AWS_S3_BUCKET_REGION') AWS_S3_ENDPOINT_URL = f'https://{AWS_BUCKET_NAMESPACE}.compat.objectstorage. {AWS_S3_BUCKET_REGION}.oraclecloud.com' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = f'{AWS_S3_ENDPOINT_URL}/{AWS_STORAGE_BUCKET_NAME}' AWS_DEFAULT_ACL = 'public-read' STATICFILES_STORAGE = 'custom_storages.StaticStorage' DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' # Use AWS_S3_ENDPOINT_URL here if you haven't enabled the CDN and got a custom domain. STATIC_URL = '{}/{}/'.format(AWS_LOCATION, 'static') STATIC_ROOT = 'var/static/' STATICFILES_DIRS = [ BASE_DIR / "static" ] MEDIA_URL = '{}/{}/'.format(AWS_LOCATION, 'media') MEDIA_ROOT = 'media/' and this is the custom storage config from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class StaticStorage(S3Boto3Storage): bucket_name = settings.AWS_STORAGE_BUCKET_NAME location = 'static' class MediaStorage(S3Boto3Storage): bucket_name = settings.AWS_STORAGE_BUCKET_NAME location = 'media' All my static files are being served and no issues, but the application doesn't recognize the style files at all. Also when I try to upload a new file, it gives the following error: botocore.exceptions.ClientError: An error occurred (SignatureDoesNotMatch) when calling the PutObject operation: The secret key required to complete authentication could not be found. The region must be specified if this is not the home region for the tenancy. What could be the issue?