Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Queue in django/python
I have developed a django REST API. I send request/data to it to perfrom a task and it does it nicely. Though, In a way, I can send it multiple request/data to perfrom the task on each of them. The issue is that server where the task gets performed has limited memory and I need to perform these task one by one. So, I am thinking to have a queue system at django pipeline which can maintain the reqeust on hold till the task in front of the queue is done. I am not sure if I am on right path, but not sure if celery is the option to solve my issue? It seems a simple task and I didnt understand if celery is what i need. Can you point me what should be looking at? -
How to send scheduled email with Crontab in Django
I like to send scheduled emails in Django with Crontab. I made a very simple app to test how can I send an email in every minutes (just for testing purposes). I think I am doing something wrong, because I can't get the mails. users/cron.py from django.core.mail import send_mail def my_scheduled_job(): send_mail( 'subject', 'Here is the message.', 'something@example.com', ['me@gmail.com'], fail_silently=False, ) print('Successfully sent') settings.py CRONJOBS = [ ('*/1 * * * *', 'users.cron.my_scheduled_job') ] I added the job like this: python3 manage.py crontab add then python3 manage.py runserver My mailing server configured fine, every other emails are sent, but I can't get these emails, nothing happens. I don't like to use Celery or Django Q. -
how update MQTT data in django template
I'm using paho-MQTT and I can receive messages and I can display the data in a template(html), but I can't update the message in realtime in the template(html). I want to update the value in the template when I get a new message from the mosquitto/topic. from django.shortcuts import render import paho.mqtt.client as mqtt import json valor_mqtt = 0 def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) client.subscribe("mhub/hr") def on_message(client, userdata, msg): global valor_mqtt valor_mqtt = (msg.payload) print(valor_mqtt) def print_on_m(request): global valor_mqtt message = str(valor_mqtt) return render(request, 'home/index.html',{'context':message}) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("mqtt.eclipseprojects.io", 1883, 60) I'm passing print_on_m in urls.py to use {{context}} in home/index.html to show the data PS: I don't want to use functions like "setInterval(function() {" or ".load(window.location.href" to update part of the web page after some time, I want to update only when I get new message from mosquitto/topic -
Get_queryset() missing 1 required positional argument: 'request' when i'm trying to filter objects by logged in user
I'm trying to list all facilties owned by a user on a "facility list page" using the django rest framework and react. I tried the following to make this happen (admin_uid is a one to one field of the user owning the facility): class FacilityListView(ListAPIView): permission_classes = [AllowAny] serializer_class = FacilitySerializer def get_queryset(self, request): return Facility.objects.filter(admin_uid=self.request.user) I'm getting this error: django | queryset = self.filter_queryset(self.get_queryset()) django | TypeError: get_queryset() missing 1 required positional argument: 'request' This is what i had before which worked but listed all facilities: class FacilityListView(ListAPIView): permission_classes = [AllowAny] serializer_class = FacilitySerializer def get_queryset(self): return Facility.objects.all() -
Why Django doesn't have an on_update=models.CASCADE option?
My question comes from a situation where I want to emulate the ON UPDATE CASCADE in SQL (when I update an id and I have a Foreignkey, it is going to be automatically updated) in Django, but I realized that (apparently) doesn't exist a native way to do it. I have visited this old question where he is trying to do the same. My question is: Why Django doesn't have a native option? Is that a bad practice? If so, why? Does that bring problems to my software or structure? Is there a simple way to do this? Thanks in advance! -
How to use custom labels from Django models.Choices field together with enum.auto?
Before Django v3.0 I used to use enum.Enum together with enum.auto (see reference) for my choices fields. The reason was mostly so I could use my enumeration class for type hints and the auto enforced the usage of the enumeration class instead of instead of using the constant value in code. However Django v3.0+ introduced the enumeration types which is similar to the enum module but with some interesting features. I'd like to use it together with enum.auto but wasn't able so far. The further I got was to something like this: class MyChoices(models.IntegerChoices, Enum): FIRST = auto() SECOND = auto() THIRD = auto() The enumeration values and the auto-generated labels are correct: MyChoices Out[13]: <enum 'MyChoices'> MyChoices.choices Out[14]: [(1, 'First'), (2, 'Second'), (3, 'Third')] MyChoices.labels Out[15]: ['First', 'Second', 'Third'] MyChoices.values Out[16]: [1, 2, 3] MyChoices.FIRST Out[17]: <MyChoices.FIRST: 1> The issue is when I try to define custom labels: class MyChoices(models.IntegerChoices, Enum): FIRST = auto(), '1st' SECOND = auto(), '2nd' THIRD = auto(), '3rd' Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3441, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-20-cf882f261e5f>", line 1, in <module> class MyChoices(models.IntegerChoices, Enum): File "/usr/local/lib/python3.8/site-packages/django/db/models/enums.py", line 28, in __new__ cls = super().__new__(metacls, classname, bases, classdict, **kwds) … -
Django 3.2 view fails when filtering on Boolean field
I'm currently upgrading a Django project from 2.2 to 3.2, but I'm getting an error from SQL Server when trying to load a View: ProgrammingError at /my/django/url ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]An expression of non-boolean type specified in a context where a condition is expected, near ')'. (4145) (SQLExecDirectW)") I have a queryset that is filtering on a Boolean Field ('islead'), the queryset contains .filter(islead=True), however when I load the View, I can see from Django debug toolbar that the SQL query doesn't include "WHERE islead = TRUE", it only has "WHERE islead" with no condition. This works fine in Django 2.2. Here is an extract of my code: models.py: class LecturerCourseYear(models.Model): ay = models.IntegerField(db_column='AY', primary_key=True) code = models.CharField(db_column='Code', max_length=12) lecturer = models.ForeignKey('Lecturers', models.DO_NOTHING, db_column='lecturer', max_length=12) islead = models.BooleanField(db_column='IsLead') views.py: def edit_course(request, code, ay): primary_lecturer_response = LecturerCourseYear.objects.filter(ay=ay, code=code, islead=True).order_by('position') initialData = {'primary_lecturer': ','.join([lecturer.lecturer.id for lecturer in primary_lecturer_response]), form = editCourseForm(initial=initialData) return render(request, 'courses/edit-course.html', {'form': form}) -
Django S3 file to InMemoryUploadedFile
There is a way to convert or use S3 file as a InMemoryUploadedFile : For example i want to get my file from S3 using storage : image = default_storage.open('example.png', 'r') Then convert it to an InMemoryUploadedFile in order to use it in my Serializer : image_temp = InMemoryUploadedFile(image, 'image_example', 'example.png', 'png', None, None) Thanks. -
Integration of paypal with android app using django
how create Paypal payment gateway for an app which used a volley and has Django on server-side . i need views.py for an app on server-side and full source code. -
Celery issue in a kubernetes pod
While trying to create a super user for this application using manage.py I am getting the following error. root@taiga-back-675fcdbd67-rx552:/taiga-back# ./manage.py createsuperuser Username: testuser Email address: testuser@abc.com Password: Password (again): Traceback (most recent call last): File "/opt/venv/lib/python3.7/site-packages/kombu/utils/functional.py", line 30, in __call__ return self.__value__ AttributeError: 'ChannelPromise' object has no attribute '__value__' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/venv/lib/python3.7/site-packages/amqp/transport.py", line 173, in _connect host, port, family, socket.SOCK_STREAM, SOL_TCP) File "/usr/local/lib/python3.7/socket.py", line 752, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno -5] No address associated with hostname This is the CELERY Configuration. Sorry, it's Nano This application running as a pod in a Kubernetes cluster. I searched for this but could not find anything meaningful to begin troubleshooting. Any hints/answer would help. -
Django. How can i bypass a form page, right after login if the user already completed it
I have a sign up form which does the user registration part and after that u are prompted to the login page. After you login, you are prompted to another form which gathers additional info about the user. How can i bypass this form if the user already completed it ? -
Django Makemigrations No changed detected
app/models: from django.db import models # Create your models here. class Blogpost(models.Model): topic = models.TextField(null=True) descrip = models.TextField() fd = models.CharField(max_length=150) ->I installed app already INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website.apps.SbuiltConfig', 'rest_framework', ] ->I Register models already from django.contrib import admin from models import Blogpost, Blog, testblog # Register your models here. admin.site.register(Blogpost) but it's still no change detected -
How i can to filter queryset by current user in django rest framework
class SalonCarDetailsSerializer(serializers.ModelSerializer): salon = PrimaryKeyRelatedField(queryset=Salon.objects.filter(owner=?)) class Meta: model = SalonCarDetails fields = ["salon", "car", "price", "number_of_cars"] CurrentUserDefault() doesn't works -
how to split content from RichTextField into 2 columns in Django
I have a model where I am using RichTextField (CKEditor) and I'd like to know if there is any way to spit the content in the HTML file into 2 columns in the same way you do it with columns in the Bootstrap grid system. models.py class Test(models.Model): ... test_content = RichTextField(blank=True) test.html <div class="row"> <div class="border bg-grey text-white rounded"> <h2 class="fw-bold text-uppercase">Test header</h2> <div>{{test.test_content|safe}}</div> </div> </div> The content now is displayed in 1 column and it is not a list so I cannot implement col-6 or something similar because it is not a loop. Any ideas or tips on how can this be implemented? -
How to remove by default clear checkbox in Django
As you can see there is clear checkbox on the page I don't want to clear the image and keep the default one But Django is adding this automatically. Is there any way remove it or select it inside code to apply operations on it. -
convert 20 Apr 2022 to 2022-04-20 using python3
Given a string like this: 20 Apr 2022 How do I convert it to: 2022-04-20 Using python 3? -
Django render playbook output to template realtime
i am struggling to get real time output of my django webapp. in a nutsshell a request from web client triggers an ansible playbook but i am struggling to capture the output of the ansible playbook and render it to the template. any suggestions (minimal config change) is welcome and anticipated. -
Convert 20 Apr 2022 to 2022-04-20 format using python3
here in my project i am using python3 and Django3 When fetching the date from the html template i am getting date in the format of 20 Apr 2022 now i want to change this format to 2022-04-20 using python3 -
how can i get rid of these errors when trying to start a Django project?
i am trying to start a django project using the django-admin startproject but it keeps bringing this error Traceback (most recent call last): File "C:\Users\GAbraham.AECIGROUP\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in run_module_as_main return run_code(code, main_globals, None, File "C:\Users\GAbraham.AECIGROUP\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in run_code exec(code, run_globals) File "C:\Users\GAbraham.AECIGROUP\AppData\Local\Programs\Python\Python310\Scripts\django-admin.exe_main.py", line 7, in File "C:\Users\GAbraham.AECIGROUP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management_init.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\GAbraham.AECIGROUP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management_init.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\GAbraham.AECIGROUP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\GAbraham.AECIGROUP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "C:\Users\GAbraham.AECIGROUP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\startproject.py", line 20, in handle super().handle('project', project_name, target, **options) File "C:\Users\GAbraham.AECIGROUP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\templates.py", line 117, in handle django.setup() File "C:\Users\GAbraham.AECIGROUP\AppData\Local\Programs\Python\Python310\lib\site-packages\django_init_.py", line 16, in setup from django.urls import set_script_prefix File "C:\Users\GAbraham.AECIGROUP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls_init_.py", line 1, in from .base import ( File "C:\Users\GAbraham.AECIGROUP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\base.py", line 8, in from .exceptions import NoReverseMatch, Resolver404 File "C:\Users\GAbraham.AECIGROUP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\exceptions.py", line 1, in from django.http import Http404 File "C:\Users\GAbraham.AECIGROUP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\http_init_.py", line 5, in from django.http.response import ( File "C:\Users\GAbraham.AECIGROUP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\http\response.py", line 13, in from django.core.serializers.json import DjangoJSONEncoder File "C:\Users\GAbraham.AECIGROUP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\serializers_init_.py", line 23, in from django.core.serializers.base import SerializerDoesNotExist File "C:\Users\GAbraham.AECIGROUP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\serializers\base.py", line 6, in from django.db import models File "C:\Users\GAbraham.AECIGROUP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models_init_.py", line 3, in from django.db.models.aggregates import * # NOQA File "C:\Users\GAbraham.AECIGROUP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\aggregates.py", line 5, in from django.db.models.expressions import Case, Func, Star, When File "C:\Users\GAbraham.AECIGROUP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\expressions.py", line 486, in class TemporalSubtraction(CombinedExpression): File … -
Django stand alone app creating dist fails because of directory structure
I am using the online Django documentation on creating reusable apps to create a resuable app, using Django 3.2 I have created an application Foo, that I want to pull out as a standalone application. My standalone application structure is as follows: core/ core/ settings.py # ... django-foo/ LICENSE README.rst MANIFEST.in setup.py setup.cfg docs/ foo/ static/ templates/ foo/ css/ js/ img/ templatetags/ __init__.py helpers.py tests/ views/ common.py views_one.py views_two.py # ... MANIFEST.in include LICENSE include README.rst recursive-include foo/static * recursive-include foo/templates * recursive-include foo/templatetags * recursive-include foo/tests/views * recursive-include docs * setup.py from setuptools import setup setup() When I run the following command: python setup.py sdist, I notice the following (error?) in the console output: 'foo/tests/views.py' not a regular file -- skipping When I run the following command: python setup.py bdist_wheel, I notice the following error in the console output: 'error: can't copy 'foo/tests/views.py': doesn't exist or not a regular file And the build fails. How do I resolve this issue (ideally, whilst keeping my directory structure with the partitioned view files)? -
How to generate a n-sized random float array that sums up to m
I need to write a function who takes two arguments. First argument is number of floats and second is their sum. I need to generate random floats(n) whose sum would be equal to m. def random_list(n, m): #n is the number of floats #m is the target sum #(Input) n = 4 m = 10 #Output n = [2.2 + 4.5 + 5.0 + 3.3] m = 15 -
Django Admin OSMWidget not displaying map
On the project I am currently working I use the Django Admin to easily set a Point. At the beginning of the project, the map displayed using the OSMWidget was perfectly displayed (I use this widget as the default one was displaying a terrain map and I want to display cities). Two or three weeks ago I logged in at the Admin page and I saw that the map was crashing. I am not aware of any update of Django or requirements.txt or anything but the map suddenly does not work. Here is how I see the map. And here you can see what happen with network when I load the page: It seems something related with OpenStreetMaps but idk how to solve it, as when debugging the server, it does not display any error. Here the admin code: from django.contrib.gis import admin from django.contrib.gis.db import models from django.contrib.gis.forms.widgets import OSMWidget class RestaurantAdmin(admin.OSMGeoAdmin): formfield_overrides = { models.PointField: {'widget': OSMWidget}, } fieldsets = [ ('Location', {'fields': [ ('address', 'city', 'postal_code', 'country'), 'coordinates' ]}), ] Does anyone know how to fix it or if can I use another type of map? Thanks in advance. -
Django/Python: Merge same type of filter calls?
I've got this code: report = { 'period': { 'actions': [a.for_report() for a in team_actions.filter(type=Action.ACTION)], 'events': [e.for_report() for e in team_actions.filter(type=Action.EVENT)], 'timeskip': [t.for_report() for t in team_actions.filter(type=Action.TIMESKIP)], 'buysell': [b.for_report() for b in team_actions.filter(type=Action.BUYSELL)], } And as you can see I'm pretty much doing the same thing 4 times, just that in the end I filter for a different type of Action. So I wanted to improve my queries and was wondering if there is a clever solution for doing things like that, which is also more performant? Thanks for any answers! -
django-import-export requires apache reload each time to import from csv
django-import-export v.2.5 was integrated to django 3.2.I was able to import it sometimes but it failed at other times skipping the records even if they were absent in the db table. After reloading apache web server, I was able to import from CSV. What is the issue? Currently I have upgraded to 2.8 version. Need to test its working with apache2. Any issue? -
Optimization of queries to the Django ORM database
It is necessary to optimize database queries, i.e. reduce their number to a minimum. Now there are 2 requests to receive a post, as django-debug-tools shows me, and to receive a comment depends on the nesting, 1 level 2 requests and the higher the level the more requests, i.e. +1 per level. How to reduce them? #models.py from django.db import models from mptt.fields import TreeForeignKey from mptt.models import MPTTModel class Post(models.Model): author = models.CharField( max_length=122, null=True, blank=True, default='Anonymous', ) title = models.CharField( max_length=200, null=True, blank=True, default='Not title' ) text = models.CharField( max_length=200 ) published = models.DateTimeField(auto_now_add=True) class Comment(MPTTModel): parent = TreeForeignKey( 'self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') title = models.CharField( max_length=200, null=True, blank=True, default='Not title' ) author = models.CharField( max_length=122, null=True, blank=True, default='Anonymous', ) post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='comments' ) published = models.DateTimeField( auto_now_add=True ) #serializers.py from django.conf import settings from mptt.templatetags.mptt_tags import cache_tree_children from rest_framework import serializers from post.models import Comment, Post class CommentSerializer(serializers.ModelSerializer): children = serializers.SerializerMethodField('get_children') def get_children(self, comment): max_level = settings.MAX_LEVEL children = comment.get_children() if all([max_level is not None, comment.get_level() >= max_level]): return [] return CommentSerializer( children, many=True ).data class Meta: model = Comment exclude = ('lft', 'rght', 'tree_id') read_only_fields = ('comments',) class PostSerializer(serializers.ModelSerializer): comments = serializers.SerializerMethodField('get_comments') …