Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Python, I want to give image as input and according to it products from local db (SQLite or SQLServer or MySQL) should be displayed
I am looking for a sample code where I can give input type as Image to search for products using Python Django Framework for one of project. after image successfully uploaded, I need to check the image and according to it, products should be listed on search page. After image successfully uploaded, I need to check the image and according to it, products should be listed on search page, from Database (SQLite, MySQL, SQL Server or any) -
How to approach Django app in another Docker Container?
I running Django Projects with Docker Container. Theres' three containers in Server. Accounts Container Blogs Container Etc Container Situation. I want to approach to Accoutns Container in Blogs Container. Why. There's Article Table in Blogs Conatiner. And Blogs Container doesn't have accounts app. so I have to approach to accounts app in Accounts Container. class Article(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ... I dont have any idea :( -
How to set up rollup config to allow for direct imports?
I have created a component library in React and am using rollup as my bundler. My project directory looks like this: src ├── assets │ ├── fonts │ └── icons ├── components │ ├── Alert │ │ ├── Alert.tsx │ │ └── index.tsx │ ├── Button │ │ ├── Button.tsx │ │ └── index.tsx │ └── index.tsx ├── styles ├── utils └── index.tsx My package.json looks like this: "files": [ "dist" ], "main": "dist/esm/index.js", "module": "dist/esm/index.js", "type": "module", "exports": { ".": "./dist/esm/index.js", "./components": "./dist/esm/components", "./assets": "./dist/esm/assets", "./utils": "./dist/esm/utils" }, "types": "dist/index.d.ts", My rollup configuration looks like: import resolve from '@rollup/plugin-node-resolve'; import commonjs from '@rollup/plugin-commonjs'; import typescript from '@rollup/plugin-typescript'; import terser from '@rollup/plugin-terser'; import copy from "rollup-plugin-copy-assets"; import dts from 'rollup-plugin-dts'; import postcss from 'rollup-plugin-postcss'; import svgr from '@svgr/rollup'; import packageJson from './package.json' assert { type: "json" }; /** * @type {import('rollup').RollupOptions} */ const config = [ { input: 'src/index.ts', output: [ { file: packageJson.module, format: 'esm', }, ], plugins: [ copy({ assets: [ "src/assets", ] }), resolve(), commonjs(), typescript({ tsconfig: './tsconfig.build.json', declaration: true, declarationDir: 'dist', }), postcss(), svgr({ exportType: 'named', jsxRuntime: 'automatic' }), terser(), ], external: ['react', 'react-dom', 'react-select', 'styled-components'], }, { input: 'dist/esm/index.d.ts', output: [{ file: 'dist/index.d.ts', format: "esm" … -
ImportError: attempted relative import with no known parent package WHILE IMPORTING VIEWS INSIDE URLS IN DJANGO
i am a beginner in Django and I am trying to import views in URL getting this error. Attaching the screenshots enter image description here enter image description here I hoped that the import of views inside Url would be successful .is that a problem with directory?? -
cPanel terminal not found, how to find it?
I am deploying a Django project in cPanel, but not showing a terminal option even in advance section. how can I find it? -
python django serializer wrong date time format for DateTimeField
I'm using Django 3.0.2. I have a serializer defined: class ValueNestedSerializer(request_serializer.Serializer): lower = request_serializer.DateTimeField(required=True, allow_null=False, format=None, input_formats=['%Y-%m-%dT%H:%M:%SZ',]) upper = request_serializer.DateTimeField(required=True, allow_null=False, format=None, input_formats=['%Y-%m-%dT%H:%M:%SZ',]) class DateRangeSerializer(request_serializer.Serializer): attribute = request_serializer.CharField(default="UPLOAD_TIME") operator = request_serializer.CharField(default="between_dates") value = ValueNestedSerializer(required=True) timezone = request_serializer.CharField(default="UTC") timezoneOffset = request_serializer.IntegerField(default=0) class BaseQueryPayload(request_serializer.Serializer): appid = request_serializer.CharField(required=True, validators=[is_valid_appid]) filters = request_serializer.ListField( required=True, validators=[is_validate_filters], min_length=1 ) date_range = DateRangeSerializer(required=True) And the payload : { "appid": "6017cef554df4124274ef36d", "filters": [ { "table": "session", "label": "1month" } ], "date_range": { "value": { "lower": "2023-01-01T01:00:98Z", "upper": "2023-01-20T01:00:98Z" } }, "page": 1 } But I get this validation error: { "error": { "date_range": { "value": { "lower": [ "Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm:ssZ." ], "upper": [ "Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm:ssZ." ] } } } } The suggested format YYYY-MM-DDThh:mm:ssZ is similar to what is passed. Am I missing anything here? -
How to add a check constraint in django model that a field value startwith letter 'c' or 'e' or 'a'
How to add a check constraint in django model that a field value startwith letter 'c' or 'e' or 'a' like the bellow SQL check constraint CREATE TABLE Account ( account_no varchar(12), FirstName varchar(255), Age int, City varchar(255), CONSTRAINT CHK_Person CHECK (SUBSTR(account_no,1,1) = 'c' OR SUBSTR(account_no,1,1) = 'e' OR SUBSTR(account_no,1,1) = 'a' ) ); i try with meta class of model. but i don't know how to specify the or case class Meta: constraints = [ CheckConstraint( check = Q(account_no___startswith=F('')), name = 'check_start_date', ), ] -
plain python script vs robot framework vs python script with web ui
I have a task to create a validation testing for new firmware builds of firewalls (do upgrade and test all firewall features ), i have a good Python knowledge . and need users to have any kind of UI for the test . i am confused which method to use . 1- Python scripts with logging and execute it from Jenkins . 2- robot framework which has its own reporting and run it from Jenkins . 3- python script with Django web UI . i'v done part of the project with robot framework which has a very limited documetation and info on the internet . i cannot do certain tasks as it gets complex . i am in love with it's reporting but at some point felt it is not worth it . now i am trying to redo this part with normal python scripts . -
How we can connect react js with django?
How we can connect react js with django without installing node js? Code of connect django with react without install nodejs server -
msgfmt : The term 'msgfmt' is not recognized as the name of a cmdlet, function, script file, or operable program. (Windows 10)
I have a django application based on django 1.11 and when i make changes on locale's .po files i run the following command: msgfmt django.po -o django.mo The command worked fine on my linux machine but I can't find a proper guide on how to get msgfmt command to work on windows. Following error message is shown: msgfmt : The term 'msgfmt' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + msgfmt django.po -o django.mo -
How i can to use django-import-export with a django-mptt?
In the project i using 2 package "django-import-export" and "django-mptt" url follow below. django-import-export : https://django-import-export.readthedocs.io/en/latest/ django-mqtt : https://django-mptt.readthedocs.io/en/latest/overview.html I have a problem when i import using django-import-export is not work with mqtt models. show error below PARENT Cannot assign "'Dept1'": "Dept.parent" must be a "Dept" instance. i think to error cause when i import data from xlsx. the django-import-export will try to check data. due to mqtt have a node parent the second records will try to add data but not have a parent in database. i want to know how i can to import and export ? thank you for expert . -
How to populate Model B when saving Model A
I have two Model, A and B respectively. I have created an modelform for Model A which i use in creating instances of Model A. What i want to achieve is that whenever i save Model A, i want an instance of Model B to be created automatically. models.py class A(models.Model): member = models.ForeignKey(User, on_delete=models.CASCADE, default="") book = models.ForeignKey(Books, on_delete=models.CASCADE, default="") library_no = models.CharField(default="", max_length=255, blank=True) staff_id = models.CharField(default="", max_length=255, blank=True) application_date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = " Borrow Book" def __str__(self): return (str(self.member)) + " " + "applied to borrow " + (str(self.book)) class B(models.Model): application = models.ForeignKey(BorrowBook, on_delete=models.SET_NULL, default="", null=True) approved = models.BooleanField() approval_date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = "Approved Lending" def __str__(self): return str(self.application) Any idea as to how i can achieve it. -
Propagating Django model clean() methods ValidationErrors into the form for user signup
I am using django-allauth's SignupForm to create new custom user objects. To ensure that any data put into the database is valid I have most of my validation within my model's clean() method. This is called by calling self.full_clean() within the save() method of my custom user model. By putting validation here (rather than in any signup form I use) I can ensure I hopefully have better data integrity as objects cannot be saved (even when using the API) without first being cleaned & valid. The issue I am having occurs when I am raising ValidationErrors within my models's clean() method. Instead of correctly propagating the ValidationErrors from the model to the signup form (which would then nicely display them in my template as an error list) the errors are raised as normal causing a server crash/HTTP 500 error (see below) Here is my custom user model (I have overridden many of the default fields provided by AbstractUser in order to customise certain aspects of their functionality): class User(AbstractUser): username = models.CharField( "Username", max_length=30, unique=True, validators=[ RegexValidator( r"^[\w.-]+\Z", "Enter a valid username. This value may contain only letters, digits and ./_ characters." ), ReservedNameValidator, validate_confusables ], error_messages={ "unique": "A user … -
ResolutionImpossible - Conflicting dependencies while deploying on heroku
While deploying a Django + React project on Heroku, this error occoured: The conflict is caused by: djoser 2.1.0 depends on social-auth-app-django<5.0.0 and >=4.0.0 rest-social-auth 8.0.0 depends on social-auth-app-django<6.0 and >=5.0 If I downgrade to social-auth-app-django==4.0.0 pkg, then get this error: raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: WSGI application 'backend.wsgi.application' could not be loaded; Error importing module. This error is caused by social_django which is added in settings.py MIDDLEWARE = [ .... # For social auth 'social_django.middleware.SocialAuthExceptionMiddleware', .... ] Fixed this error by removing/commenting it out, then found another one: cannot import name 'urlquote' from 'django.utils.http' (lib\site-packages\django\utils\http.py) Because urlquote() is no longer available in Django 4.0+ versions, after downgrading social-auth-app-django==4.0.0 pkg. This try to import from django.utils.http import urlquote in filelib\site-packages\social_django\context_processors.py. I'm in Dependency hell. I have even tried to downgrading the djoser pkg, then got other errors. After searching a lot, I found this blog post, according to this: First, pip install pip-tools then create a requirements.in file and add django djangorestframework then run pip-compile ./requirements.in this will generate requirements.txt file: # This file is autogenerated by pip-compile with Python 3.9 # by the following command: # # pip-compile ./requirements.in # asgiref==3.6.0 # via django django==4.1.5 # via # -r ./requirements.in # … -
In Django, how to filter a _set inside a for loop?
I have these two models: class Convocacao(models.Model): cursos = models.ForeignKey(Cursos) class RegistroConvocacao(models.Model): convocacao = models.ForeignKey(Convocacao) I get a specific object from Convocacao: obj = get_object_or_404( Convocacao.objects.prefetch_related("cursos", "registroconvocacao_set"), pk=pk, ) Now, while the for loop runs through obj.cursos, I need to filter obj.registroconvocacao_set inside the loop: for curso in obj.cursos.all(): obj.registroconvocacao_set.filter(...filters...)... However, in each iteration of the for loop, obj.registroconvocacao_set.filter() makes a new query to the database, generating thousands of accesses to the database and repeated queries. How do I prefetch obj.registroconvocacao_set to avoid this? -
DEBUG=True is in your settings file and you have not configured any URLs
This junk is trippin. I have the app registered in installed apps, I have my templates directory set up properly, and I even have all the urls configured in both urls.py files. What am I doing wrong? (https://i.stack.imgur.com/CsosC.png)(https://i.stack.imgur.com/g6RA5.png)(https://i.stack.imgur.com/JIVJa.png)(https://i.stack.imgur.com/ausuN.png) I was expecting it to work, what else? -
Any way to speed up case-insensitive Django UniqueConstraint?
The Django docs show this example UniqueConstraint: UniqueConstraint(Lower('name').desc(), 'category', name='unique_lower_name_category') First off, the desc() produces errors in the admin interface. (Edited version below.) ProgrammingError at /admin1/app/tablename/add/ syntax error at or near "DESC" LINE 1: ...lename" WHERE LOWER("tablename"."name") DESC = (LO... ^ Request Method: POST Request URL: http://host/admin/app/tablename/add/?_changelist_filters=a_val Django Version: 4.1.5 Exception Type: ProgrammingError Exception Value: syntax error at or near "DESC" LINE 1: ...lename" WHERE LOWER("tablename"."name") DESC = (LO... Okay, never mind that. Let's drop desc(). And, I don't have two fields, I only have one. So look at this UniqueConstraint: UniqueConstraint(Lower('name'), 'name', name='unique_lower_name') When I load data into that table in Postgres (13 or 14, say), it's quite slow. Is there an easy way to speed up having a constraint that says "Only one version of this name (ignoring case) should be in the table"? I could drop the constraint. I could also add a field that's all lowercase and put a unique constraint on that field. It would be extra DB info (a cache), but for performance sake. -
Can't create superuser in Django using custom user
I got this error when i try to run manage.py createsuperuser TypeError: UserManager.create_superuser() missing 1 required positional argument: 'username' My User model: class User(AbstractUser): name = models.CharField(max_length=32) email = models.CharField(max_length=140, unique=True) password = models.CharField(max_length=140) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] and in my settings.py file: AUTH_USER_MODEL = 'usuarios.User' How can i solve this? Im new in Django, documentation is confused to me... I already tried remove AUTH_USER_MODEL = 'usuarios.User' or remove username attribute from class User -
How to return JsonResponse without using Return in Django
Am building a USSD app that requires me to send a return JsonResponse but i want to do it without using Return. Beacuase i want to a couple of things after the return payload ={ "USERID": code_id, "MSISDN": serviceCode, "MSGTYPE": type_msg, "USERDATA": text, "SESSIONID": session_id, "MSG": response, } return JsonResponse(payload) -
Django Authentication, should frontend connect to remote database using API or SSH key?
I'm new to backend and now in my backend, I have a database and server connecting, I'm trying to build a login and registration function. And in my frontend, I'm not connecting to my database directly. My question is, should I connect to my database using my ssh key so that I can register a user directly on my frontend? Or should I just post my username and password to the backend using my API? But for this approach, how to encode the password and save it to the user authentication table? Thanks for your help! Kind regards, Xi -
How to list a series of Objects Models in another model?
I'm creating a chatbot, with two Models. A Message model which will store all messages sent by all users to the bot, as raw data without filters. A second model representing a chat, which has to be private and specific to the user. Therefore, I need to store messages within this chat, but entries related to the chat user only. So, on the one hand I have a model with one object is equal to one message, on the other hand I want a second model storing only user's content messages. class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) room = models.CharField(max_length=1000) media = models.BooleanField(default=False) mediasrc = models.CharField(max_length=1000, default=None) class Chat(models.Model): userchat = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, blank=True) group = models.BooleanField(default=False) messages = models.ManyToManyField(Message, blank=True, related_name='userchat') last_modified = models.DateTimeField(auto_now=True) My issue is that this second model (the Chat's ones) is listing all existing messages. I need to specify a filter for the ManyToManyField. -
django json_script variables not updating in javascript for loop
In my django project I have a for loop that iterates through a list of dicts containing a list of prices and and a list of dates. The lists of prices and dates for each item will then be used for a javascript graph for each individual item. The problem is that all of the graphs are the same. When outputting prices and dates in the console each list of prices and dates are the same as the first element in the list of items. Why is this happening? console output - (sw0_ _ _ is the ID of each item) html {% for item in watchlist_items %} <canvas id="chart_{{item.item_id}}"></canvas> {{ item.prices|json_script:"prices" }} {{ item.dates|json_script:"dates" }} <script> var prices = JSON.parse(document.getElementById('dates').textContent); var dates = JSON.parse(document.getElementById('prices').textContent); var data = []; for (let i = 0; i < prices.length; i++) { data.push({x:prices[i], y:dates[i]}); } console.log(`chart_{{item.item_id}} - `, "prices:",prices, "dates:", dates) new Chart(`chart_{{item.item_id}}`, { ... data: { data:data } ... } </script> {% endfor %} -
Elastic Beanstalk 504 Gateway Timeout Error - Django
I recently completed the W3schools.com Django Tutorial. I followed it step by step. Everything works as expected locally. I also created and connected a PostgreSQL database on Amazon RDS to my app. Eventually I deployed the Django application to Elastic Beanstalk. Finally I visited the website and the homepage works, including 5 items added to the database during the tutorial which was migrated from the tutorial to the Amazon RDS. Unfortunately, neither the Django admin panel nor a simple subdirectory of the website are accessible. I get a 504 Gateway Time-out error. I don't know why. It is not clear from the logs what the issues might be. I am thinking it could possibly be a configuration file error or an incorrect value of settings.py on Django's side. Any help would be greatly appreciated. -
Not getting the expected result from Django reverse
hope anyone here will be able to help me out. I am trying to get the reverse url for a viewset but somehow it's not working. I will quickly go through what I have done from the moment everything was working fine to the moment the reverse stopped working. I had a viewset on an app called "card" the reverse was reverse('card:card-list') everything was perfect, then I decided to move the card viewset to a different app called 'company' I did check the new urls structure by using the django_extensions and running the following command on the terminal python manage.py show_urls which gave me the new routing company:card-list I have then changed my reverse to reverse('company:card-list'), but now the code is broken and the reverse is not working as expected. I have done those changes cause an end point as /api/company/card instead of /api/card/ . Any ideas on how to solve it? tks a lot -
Memory quota exceeded when running Django Celery On Heroku
I have a Django project for running periodic tasks using Celery that is deployed to Heroku from GitHub. The project is a web scraping project that scrapes through other websites and stores the result in backend. The website is deployed on heroku well and the other parts are working fine. The issue is that whenever I start the periodic tasks, I get the error Process running mem=760M(148.5%) Error R14 (Memory quota exceeded) in the logs. Also no results is saved in the database. The website is working fine in my localhost without any errors. Here is my Procfile configuration; web: gunicorn jobWebsite.wsgi --log-file - --log-level debug worker: celery -A jobWebsite worker -l info -B In the second line, I combined the worker and beat processes to use one dyno. Also, here is a part of the logs that I am getting; 2023-01-24T21:58:41.000000+00:00 app[heroku-redis]: source=REDIS addon=redis-flat-79602 sample#active-connections=6 sample#load-avg-1m=0.42 sample#load-avg-5m=0.405 sample#load-avg-15m=0.395 sample#read-iops=0 sample#write-iops=0 sample#memory-total=16084924kB sample#memory-free=12314188kB sample#memory-cached=2049948kB sample#memory-redis=443248bytes sample#hit-rate=0.29167 sample#evicted-keys=0 2023-01-24T21:59:11.683479+00:00 heroku[worker.1]: Process running mem=760M(148.5%) 2023-01-24T21:59:11.685197+00:00 heroku[worker.1]: Error R14 (Memory quota exceeded) 2023-01-24T21:59:32.045205+00:00 heroku[worker.1]: Process running mem=760M(148.5%) 2023-01-24T21:59:32.046763+00:00 heroku[worker.1]: Error R14 (Memory quota exceeded) I have used the Heroku postgres database and also the Heroku Redis database in this project. Any assistance will …