Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to query value in numeric order?
Suppose I have a model class Industry(models.Model): name = models.Charfield(max_length = 100) status = models.IntegerField() order = models.IntegerField() How can i query data in view basing on numeric values i have given in order column to some Industry and others in alphabetical order. industry_results = Industry.objects.filter(filters,status='1').order_by('name','-id').values('name','id').exclude(name__isnull=True).distinct('name') -
Django REST: Dynamically add Model Fields
I'm working on a Django Rest project where I'm given two MySQL tables: metrics: Contain a row for each potential metric daily_data: Contains a row for each data entry where the column names refer to metrics from the 'metrics' table What I want to do now, is creating new entries in 'metrics' which should be automatically added to existing 'daily_data' entries (with a default value) and displayed on the website. Here is how the current models looks like: class Metrics(model.Model): metric_id = models.CharField(max_length=255, primary_key=True) is_main_metric = models.BooleanField(default=False) name = models.CharField(max_length=255, blank=False, null=False) description = models.CharField(max_length=255, blank=False, null=False) lower_bound = models.FloatField(default=0.0, null=False) upper_bound = models.FloatField(default=0.0, null=False) class Meta: verbose_name_plural = "Metrics" db_table = "metrics" class DailyData(models.Model): location = models.CharField(max_length=255, blank=False, null=False) date = models.DateField(blank=False, null=False) # then a static field for each metric is added that corresponds to a 'metric_id' in the table 'metrics': metric_01 = models.FloatField(default=0.0, null=False) metric_02 = models.FloatField(default=0.0, null=False) metric_03 = models.FloatField(default=0.0, null=False) ... class Meta: verbose_name_plural = "Daily Data" db_table = "daily_data" Later on, the Javascript code iterates over all 'metrics' to display them with the corresponding values from a requested 'daily_data' entry. Here is a small example: let resp = await axios.get(`${API_URL}/daily_data/?location=berlin&date=2021-01-07`); let data = resp.data[0]; … -
Set Django auto-increment primary key to specific value
I have an Order model for which I grabbed a bunch of orders from an older system. As we wanted to preserve the ID, I set it manually during the migration. However, this has thrown of the auto-increment key. It's no longer correct. How can I set the auto-increment to start from a specific value? -
Filter Data via DateTimeField in Local Timezone [DJANGO]
Date and time are saved in the MySQL db in UTC. I need to filter for objects saved via date depending on the user timezone. For example, John who is in 'Africa/Lagos' timezone did a transaction on Feb 1, 2021 at 12:00AM in his local time and it will be saved in the DB as Jan 31, 2021 23:00 UTC. When I run the below query on Feb 1, 2021 it won't come up because of the +1 hr difference. time_zone = pytz.timezone("Africa/Lagos") today_date = timezone.now().astimezone(time_zone).date() today_transaction = Credit.objects.filter(created_date__contains=today_date) Where today's date is Feb 1, 2021. But because it was saved in the DB in UTC, the exact date in local timezone won't be returned. The query will return []. Is it possible to make the conversion today_date in the DB level? What am I missing? -
How to run celery from different location?
My folder structures are like below root ---django_files ---django_app1 ---django_app2 ---scripts --some sh files I want to run celery from root folder. I write code like this celery -A django_files.proj.celery_conf:app worker --loglevel=info It says no module named django_files. I guess my command line is not correct,how can i run then from root folder? -
Django ValidationError Doesn't Show Up
I am learning a django and I was practicing registration. But before doing that, I wanted to test the validationerrors but it doesn't show up the error message on the screen even if the form is not valid. I want my program to write on screen an error message when student_tc and student_password don't match. views.py messages = [] def student_register(request): if request.method == "POST": form = StudentRegisterForm(data=request.POST) if form.is_valid(): student_name = form.cleaned_data.get('student_name') student_surname = form.cleaned_data.get('student_surname') student_no = form.cleaned_data.get('student_no') student_contact = form.cleaned_data.get('student_contact') student_email = form.cleaned_data.get('student_email') student_tc = form.cleaned_data.get('student_tc') student_gender = form.cleaned_data.get['student_gender'] student_branch = form.cleaned_data.get('student_branch') student_password = form.cleaned_data.get('student_password') data = {'student_name': student_name, 'student_surname': student_surname, 'student_no': student_no, 'student_contact': student_contact, 'student_email': student_email, 'student_tc': student_tc, 'student_gender': student_gender, 'student_branch': student_branch, 'student_password': student_password} messages.append(data) form.save() return render(request, 'student_registered.html') else: return render(request, 'student_register.html', context={'form': form}) form = StudentRegisterForm() return render(request, 'student_register.html', context={'form': form}) forms.py class StudentRegisterForm(forms.ModelForm): class Meta: model = Student fields = ['student_name', 'student_surname', 'student_tc', 'student_gender', 'student_no', 'student_contact', 'student_email', 'student_branch', 'student_password'] widget = {'student_password': PasswordInput} def __init__(self, *args, **kwargs): super(StudentRegisterForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs = {'class': 'form-control'} def clean(self): student_password = self.cleaned_data.get('student_password') student_tc = self.cleaned_data.get('student_tc') if student_password != student_tc: raise forms.ValidationError('Password and TC don't match') return student_password def clean_email(self): student_email = self.cleaned_data.get('student_email') student_email … -
Internationalization does not work in pythonanywhere
I have deployed my Django website to PythonAnywhere last week and in the meantime, I made some changes to texts on the website. Now, I am trying to translate these pieces of text using the internationalization package in PythonAnywhere, but somehow it does not work. When I run python manage.py makemessages -l en, my django.po file is updated and I am able to add the translations, but once I run python manage.py compilemessages -l en, the English translations do not show up on the website. The first day, I did get the translations to work, but now they don't anymore. What could be the cause of this? And could anybody help me find a way to solve the issue? Thanks! -
How to launch django with socket io on nginx gunicorn/uwsgi
is there any tutorial or guide to properly launch python socketion with django on nginx gunicorn/uwsgi server? I have tried those at official documentation, but not successful. -
Django app extremely slow after upgrading Django from 3.0.8 to 3.1.5 and channels from 2.4.0 to 3.0.3
So I've developped Django app using Django 3.0.8 and served it as an asgi app with channels 2.4.0 and daphne. At that point in time those were the latest versions. The application was working nicely with web sockets and django views working adequately, and channels handled treading great. So all was great and world seemed like a beautiful place... until some evil inside me pushed to upgrade Django to 3.1.5 which required upgrading channels to 3.0.3. So now app still works, all pages are served and web sockets work, but all HTTP requests are queued and handled in one thread, which makes the application extremely slow. I've tried to read the docs for channels 3 and all release notes for Django and channels, yet I'm not seeing what has changed and what changes I need to introduce to make my app run like it was before. Here are all versions of related packages Django==3.1.5 channels==3.0.3 channels_redis==3.2.0 asgiref==3.3.1 daphne==3.0.1 I also use Redis 6. My routing looks like this application = ProtocolTypeRouter({ "http": get_asgi_application(), 'websocket': AuthMiddlewareStack( URLRouter( websocket_urls.urlpatterns ) ), }) Any suggestions on what I'm doing wrong here are welcome. -
is there a way to get the count of conflicts while using Django ...bulk_create(.., ignore_conflicts=True)?
I am using bulk_create to upload some data from excel to django db. Since the data is huge I had to use bulk_create instead of .create and .save. But the problem is that I need to show the user how many duplicate data has been found and has not been uploaded due to integrity error. Is there a way to get the number of errors or duplicate data while using bulk upload? -
How can i call MySQL custom function in django ORM?
i want call this function with Django ORM, not with connection.corsur() CREATE FUNCTION RefreshOrderId (order_id_ INT) RETURNS INT DETERMINISTIC BEGIN DECLARE last_order_id INT; SELECT MAX(order_id) INTO last_order_id FROM post_order; UPDATE post_order SET order_id = last_order_id + 1 WHERE order_id = order_id_; RETURN last_order_id + 1; END; // DELIMITER ; -
configure django apscheduler with apache & mod wsgi
I have configured django apscheduler in django project by running the below command - python manage.py runapscheduler but now we have moved the application to the production server and configured with Apache & Mod wsgi so now how to configure and run apscheduler. Kindly suggest. -
Python Django execute save() on database [duplicate]
I've been doing some work in Django and noticed most people push save() right away after the change to model has been made for example in SQLAlchemy if we loop over few db objects and do modification after the loop we can say db.session.commit() saying to commit everything that has been done and save some performance but committing in bulk rather on each loop Is there a similar function for Django? -
why scheduled job using corn is not working in django?
I've used https://pypi.org/project/django-crontab/to tutorial to schedule corn job but it is not working: I added INSTALLED_APPS = [ ..., 'django_crontab', ] CRONJOBS = [ ('*/1 * * * *', 'allActivitiesApp.cron.sendNotification', '>> /path/to/log/file.log'), ] In allActivitiesApp -> corn.py: from .models import * def sendNotification(): # notificationList = dateBasedNotificaton.objects.filter(scheduleDate = date.today()) obj = test(name="working") obj.save() obj.refresh_from_db() # print("sending notifications/messages") return "success" but it is not doing anything when I tried to get logs I found: Feb 1 13:17:01 karanyogi CRON[43137]: (root) CMD ( cd / && run-parts --report /etc/cron.hourly) Feb 1 13:17:01 karanyogi CRON[43138]: (karanyogi) CMD (/home/karanyogi/E-Mango/env/bin/python /home/karanyogi/E-Mango/Jan27New/eMango/manage.py crontab run 60a198cfdc0c719d07735a708d42bafb >> /path/to/log/file.log # django-cronjobs for iStudyMain) Feb 1 13:17:01 karanyogi CRON[43136]: (karanyogi) MAIL (mailed 71 bytes of output but got status 0x004b from MTA#012) Feb 1 13:18:01 karanyogi CRON[43267]: (karanyogi) CMD (/home/karanyogi/E-Mango/env/bin/python /home/karanyogi/E-Mango/Jan27New/eMango/manage.py crontab run 60a198cfdc0c719d07735a708d42bafb >> /path/to/log/file.log # django-cronjobs for iStudyMain) Feb 1 13:18:01 karanyogi CRON[43266]: (karanyogi) MAIL (mailed 71 bytes of output but got status 0x004b from MTA#012) Feb 1 13:19:01 karanyogi CRON[43285]: (karanyogi) CMD (/home/karanyogi/E-Mango/env/bin/python /home/karanyogi/E-Mango/Jan27New/eMango/manage.py crontab run 60a198cfdc0c719d07735a708d42bafb >> /path/to/log/file.log # django-cronjobs for iStudyMain) Feb 1 13:19:01 karanyogi CRON[43282]: (karanyogi) MAIL (mailed 71 bytes of output but got status 0x004b from MTA#012) Feb 1 13:20:01 karanyogi CRON[43437]: … -
django count distinct values of multiple fields
I've no idea on a efficient way to count "GOOD" or "BAD" in a single Feedback.(count from all fields, mean count how many good does this Feedback has). My models.py is as class Feedback(models.Model): ... class FeedbackOption(models.TextChoices): BAD = "BAD", "Bad" GOOD = "GOOD", "Good" ... comment = models.TextField() timestamp = models.DateTimeField(auto_now_add=True, blank=True, null=True) overall_experience = models.CharField(max_length=32, choices=FeedbackOption.choices) doctor_checkup = models.CharField(max_length=32, choices=FeedbackOption.choices) staff_behavior = models.CharField(max_length=32, choices=FeedbackOption.choices) clinic_environment = models.CharField(max_length=32, choices=FeedbackOption.choices) -
ImportError: cannot import name 'CustomerIdNameSerializer' from 'contacts.api.serializers'
I have been trying to craft some unit tests for pytest. The server runs just fine when I do 'python manage.py runserver'. However, when I do 'pytest', it shows the following error: ============================ test session starts ============================= platform darwin -- Python 3.7.9, pytest-6.2.2, py-1.10.0, pluggy-0.13.1 django: settings: tradeforce.settings.dev (from ini) rootdir: /Users/woohyunan/projects/work/tradir/backend-app, configfile: pytest.ini plugins: fixture-order-0.1.3, drf-1.1.2, common-subject-1.0.5, lambda-1.2.4, django-4.1.0, assert-utils-0.2.1 collected 0 items INTERNALERROR> Traceback (most recent call last): INTERNALERROR> File "/Users/woohyunan/myvenv/lib/python3.7/site-packages/_pytest/python.py", line 578, in _importtestmodule INTERNALERROR> mod = import_path(self.fspath, mode=importmode) INTERNALERROR> File "/Users/woohyunan/myvenv/lib/python3.7/site-packages/_pytest/pathlib.py", line 531, in import_path INTERNALERROR> importlib.import_module(module_name) INTERNALERROR> File "/Users/woohyunan/.pyenv/versions/3.7.9/lib/python3.7/importlib/__init__.py", line 127, in import_module INTERNALERROR> return _bootstrap._gcd_import(name[level:], package, level) INTERNALERROR> File "<frozen importlib._bootstrap>", line 1006, in _gcd_import INTERNALERROR> File "<frozen importlib._bootstrap>", line 983, in _find_and_load INTERNALERROR> File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked INTERNALERROR> File "<frozen importlib._bootstrap>", line 677, in _load_unlocked INTERNALERROR> File "/Users/woohyunan/myvenv/lib/python3.7/site-packages/_pytest/assertion/rewrite.py", line 170, in exec_module INTERNALERROR> exec(co, module.__dict__) INTERNALERROR> File "/Users/woohyunan/projects/work/tradir/backend-app/contacts/tests/integration_tests.py", line 4, in <module> INTERNALERROR> from contacts.api.views import CustomerCreateAPIView INTERNALERROR> File "/Users/woohyunan/projects/work/tradir/backend-app/contacts/api/views.py", line 15, in <module> INTERNALERROR> from contacts.api.serializers import ( INTERNALERROR> File "/Users/woohyunan/projects/work/tradir/backend-app/contacts/api/serializers.py", line 7, in <module> INTERNALERROR> import user.api.serializers INTERNALERROR> File "/Users/woohyunan/projects/work/tradir/backend-app/user/api/serializers.py", line 20, in <module> INTERNALERROR> from contacts.api.serializers import ( INTERNALERROR> ImportError: cannot import name 'CustomerIdNameSerializer' from 'contacts.api.serializers' (/Users/woohyunan/projects/work/tradir/backend-app/contacts/api/serializers.py) … -
Environment variable not accessible in wsgi.py
I want to have different settings.py files for the production and development environments for my Django project. For that, I have permanently added an environment variable(DJANGO_ENV) in the production environment based on which I am loading different settings.py. But for some reason, wsgi.py[code below] isn't accessing the environment variable hence the if condition is failing. import os from django.core.wsgi import get_wsgi_application if os.environ.get("DJANGO_ENV") == "PROD": #*this condition is failing for some reason os.environ['DJANGO_SETTINGS_MODULE']= 'myproject.settings_prod' else: os.environ['DJANGO_SETTINGS_MODULE']= 'myproject.settings' application = get_wsgi_application() If I do echo $DJANGO_ENV on the terminal, I get "PROD" as the response, so the variable is set properly. Also in the python shell, I can access the DJANGO_ENV variable. >>> import os >>> os.environ.get("DJANGO_ENV") 'PROD' What am I doing incorrectly? -
How do we seek/backward video file that stored in Django backend?
I have a video file that plays with HTML in frontend, but I can't seek/forward/backward the video. How do I implement this feature ? Any web technologies in any language will be welcomed. I am thinking about web sockets in python and socket.io in JS. -
ModuleNotFoundError: No module named 'fcntl' django
Traceback (most recent call last): File "c:\users\sairam\appdata\local\programs\python\python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\sairam\appdata\local\programs\python\python39\lib\runpy.py", line 87, in run_code exec(code, run_globals) File "C:\Users\sairam.virtualenvs\SEMP-VmrjoZUW\Scripts\gunicorn.exe_main.py", line 4, in File "c:\users\sairam.virtualenvs\semp-vmrjozuw\lib\site-packages\gunicorn\app\wsgiapp.py", line 9, in from gunicorn.app.base import Application File "c:\users\sairam.virtualenvs\semp-vmrjozuw\lib\site-packages\gunicorn\app\base.py", line 11, in from gunicorn import util File "c:\users\sairam.virtualenvs\semp-vmrjozuw\lib\site-packages\gunicorn\util.py", line 9, in import fcntl -
How to use Svelte + Flask (Jinja2) templates?
Summary: To use Svelte instead of jQuery in existing Flask apps. Problem: We've got an existing Flask/Jinja2 server-side rendered website. It uses jQuery. I'd like to use Svelte without SPA/Sapper/Router/etc. and just as a library. Ofcourse, Svelte is a compiled preprocessor that generates optimized vanilla JS that manages state/reactivity without shadow DOM or any other tricks that React/Angular uses. Requirements: Multipage app, cannot be SPA. Routing is not needed, we're fine with page refresh :) and no state needs to be shared between pages (except for cookies ofcourse). Impact: Svelte is great, but vast majority of enterprise and silent majority already have websites written in Flask/Django with some JS functionality (most likely jQuery). Wouldn't be great to use a preprocessor such as Svelte to add interactivity/reactivity to existing websites? Not everyone has the luxury to build SPA apps and there are other reasons for not building one (SEO for e.g.). Possible Ideas: Webpack: Preprocess Svelte app to .js file + .html file. Serve both after rendering it through Jinja2 templating engine. How Vue.js does this: How to render by Vue instead of Jinja Thoughts? I am not familiar with Webpack enough but Svelte seems to be a perfect fit for … -
Django-Upload image to MySQL Database as BLOB
Im creating an E-shop and i have an admin dashboard where i add new products in database. Currently im storing directly the product image as file, and phpmyadmin is converting it to BLOB. But this is not an efficient way to do this. So im coding a HTML page where i can send the image to backend and then upload it to the database. Im using Django Forms to register a new product as follows Forms.py class Upload_New_Product_Form(forms.Form): product_id = forms.IntegerField() name = forms.CharField(max_length=50) price = forms.DecimalField(max_digits=7, decimal_places=2) image = forms.ImageField() products.html <form method="POST" action="{% url 'upload_new_product' %}"> {% csrf_token %} <div class="input-group"> {{product_form}} </div> <br> <button type="submit" class="makeChangebtn btn-primary">Submit changes</button> </form> views.py def Upload_New_Product_View(request): if request.method == 'POST': _id = request.POST['product_id'] name = request.POST['name'] price = request.POST['price'] image = request.POST['image'] print(image) new_product = Product.objects.create(id=_id,name=name,price=price,image=image) new_product.save() When i print the image in my views.py from POST request, i get only the name of the image. What is the correct way to retrieve the image and then convert it in binary to finally store it on database? -
No migrations to apply while in makemigrations migrations are shown
Even When there are migrations to apply when making the command migrate it shows no migrations to apply -
CORS policy: Response to preflight request doesn't pass access control
Here I'm trying to run this code but i am getting CORS error when integrated with angular. this is my source code Settings.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'webapp', 'rest_framework', 'knox', 'django_rest_passwordreset', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] ALLOWED_HOSTS=['*'] CORS_ORIGIN_ALLOW_ALL = True I'm adding all of these but I'm getting same error while running. Tell me the answer -
Django dynamic folder name based on id/username when uploading image
Good day SO. I want to make my folder name(s) to be renamed based on the ID/username of the uploader. My setup is as follows: class Account(AbstractBaseUser): username= models.CharField(...) # As per our setup, user cant enter their own username but will be auto created based on a separate py file on my view during registration ... class Type01Account(models.Model): account = models.OneToOneField(Account, on_delete=models.CASCADE) ... imgPath = "" images= models.ImageField(upload_to=imgPath, null=False, blank=False) How should I assign imgPath? Should I assign it on models or on view? If so, how should I save it? -
Having a unqiue counter per User for a different model in Django
I would like to know what the best way to have a model Receipt where the model has an ID field that is unique to each Django User, that won't have issues with asynchronous requests. There is still a separate main ID field added by default, but I would like to have a separate ID for the receipts so that I can display this ID for each User so that their receipt numbers start from 1 when they go to their receipt list. class Receipt(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) employee = models.CharField(max_length=255) date = models.DateTimeField() txn_type = models.CharField(max_length=8) total = models.DecimalField(max_digits=10, decimal_places=2) correction = models.ForeignKey( ReceiptCorrection, on_delete=models.PROTECT, default=None, null=True I understand you can check the last number and then just increment by one, but won't that have issues if two computers are running the same user and they both make a receipt at the same time? I appreciate any help with this. Thank you!