Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change DateField Input format on django admin edit page
I have a Django project where users can submit requests and then our admin's can view these requests through Django's admin page. I'd like the TimeField on the change page to be in a different format when one our our admins selects an object to change. The image below show what a list of objects looks like through the list display page. The Start time is in a 12 hour format using AM/PM. Once the user clicks an object to change though the form expects the the Start Time to be in 24 hour format as shown below. I'd like to change the admin form to match the list display format if possible. If I need to provide any other information or code example please let me know. Thank you. -
Get Error "not enough values to unpack (expected 2, got 0)" when using Django EAV 2
from django.contrib import admin from .models import Product from eav.forms import BaseDynamicEntityForm from eav.admin import BaseEntityAdmin Register your models here. class ProductAdminForm(BaseDynamicEntityForm): model = Product class ProductAdmin(BaseEntityAdmin): form = ProductAdminForm admin.site.register(Product, ProductAdmin) Get error: Request Method: GET Request URL: http: //127.0.0.1:8000/admin/shop/product/add/ Django Version: 5.1.1 Exception Type: ValueError Exception Value: not enough values to unpack (expected 2, got 0) Exception Location: C:\Users\iskander\Desktop\shop\venv\Lib\site-packages\django\forms\widgets.py, line 772, in _choice_has_empty_value Raised during: django.contrib.admin.options.add_view Error during template rendering In template C:\Users\iskander\Desktop\shop\venv\Lib\site-packages\django\contrib\admin\templates\admin\includes\fieldset.html, error at line 25 <div> 16 {% if not line.fields|length == 1 and not field.is_readonly %}{{ field.errors }}{% endif %} 17 <div class="flex-container{% if not line.fields|length == 1 %} fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}{% endif %}{% if field.is_checkbox %} checkbox-row{% endif %}"> 18 {% if field.is_checkbox %} 19 {{ field.field }}{{ field.label_tag }} 20 {% else %} 21 {{ field.label_tag }} 22 {% if field.is_readonly %} 23 <div class="readonly">{{ field.contents }}</div> 24 {% else %} **25 {{ field.field }}** 26 {% endif %} 27 {% endif %} 28 </div> 29 {% if field.field.help_text %} 30 <div class="help"{% if field.field.id_for_label %} id="{{ field.field.id_for_label }}_helptext"{% endif %}> 31 … -
Sort version number of format 1.1.1 in Django
I have a Django model with a release_version char field that stores version information in the format 1.1.1 (e.g., 1.2.3). I need to sort a queryset based on this version field so that versions are ordered correctly according to their major, minor, and patch numbers. class Release(BaseModel): file_name = models.CharField(max_length=255) release_version = models.CharField(max_length=16) Using the default order_by gives the result in lexicographic order and it sorts 1.10.0 before 1.2.0 when sorting ascending. The solution seems to be that I can annotate the major, minor and patch version and then sort based on these three fields. The issue in this is that I am not able to figure out how to separate this version into major, minor and patch numbers. -
Is it possible to pause celery tasks during execution
I have an app that does transcription. I want that if the user tries to reload they are alerted that reloading will stop their task from completing. I tried to use it with unload but it didn't work most of the time and I know that it is inconsistent. I would like to pause the task if the user tries to reload. They will get the browser warning alert and if they decide that they still want to reload the task will be terminated. The idea I have is to trigger a beforeunload which will give them a warning and trigger the pausing of the celery task. I have a polling function on the frontend set up using JS that polls if the task is still running every 5 seconds. If the user reloads this polling function will stop running and so the backend will stop being polled which will trigger the celery task termination. Otherwise, the function will receive the poll if the user cancels or hasn't reloaded and the task is unpaused. Here is my polling function: function pollTaskStatus(taskId) { currentTaskId = taskId; console.log(currentTaskId) pollInterval = setInterval(() => { const xhr = new XMLHttpRequest(); xhr.onload = function() { … -
Djnago coroutine to query data from DB in batches and yield as an iterable
I am using Django 4.2 with python3.8. I have a Mysql8 DB containing a Model as class A(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=522) class B(models.Model): name = models.CharField(max_length=255, unique=True) a = models.ManyToManyField(A) i want to create a function which when provided id for A should be able to query all instances of B for A but because B can be very large like millions of rows. want to iterate over it in batches of 1000 without loading it in memory. Is it possible to do so? I wanted to use co-routines as i think i can use it to build a iterator like object. any other alternatives to make sure it is performant enough so i can parallelize it over for 100+ organizations. i would like a code snippets if possible so i can understand this better context: This is a management command that needs to be run as cronjob everyday so i need to run fast -
Can't make dynamic page changes
I want to make a dynamic page, but when I make a request the page just refreshes, although it should return an alert when no data is entered (I have not entered any). views.py def adding(request): return render(request, 'matrix_app/adding_matrix.html') create_matrix.js function create_matrix(){ let rows1 = document.getElementById("rows_1_matrix").textContent; let columns1 = document.getElementById("columns_1_matrix").textContent; let rows2 = document.getElementById("rows_2_matrix").textContent; let columns2 = document.getElementById("columns_2_matrix").textContent; nums = [rows1, rows2, columns1, columns2]; for(let i = 0; i < 4; i++){ if (nums[i] === false || nums[i] === '0') { return alert("All fields are ruqired"); } } } adding_matrix.html % extends 'base.html' %} {% load static %} {% block content %} <script src="{% static 'js/create_matrix.js' %}"></script> <form onsubmit="create_matrix()" id="matrix" method="post"> {% csrf_token %} <div> <label>text</label> <input type="number" id="rows_1_matrix"/> </div> <div> <label>text</label> <input type="number" id="columns_1_matrix"/> </div> <div> <label>text</label> <input type="number" id="rows_2_matrix" /> </div> <div> <label>text</label> <input type="number" id="columns_2_matrix"/> </div> <input type="submit" value="generate"/> </form> <a href="/operations"><button>Back</button></a> {% endblock %} -
Django + Nginx + Gunicorn : Problem to load statics files
I am running a Django application on a Linux server with NGINX. I am having issues accessing the index.html to load static files such as CSS and JavaScript. Paths: Project path: /opt/proj/proj Static folder path: /opt/proj/proj/static Static files path: /opt/proj/staticfiles WSGI path: /opt/proj/proj/config wsgi HTML templates path: /opt/proj/proj/login/templates Settings.py: BASE_DIR: /opt/proj/proj STATIC_ROOT: /opt/proj/staticfiles STATICFILES_DIRS: ['/opt/proj/proj/static'] ls -la: drwxrwxr-x 6 appusr root 4096 Sep 10 11:00 . drwxrwxr-x 3 appusr appusr 4096 Sep 9 22:44 .. drwxrwxr-x 2 appusr root 4096 Sep 10 08:53 bin drwxrwxr-x 3 appusr root 4096 Sep 9 22:44 lib drwx------ 6 appusr appusr 4096 Sep 10 11:04 proj -rwxrwxr-x 1 appusr root 203 Sep 10 08:53 pyvenv.cfg drwxr-xr-x 6 www-data www-data 4096 Sep 10 11:00 staticfiles NGINX Configuration: server { listen 80; server_name pense.ai; access_log /var/log/nginx/proj.log; location /static/ { alias /opt/proj/staticfiles/; } location / { proxy_pass http://181.177.55.120:8000; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALLDSP COR PSAa PSDa OURNOR ONL UNI COM NAV"'; } } Console Error: WARNING 2024-09-10 13:29:08,648 log Not Found: /static/css/login-btn-voltar.css Not Found: /static/css/login-style.css WARNING 2024-09-10 13:29:08,653 log Not Found: /static/css/login-style.css Not Found: /static/js/login.js WARNING 2024-09-10 13:29:08,665 log Not Found: /static/js/login.js I have literally tried everything. I am almost considering removing the … -
Acces to django context to html js
I'm trying to access to my django context from my views.py to my index.html page but something wrong and I need help. My context from django called in my html template is working fine with: {% for i in links %} <li><a>{{i.id}}; {{i.sequence}}; {{i.category}};{{i.link}}; {{i.description}}; {{i.image}}</a></li> {% endfor %} out of that give me: 2; 0; OUTILS DU QUOTIDIEN - DIVERS;https://safran.fabriq.tech/login; La solution tout-en-un pour le QRQC Digitalisé ! Détectez, escaladez, résolvez vos problèmes plus rapidement et améliorez votre performance.; Logos/Fabriq_0ER4lsy.png 3; 0; OUTILS DU QUOTIDIEN - DIVERS;https://improve.idhall.com/; Improve est la plateforme collaborative de Safran pour piloter toutes les initiatives de progrès du Groupe (de l'idée au projet d'amélioration).; Logos/Improve_lFlB5pY.png 4; 0; OUTILS DU QUOTIDIEN - DIVERS;https://portal.bi.group.safran/reports/powerbi/REPORTS/Safran%20Aircraft%20Engines/Develop/Innovation-Participative-SAE/IP-FULL-SAE?rs:Embed=true; PowerBI IP Safran Aircraft Engines.; Logos/Gestor_gVEU0RR.png but in my js: <script> var linksData = '{{links}}'; for(let j=0;j< linksData.length;j++) { document.writeln('<p class="card-text">"'+String(linksData[j].category)+'"</p>'); } </script> give me : "undefined" "undefined" "undefined" "undefined" "undefined" "undefined" "undefined" "undefined" "undefined" "undefined" "undefined" "undefined" "undefined" ... My attempt was also with var linksData = JSON.parse('{{links|escapejs}}'); but still not working and return nothing, could you help me please? Thanks a lot Philippe -
NotImplementedError: subclasses of BaseDatabaseIntrospection may require a get_sequences() method
I have recently upgraded the social-auth-app-django library version from 5.0.0 to 5.4.1. I am adding the versions of few of the other libraries used: Django==4.2.15 django-tenant-schemas==1.12.0 django-restql==0.15.4 djangorestframework==3.15.2 social-auth-app-django==5.4.1 I keep getting the below error after this upgrade, adding the stack trace below: Applying social_django.0011_alter_id_fields... Traceback (most recent call last): File "/home/circleci/.pyenv/versions/3.11.9/lib/python3.11/site-packages/django/db/models/query.py", line 916, in get_or_create return self.get(**kwargs), False ^^^^^^^^^^^^^^^^^^ File "/home/circleci/.pyenv/versions/3.11.9/lib/python3.11/site-packages/django/db/models/query.py", line 637, in get raise self.model.DoesNotExist( core.models.LoyaltyTenant.DoesNotExist: LoyaltyTenant matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/circleci/bolapi-build/manage.py", line 35, in <module> main() File "/home/circleci/bolapi-build/manage.py", line 31, in main execute_from_command_line(sys.argv) File "/home/circleci/.pyenv/versions/3.11.9/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/circleci/.pyenv/versions/3.11.9/lib/python3.11/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/circleci/.pyenv/versions/3.11.9/lib/python3.11/site-packages/django/core/management/commands/test.py", line 24, in run_from_argv super().run_from_argv(argv) File "/home/circleci/.pyenv/versions/3.11.9/lib/python3.11/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/home/circleci/.pyenv/versions/3.11.9/lib/python3.11/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/circleci/.pyenv/versions/3.11.9/lib/python3.11/site-packages/django/core/management/commands/test.py", line 68, in handle failures = test_runner.run_tests(test_labels) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/circleci/.pyenv/versions/3.11.9/lib/python3.11/site-packages/django/test/runner.py", line 1054, in run_tests old_config = self.setup_databases( ^^^^^^^^^^^^^^^^^^^^^ File "/home/circleci/bolapi-build/core/test_runner.py", line 58, in setup_databases tenant, _ = get_tenant_model().objects.get_or_create( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/circleci/.pyenv/versions/3.11.9/lib/python3.11/site-packages/django/db/models/manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/circleci/.pyenv/versions/3.11.9/lib/python3.11/site-packages/django/db/models/query.py", line 923, in get_or_create return self.create(**params), True ^^^^^^^^^^^^^^^^^^^^^ File "/home/circleci/.pyenv/versions/3.11.9/lib/python3.11/site-packages/django/db/models/query.py", line 658, in … -
How to filter the one-to-many relationship from both side
I have two tables which has relationship. class Parent(SafeDeleteModel): name = models.CharField(max_length=1048,null=True,blank=True) class Child(SafeDeleteModel): name = models.CharField(max_length=1048,null=True,blank=True) parent = models.ForeignKey(Project,blank=True, null=True, on_delete=models.CASCADE,related_name="parent_project") In this case I can filter the Child by Parent such as Child.objects.filter(parent__name="test") However I want to do the reverse like this below. Parent.objects.filter(child__name="test") Is it possible? -
Django PayPal webhooks verification testing
I want to create my own realization of paypalrestsdk.WebhookEvent.verify that I'm using right now, so I want to create test, that uses request from PayPal webhook that my app already handled, for verification tests. My question is - Is it possible to verify webhook that is already verified (so basically I just provide already verified request to paypalrestsdk.WebhookEvent.verify). I created test that uses data that was used for real webhook verification for paypalrestsdk.WebhookEvent.verify. Symbol "*" is used for confidential info. class MockRequest: def __init__(self, meta, body): self.META = meta self.body = body class TestVerifyEvent(unittest.TestCase): def setUp(self): self.body = {"id":"*","event_version":"1.0","create_time":"*","resource_type":"sale","event_type":"PAYMENT.SALE.COMPLETED","summary":"Payment completed for $ 10.0 USD","resource":{"billing_agreement_id":"I-2CSK9W3P6C29","amount":{"total":"10.00","currency":"USD","details":{"subtotal":"10.00"}},"payment_mode":"INSTANT_TRANSFER","update_time":"*","create_time":"*","protection_eligibility_type":"ITEM_NOT_RECEIVED_ELIGIBLE,UNAUTHORIZED_PAYMENT_ELIGIBLE","transaction_fee":{"currency":"USD","value":"0.84"},"protection_eligibility":"ELIGIBLE","links":[{"method":"GET","rel":"self","href":"https://api.sandbox.paypal.com/v1/payments/sale/*"},{"method":"POST","rel":"refund","href":"https://api.sandbox.paypal.com/v1/payments/sale/*/refund"}],"id":"1TV06398E1048801N","state":"completed","invoice_number":""},"links":[{"href":"https://api.sandbox.paypal.com/v1/notifications/webhooks-events/*","rel":"self","method":"GET"},{"href":"https://api.sandbox.paypal.com/v1/notifications/webhooks-events/*/resend","rel":"resend","method":"POST"}]} self.META = { 'HTTP_PAYPAL_TRANSMISSION_ID': 'verified transmission id', 'HTTP_PAYPAL_TRANSMISSION_TIME': 'verified transmission time', 'HTTP_PAYPAL_CERT_URL': 'https://api.sandbox.paypal.com/v1/notifications/certs/*', 'HTTP_PAYPAL_TRANSMISSION_SIG': 'verified transmission signature', 'HTTP_PAYPAL_AUTH_ALGO': 'SHA256withRSA' } self.mock_request = MockRequest(self.META, str(self.body).encode('utf-8')) def test_verify_event(self): result = verify_event(self.mock_request) self.assertTrue(result) if __name__ == '__main__': unittest.main() And that is my code that gets info from request and uses paypalrestsdk.WebhookEvent.verify for verification. It's working on deployment server, but in my test it always returns False. I have several ideas why it is like that: 1. It's because I test it on localhost 2. Maybe webhook can be verified only once or something like that 3. My test work's … -
How to specify a default based on the request for a field in the create form of a TabularInline
I have a model which has a language_code field: class SkillSynonym(StandardModel): """SkillSynonym class""" skill = models.ForeignKey( Skill, on_delete=models.CASCADE, related_name="synonyms" ) name = models.CharField(max_length=200) language_code = models.CharField( db_index=True, max_length=8, verbose_name="Language", choices=settings.LANGUAGES, default=settings.LANGUAGE_CODE, ) class Meta: unique_together = ("name", "language_code") def __str__(self) -> str: """SkillSynonym object representation.""" return f"{self.name}" This is then edited through a TabularInline admin inside the SkillAdmin: class SkillSynonymInline(admin.TabularInline): model = SkillSynonym extra = 0 def get_queryset(self, request: HttpRequest): queryset = super().get_queryset(request) language_code = request.GET.get("language", "en") if language_code: queryset = queryset.filter(language_code=language_code) return queryset As you can see I am already filtering the records to be shown in the inline field by the language GET parameter. This is set by the parler extension in the parent admin. I would also like to set a default value for language_code in the create form for the TabularInline I've tried overriding get_formset, but I'm not sure what to do with it. -
How to remove the accessibility item from the userbar
Is there a way to remove the accessibility item from the Wagtail userbar? -
Customization of trix-editor in Django project
I just want to understand how exactly I can customize the django-trix-editor to my needs. For example, remove unnecessary buttons, change the size of editor, change the language to RU, etc. I've never worked with editors before and I don't understand a lot of things. At the momemnt I just implemented the editor in my project, it works with all its functions. I found the documentation in the repository that described how to implement the editor in Django. That's what I did. There is also another official repository of this editor, but it describes its work with JS, as I understand it. https://github.com/adilkhash/django-trix-editor https://github.com/basecamp/trix -
Django database migrate
It uses my own user and permissions model in Django, but the database consists of Django's own models. I use my own authorization model in Django, but when I migrate, auth_permissions occur in the database. Can I prevent this? What can I do to prevent it from occurring? class Permission(models.Model): add_product = models.BooleanField(default=False) add_category = models.BooleanField(default=False) -
Django Error: 'class Meta' got invalid attribute(s): index_together
I am working on a Django project and encountered an issue when running the python manage.py migrate command. The migration process fails with the following error: Traceback (most recent call last): File "C:\Users\dell\Desktop\Django Project GMP\GMB-Django\gmb_project\manage.py", line 22, in <module> main() File "C:\Users\dell\Desktop\Django Project GMP\GMB-Django\gmb_project\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\dell\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\dell\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\dell\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\dell\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 459, in execute output = self.handle(*args, **options) File "C:\Users\dell\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 107, in wrapper res = handle_func(*args, **kwargs) File "C:\Users\dell\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\commands\migrate.py", line 303, in handle pre_migrate_apps = pre_migrate_state.apps File "C:\Users\dell\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\utils\functional.py", line 47, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\dell\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\migrations\state.py", line 565, in apps return StateApps(self.real_apps, self.models) File "C:\Users\dell\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\migrations\state.py", line 626, in __init__ self.render_multiple([*models.values(), *self.real_models]) File "C:\Users\dell\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\migrations\state.py", line 664, in render_multiple model.render(self) File "C:\Users\dell\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\migrations\state.py", line 957, in render return type(self.name, bases, body) File "C:\Users\dell\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\models\base.py", line 143, in __new__ new_class.add_to_class("_meta", Options(meta, app_label)) File "C:\Users\dell\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\models\base.py", line 371, in add_to_class value.contribute_to_class(cls, name) File "C:\Users\dell\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\models\options.py", line 220, in contribute_to_class raise TypeError( TypeError: 'class Meta' got invalid attribute(s): index_together How can I resolve this error, and what changes do I need to make to migrate successfully? How can I resolve this error, … -
Django CMS with Vite bundler instead of Webpack
I am the maintainer of a Django (with Django CMS) project, and I use Webpack to bundle all static files and templates into a dist folder. I am trying to migrate to Vite, as I read that it offers better performance than Webpack and requires fewer components to work. this is my webpack.conf.js file: const path = require('path'); const chalk = require('chalk'); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const glob = require("glob"); const HtmlWebpackPlugin = require('html-webpack-plugin'); const webpack = require('webpack'); const pkg = require('./package.json'); const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin'); const TerserPlugin = require("terser-webpack-plugin"); const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; const { defaultMinimizerOptions } = require("html-loader"); // Ignore node modules and all js files in root project const excludedBase = ['node_modules/**', '*.js', 'dist/**']; // exclude node_modules, js into the root of prj, dist folder // Ignored django apps const excludedApps = [ '**/admin/**', 'our_content/**', 'our_cms_plugins/base_cms_plugin/**', 'our_composer/templates/our_composer/**', '**/default_style.html', // managed from html-webpack-plugins 'themes/static/themes/js/main.js', // must be the first file 'themes/static/themes/js/components/**', // only imported components should be included in bundle 'themes/static/themes/css/compiled/**', // manual import for PDF ]; const excludedPaths = excludedBase.concat(excludedApps); const ENV_CONF = { PRODUCTION: 'production', DEV: 'development' }; let loadEntries = (env, argv) => { let formattedPaths = ['./themes/static/themes/js/main.js']; let … -
Having problems connecting a local Django project to a Cloud SQL database instance
I have a Cloud SQL database running on MySQL 8.0.31. Now, I have a Django 5.1 project that I want to connect the database with (with root permissions). However, whenever I run any python manage.py <django-script-here> (inspectdb, runserver, showmigrations, etc.) command, it results in an error saying django.db.utils.OperationalError: (2013, 'Lost connection to server during query') I'm pretty sure its a Django issue because I can connect to the database through MySQLWorkbench 8.0.22, and I can connect to it locally by using the mysql.connector library. So, I thought it was version problems but I checked the package versions within my virtual environment and they are all compatible with official documentation to back it up (i.e MySQL 8.0.31 works with Django 5.1). -
Django REST API view post serializer.save sets one parameter 'null'
In Django, I have the following model: class business(models.Model): business_category = models.ForeignKey(businessCategory, related_name='businesss', on_delete=models.CASCADE) partner1 = models.CharField(max_length=255) #, blank=True, null=True) partner1_is_creator = models.BooleanField(default=True) partner2 = models.CharField(max_length=255) creator = models.ForeignKey(User, related_name='businesss', on_delete=models.CASCADE, null=True) name = models.CharField(max_length=255) setting = models.CharField(max_length=255) estimated_budget = models.FloatField() location = models.CharField(max_length=255) date_created = models.DateTimeField(auto_now_add=True) business_start_date = models.DateTimeField(null=True, editable=True, default=django.utils.timezone.now) business_end_date = models.DateTimeField(null=True, editable=True, default=django.utils.timezone.now) This is the related serializer: class BusinessCreator(serializers.ModelSerializer): class Meta: model = business fields = ['business_category', 'name', 'partner1', 'partner2', 'partner1_is_creator', 'business_start_date', 'location', 'setting', 'estimated_budget'] and this is the view: class BusinessList(APIView): @method_decorator(login_required, name='dispatch') def get(self, request): created_user = request.user businesss = Business.objects.filter(creator=created_user) serializer = BusinessSummary(businesss, many=True) return Response(serializer.data) @method_decorator(login_required, name='dispatch') def post(self, request): new_business = request.data.get('business') serialized_business = BusinessCreator(data=new_business) if serialized_business.is_valid(raise_exception=True): print(serialized_business.validated_data) serialized_business.save() return Response(serialized_business.data, status=201) return Response(serialized_business.errors, status=400) The get() method works well. But when I send the following JSON message via a post message, { "business":{ "business_category": 3, "name": "business1", "partner1": "john", "partner2": "smith", "partner1_is_owner": true, "business_start_date": "2024-09-18T08:03:00Z", "location": "CA", "setting": "club", "estimated_budget": 121.0 } } serialized_business.save() sets only partner1 as null. { "business":{ "business_category": 3, "name": "business1", "partner1": null, "partner2": "smith", "partner1_is_owner": true, "business_start_date": "2024-09-18T08:03:00Z", "location": "CA", "setting": "club", "estimated_budget": 121.0 } } As a result, this throws an error. However, … -
Building an AI software related to targeted marketing
I know this is a general question but I an truly lost. To keep it short, I own a startup building a software that will utilize AI to deliver targeted marketing. The main problem is that I cant decide on which database framework to go with. I am leaning towards Django due to cost issues but I have more experience when it comes to MongoDB. I cant decide whether to cut cost and go with Django or blow some of my money on MongoDB I referred a few articles before reaching out here on stack overflow. Most of them talk about the key differences between MongoDb , PostgreSQL and Django. I`m more interested on knowing in terms on scalability and maintainability which would be better. -
Rust vs Django Auth Speed and Security
Goal was to look at Instagram system design. I recently tried doing comparison in rust and django. I know first instinct will be rust gonna be faster, but here are the results. Help me digest these and rust community give your valuable feedback. Django by default uses PBKDF2 to store the password in db and i used djoser for handy routes of API's. Django When you request a JWT token it takes around 150ms. And to refresh the same token it takes 25ms. Rust (Actix-web) When you implement the hashing through Argon salt, it takes 350ms to request a JWT token and to refresh it take 150ms. use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier, Params}; use argon2::password_hash::SaltString; use rand::rngs::OsRng; pub fn hash_password(password: &str) -> Result<String, argon2::password_hash::Error> { // Generate a random salt let salt = SaltString::generate(&mut OsRng); // Aggressively tuned Argon2 parameters for speed let params = Params::new(32768, 1, 4, None).expect("Invalid params"); // 32 MB memory, 1 iteration, 4 parallel threads // Initialize Argon2 hasher with custom parameters let argon2 = Argon2::new(Default::default(), Default::default(), params); // Hash the password let password_hash = argon2.hash_password(password.as_bytes(), &salt)?.to_string(); Ok(password_hash) } pub fn verify_password(password: &str, hash: &str) -> Result<bool, String> { // Parse the password hash from the … -
My Django admin page doesn't utilize the CSS files after installing and configuring whitenoise
My site looks like this right now. My Settings.py looks like this 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', ] STATIC_URL = '/static/' STATICFILES_DIRS = [BASE_DIR / 'static'] STATIC_ROOT = BASE_DIR / "staticfiles" STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" Whitenoise ran fine and copied all the files into staticfiles; however admin page still wont use the styling correctly like it can't see the admin folder in staticfiles and its contents. (venv) root@ubuntu-s-1vcpu-512mb-10gb-sfo3-01:~/cquence# ls -la total 288 drwxr-xr-x 13 root root 4096 Sep 9 23:58 . drwx------ 10 root root 4096 Sep 9 23:56 .. drwxr-xr-x 4 root root 4096 Jul 31 00:27 account drwxr-xr-x 3 root root 4096 Sep 9 23:56 config -rw-r--r-- 1 root root 233472 Sep 9 23:58 db.sqlite3 drwxr-xr-x 5 root root 4096 Sep 9 23:12 djangopaypal -rwxr-xr-x 1 root root 662 Mar 14 16:49 manage.py drwxr-xr-x 4 root root 4096 Jul 31 00:28 polls drwxr-xr-x 7 root root 4096 Jul 25 22:33 productionfiles drwxr-xr-x 7 root root 4096 Sep 5 11:50 registration drwxr-xr-x 2 root root 4096 Sep 9 23:32 static drwxr-xr-x 7 root root 4096 Sep 9 23:48 staticfiles drwxr-xr-x 5 root root 4096 Sep 9 17:41 stripe_demo drwxr-xr-x 5 root root 4096 Mar … -
Django TemplateView raising on production Server 500 error
I am using Django with a gunicorn server for serving the dynamic templates and also the static files with whitenoise. The application runs in an Docker-Container with a postgresql Database. When using the DEBUG = True in the setting files. The html using TemplateView class is displayed. However, when changing to DEBUG = FALSE the server raises a 500 code. All the other pages are rendered and work. So I dont think it is an issue where I placed the html files. Also the static files are beeing served by gunicorn correctly. What I found out so far is that in the settings: #STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' Makes the difference...but how and why? I was aked to create a MRE. So here it is and I hope it is fine like this. To reproduce it the following is needed: a django project and docker. In the settings I have a base.py and a test.py. Here the base.py """ Django settings for RootApplication project. Generated by 'django-admin startproject' using Django 2.1.dev20180114011155. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ """ import os from django.utils.translation import gettext_lazy as _ BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) … -
Django prefetch_related on ForeignKey relation
I have this database setup: class Profile(AbstractBaseUser, PermissionsMixin): email = models.CharField(max_length=30, null=True, unique=True) date_created = models.DateTimeField(auto_now=True) ... class SubProfile(models.Model): profile = models.OneToOneField(Profile, on_delete=models.CASCADE) display_name = models.CharField(max_length=25) ... class SubProfilePost(models.Model): profile = models.ForeignKey(Profile, related_name='sub_profile_postings', on_delete=models.CASCADE) title = models.CharField(max_length=20, null=False) looking_for_date = models.DateTimeField(null=False) How do I now fetch the SubProfiles, and prefetch the related SubProfilePosts? I have tried doing this: subprofile_queryset = SubProfile.objects \ select_related('profile') \ prefetch_related( Prefetch('profile__sub_profile_postings', queryset=SubProfilePost.objects.only('id', 'looking_for_date'))) When I run the queryset through my serializers: serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) The data does not contain SubProfilePost(s). If I directly access the obj.profile.sub_profile_postings.all() I can see the data. I might be misunderstanding how prefetching works, or whether the data is annotated to the queryset when prefetching etc. Can someone more experienced enlighten me if there is something wrong with my setup, or am I misunderstanding the whole concept. Here are my serializers: class ProfileSerializer(ModelSerializer): class Meta: model = Profile fields = '__all__' extra_kwargs = { 'password': {'write_only': True, 'required': False}, } class SubProfilePostSerializer(ModelSerializer): profile = ProfileSerializer() class Meta: model = SubProfilePost fields = '__all__' class SubProfileSerializer(ModelSerializer): sub_profile_postings = SubProfilePostSerializer(many=True, read_only=True) class Meta: model = SubProfile fields = [ 'id', 'profile', 'display_name', 'sub_profile_postings', # Prefetched field ] -
Should I use `select_for_update` in my Django transcription application?
My app allows users to upload and transcribe audio files. My code stores the audio file and transcript in a postgres database. Here is my original code: try: transcribed_doc = TranscribedDocument.objects.get(id=session_id) except TranscribedDocument.DoesNotExist: ... try: if transcribed_doc.state == 'not_started': transcribed_doc.state = 'in_progress' transcribed_doc.save() ... Here is the adjusted code: try: transcribed_doc = TranscribedDocument.objects.select_for_update().get(id=session_id) except TranscribedDocument.DoesNotExist: ... try: if transcribed_doc.state == 'not_started': transcribed_doc.state = 'in_progress' transcribed_doc.save() ... I know select_for_update() is used to lock the row being updated to prevent situations where multiple calls might try to update the same record simultaneously. But I can only imagine such a situation if the same user mistakenly or maliciously start the same transcription process multiple times by, for example, hitting the 'start transcription' button several times.