Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Why when i use 0 as parameter is not found, but is completely fine when the parameter is 1, 2, 3, ... in Django-Redirect
articles = { 'sports': 'Sports news', 'music': 'Music news', 'travel': 'Travel news', 'tech': 'Tech news', } def num_page_view(request, num_page): topic_list = list(articles.keys()) print(topic_list) topic = topic_list[num_page] return HttpResponseRedirect(topic) I'm currently learning dynamic url. Here's when i use /0 it is shown not found Error input 0 But, when i use /1 it's completely fine, it redirected into "music" page. Please Help! I tried print the topic_list, and it is shown like this: ['sports', 'music', 'travel', 'tech'] when i print topic_list[0] it is shown as "sport" but i dont know, i cant do redirect. -
Django can't connect to Postgresql
I'm working on my first ever Django project. I've Create a Postgresql Database on a host(which my project is already on that host) which is accessible on public network too .I can connect to the database on my local computer so the database is created. But in production I'm trying to migrate to the database but I got the FATAL: database "postgre" does no t exist I tried to connect it on my local with public network host and port but still got the same error. here is my db code : DATABASES = { 'default': { 'ENGINE': config('ENGINGE', default='django.db.backends.postgresql'), 'NAME': config('NAME', default='postgre'), 'USER': config('USER', default='postgre'), 'PASSWORD': config('PASSWORD', default='postgre'), 'HOST': config('HOST', default='postgre'), 'PORT': config('PORT', default='5432'), } } I'm passing the variables with .env. Also I tried to connect with dj-database-url like this : DATABASES = DATABASES['default'] = dj_database_url.config('DATABASE_URL') And in both cases I've got the same error. Does anyone got any idea what's wrong here? -
How to resolve error: collectstatic - Could not find backend 'storages.custom_azure.AzureStaticStorage'
I have a django app and I have installed the module: django-storages[azure] with the command: pipenv install django-storages[azure] And now I try to run the collectstatic command. But if I enter the command: python manage.py collectstatic I get this error: Could not find backend 'storages.custom_azure.AzureStaticStorage': No module named 'storages.custom_azure' So my pipfile looks: [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] django = "*" django-storages = {extras = ["azure"], version = "*"} [dev-packages] [requires] python_version = "3.10" settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "uploader", "storages" ] STATIC_URL = '/static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' DEFAULT_FILE_STORAGE = 'uploader.custom_azure.AzureMediaStorage' STATICFILES_STORAGE = 'storages.custom_azure.AzureStaticStorage' STATIC_LOCATION = "static" MEDIA_LOCATION = "media" AZURE_ACCOUNT_NAME = "name" AZURE_CUSTOM_DOMAIN = f'{AZURE_ACCOUNT_NAME}.blob.core.windows.net' STATIC_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{STATIC_LOCATION}/' MEDIA_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{MEDIA_LOCATION}/' and I have a file custom.azure.py in the app uploader: from storages.backends.azure_storage import AzureStorage class AzureMediaStorage(AzureStorage): account_name = ''name' # Must be replaced by your <storage_account_key> account_key= 'key' azure_container = 'media' expiration_secs = None class AzureStaticStorage(AzureStorage): account_name = 'name' account_key = 'key' azure_container = 'static' expiration_secs = None Question: how to resolve the error: Could not find backend 'storages.custom_azure.AzureStaticStorage': No module named 'storages.custom_azure' -
How to add django-filter Rangefilter class?
I am try to add bootstrap class in to price range filter but i can't, import django_filters from panel.models import Product, Category,Size,TopNote, BaseNote, MidNote from django import forms class ProductFilter(django_filters.FilterSet): price = django_filters.RangeFilter( # widget = forms.TextInput(attrs={'class':'form-control'}) ) class Meta: model = Product fields =['name', 'category_id', 'price', 'top_notes', 'base_notes', 'category_id', 'size'] when I am add class using widget = forms.TextInput(attrs={'class':'form-control'}) range filter convert into 1 textbox i dont't know why ???/ -
How to properly aggregate Decimal values in a django app: 'decimal.Decimal' object has no attribute 'aggregate'
I'm in a django-tables2 Table, trying to compute the sum of a column (based on a MoneyField (django-money) in the model, see hereunder): import django_tables2 as table class PriceAmountCol(table.Column): # print(f"Total price is: {record.price.amount}") # print(f"Type of total price is: {type(record.price.amount)}") def render(self, value, bound_column, record): total_price = record.price.amount.aggregate( total=Sum("price") ) Class MyTable(table.Table): # Fields price = PriceAmountCol( verbose_name=_("Price [EUR]"), ) #... But this error is raised: File "/code/djapp/apps/myapp/tables.py", line 192, in render total_price = record.price.amount.aggregate( AttributeError: 'decimal.Decimal' object has no attribute 'aggregate' If not commented out, the two print instructions give: Total price is: 112.80 Type of total price is: <class 'decimal.Decimal'> How could I properly aggregate price values (Decimal) in my current table column? The field in the model is as follow: price = MoneyField( default=0.0, decimal_places=2, max_digits=12, default_currency="EUR", verbose_name=_("Price [EUR]"), ) Version info django 4.2.8 djmoney 3.4.1 django-tables2 2.7.0 python 3.10.6 Related information https://django-tables2.readthedocs.io/en/latest/pages/column-headers-and-footers.html#adding-column-footers Django-tables2 column total Django-tables2 footer sum of computed column values -
taking picture from the django admin panel to a website with zip
There will be a field in the Django admin panel, I will select zip from this field. there will be about 60 to 70 images in the zip file. I want to be able to display these images as slides on my website, but I haven't found a solution. I've tried multiple solutions, but none of them have been successful, so I can't share the codes. -
Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/login/login/
I stored the user registration details in the database, but when I attempt to log in with the entered data, it is not working; instead, it displays the following message. enter image description here here is urls.py urlpatterns=[ path('',views.index,name='index'), #path('counter',views.counter,name='counter'), path('register/',views.register,name='register'), path('login/',views.login,name='login.html'), path('logout/',views.logout,name='logout.html'), path('post/<str:pk>',views.post,name='post.html') #path('',views.display_records,name='table.html'), ] here is views.py def login(request): if request.method=='POST': username=request.POST['username'] password=request.POST['password'] user=auth.authenticate(username=username,password=password) if user is not None: auth.login(request,user) return redirect('/') else: messages.info(request,'Invalid User Login') return redirect('login') else: return render(request,'login.html') here is login.html <h1>Login Now</h1> <style> h3{ color: red; } </style> {% for message in messages %} <h3>{{message}}</h3> {% endfor %} <form action="login/" method='POST'> {% csrf_token %} <p>Username</p> <input type="text" name="username" placeholder="username"/> <p>Password</p> <input type="password" name="password" placeholder="password"/> <br> <br> <input type="submit"/> </form> After completion of registration.it is not redirecting to login page instead showing this. type here enter image description here