Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Make django middleware variables able to handle concurrent requests
I have to implement a custom middleware in django to count the number of requests served so far. It is a part of an assignment that I've got. I have created the middleware like this # myapp/middleware.py from django.utils.deprecation import MiddlewareMixin class RequestCounterMiddleware(MiddlewareMixin): request_count = 0 def process_request(self, request): RequestCounterMiddleware.request_count += 1 def process_response(self, request, response): return response @staticmethod def get_request_count(): return RequestCounterMiddleware.request_count Now my question is how to make the variable request_count able to handle concurrent requests and show the correct value. ChatGPT suggested using threading.Lock(). Would that be a good option? If not, please suggest some other way. Thanks :) -
fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory
running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-cpython-312 creating build\lib.win-amd64-cpython-312\MySQLdb copying MySQLdb_init_.py -> build\lib.win-amd64-cpython-312\MySQLdb copying MySQLdb_exceptions.py -> build\lib.win-amd64-cpython-312\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-cpython-312\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-cpython-312\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-cpython-312\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-cpython-312\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-cpython-312\MySQLdb creating build\lib.win-amd64-cpython-312\MySQLdb\constants copying MySQLdb\constants_init_.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants running build_ext building 'MySQLdb.mysql' extension creating build\temp.win-amd64-cpython-312 creating build\temp.win-amd64-cpython-312\Release creating build\temp.win-amd64-cpython-312\Release\MySQLdb "C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -Dversion_info=(2,1,0,'final',0) -D__version_=2.1.0 "-IC:\Program Files\MariaDB\MariaDB Connector C\include\mariadb" "-IC:\Program Files\MariaDB\MariaDB Connector C\include" -ID:\python\ewp_django_backend\venv\include -IC:\Users\USER\AppData\Local\Programs\Python\Python312\include -IC:\Users\USER\AppData\Local\Programs\Python\Python312\Include "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\cppwinrt" /TcMySQLdb/_mysql.c /Fobuild\temp.win-amd64-cpython-312\Release\MySQLdb/_mysql.obj _mysql.c MySQLdb/_mysql.c(29): fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64\cl.exe' failed with exit code 2 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for mysqlclient Failed to build backports.zoneinfo mysqlclient ERROR: ERROR: Failed to build installable wheels for some pyproject.toml based projects (backports.zoneinfo, mysqlclient) I … -
How to set up virtual environment in visual studio?
I am trying to start working with django and visual studio but I cannot figure out what are the instructiosns are to set up a virtual environemnt. How do you do this? I have both tried in a blank file and also in the Terminal. enter image description here I tried to both use the terminal and add the code to a blank file -
Django-Cryptography not encrypting sensitive data in models as expected
I am using django-cryptography to encrypt my sensible data, but it does not does it. ```python from django_cryptography.fields import encrypt class ComplaintModel(BaseModel): detailed_description = encrypt(models.TextField(null=False,)) <br> [![enter image description here][1]][1] <br> [![enter image description here][2]][2] [1]: https://i.sstatic.net/guv90eIz.png [2]: https://i.sstatic.net/2gEHhGM6.png -
How to add an i18n locale tag to a Nuxt api proxy?
I am currently working on an app with a Nuxt frontend and a Django backend. The Django backend is localized with i18n. Therefore, the URL contains an i18n tag (example.com/en/). I now want to take this tag from i18n in Nuxt and add it to my proxy in the Nuxt config, which currently looks like this: // https://nuxt.com/docs/api/configuration/nuxt-config export default defineNuxtConfig({ compatibilityDate: '2024-04-03', devtools: { enabled: true }, modules: ['@nuxtjs/tailwindcss', '@nuxtjs/i18n'], nitro: { devProxy: { '/api': { target: `http://127.0.0.1:8000/`, changeOrigin: true, }, }, }, i18n: { locales: ['en', 'de'], defaultLocale: 'en', }, }); The process should be as follows: User with French Nuxt language calls example.com/hello mybackend.com/fr/hello is called via the proxy (/api). If it is Russian, mybackend.com/ru/hello is called. I tried to achieve my goal with a middleware, but could only append the tag. -
Django-Tables2 To Export Multiple Tables
I am working with Django-tables2 and Django to export multiple tables in 2 file. Is this possible? If so, how would it be done? When I try, it gives me an as_values error. -
How to include a field's display text (i.e., "get_foo_display") in a ModelSchema in django ninja?
Problem Let's say I have a django model with an IntegerField with a defined set of choices and then a django ninja schema and endpoint to update this model. How can I access the display text for the IntegerField (i.e., get_foo_display)? Example Code models.py from django.db import models from django.utils.translation import gettext_lazy as _ class PracticeSession(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=False,related_name="practice_sessions", db_index=True, ) class RATING_CHOICES(models.IntegerChoices): UNHELP = 1, _('unhelpful') NEITHER = 2, _('neither helpful nor unhelpful') HELP = 3, _('helpful') rating = models.IntegerField(choices=RATING_CHOICES.choices) is_practice_done = models.BooleanField(default=False) api.py from ninja import NinjaAPI, Schema, ModelSchema from ninja.security import django_auth from practice.models import PracticeSession api = NinjaAPI(csrf=True, auth=django_auth) class UpdatePracticeSessionSchema(ModelSchema): class Meta: model = PracticeSession fields = ['is_practice_done', 'rating'] @api.put( "member/{member_id}/practice_session/{sesh_id}/update/", response={200: UpdatePracticeSessionSchema, 404: NotFoundSchema} ) def update_practice_sesh(request, member_id: int, sesh_id: int, data: UpdatePracticeSessionSchema): try: practice_sesh = PracticeSession.objects.get(pk=sesh_id) practice_sesh.is_practice_done = data.is_practice_done practice_sesh.rating = data.rating practice_sesh.save() return practice_sesh except Exception as e: print(f"Error in update_practice_sesh: {str(e)}") return 404, {'message': f'Error: {str(e)}'} Things I've tried I tried adding rating_choices = PracticeSession.rating.field.choices to my UpdatePracticeSessionSchema before class: Meta, but this triggered a pydantic error (see below), and, besides, this extra field in my Schema would have only gotten me a step closer to creating some … -
Django: How can I create code to show the question with follow levels as easy until hard
enter image description here enter image description here my system can show question have save in the table, but just random way. create code that categorizes questions by difficulty level (easy, medium, hard), and displays them in ascending order of difficulty. -
Unexpected " [] " Characters on Django Admin Log in Page
I have a Django App running on a local server. I am using the default admin features and rendering with collected static files. However, I am seeing " [] " inserted into the main content of the login form. Why is this and how do I ensure this doesn't occur? -
django 5.1 email [WinError 10061]
хочу отправить письмо с джанго вроде все настроил верно но выходит ошибка: ConnectionRefusedError: [WinError 10061] Подключение не установлено, т.к. конечный компьютер отверг запрос на подключение. помогите пжл. вот мои настройки: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.yandex.ru' EMAIL_PORT = 465 EMAIL_USE_TLS = False EMAIL_USE_SSL = True EMAIL_HOST_USER = \['Vlad.Olegov750@yandex.ru'\] EMAIL_HOST_PASSWORD = 'пароль' RECIPIENTS_EMAIL = \['Vlad.Olegov750@yandex.ru'\] DEFAULT_FROM_EMAIL = \['Vlad.Olegov750@yandex.ru'\] SERVER_EMAIL = \['Vlad.Olegov750@yandex.ru'\] EMAIL_ADMIN = \['Vlad.Olegov750@yandex.ru'\] пробовал менять порт на 587. но без успешно