Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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') … -
Not to render all columns in UI Django HTML Template
In my UI I can see all the columns as default. I do not want to view all the columns in my UI, how do do that? In this picture I have four columns by default I do not want to view EMAIL as the default -
Django - not able to upload files/images correctly
I am building a Django application (run in local) and I am having headaches about uploading files/pictures. I have read tons of questions/answers everywhere as well as followed the official doc, but somehow I still have problems. In models.py, I have the following: class Documents(models.Model): hkid = models.ImageField("HKID", upload_to='images/', null=False) Corresponding view in views.py: class ApplicationUploadView(LoginRequiredMixin, CreateView): model = Documents template_name = "home/application.html" fields = '__all__' success_url = reverse_lazy('completion') def form_valid(self, form): print("form is valid") //other stuff.. return super().form_valid(form) In settings.py, I have added (as explained in the docs): MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' And finally, I added this at the end of my urls.py: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) When I run the application, everything works fine - I uploade the picture in the form, and the "form is valid" is also printed on the screen. However, no picture is uploaded at all inside media/ or media/images folder. However, if I remove the two MEDIA_ROOT and MEDIA_URL lines in settings.py and I remove the "urlpatterns +=" line in urls.py, the picture instead is correctly uploaded, but in a 'images' folder (not inside media, though). However, if I try to open the picture from the admin panel, which has … -
How can I return the real user after django social-auth-app-django?
In my django project I am using django social-auth-app-django for google login to website.Everything is fine,but When user wants to login with google,if user has registired website before,I want to return this user.So ı don't want to create new user.Hox can I do that.I guess ı have to use SOCIAL_AUTH_PIPELINE but I don't know exactly this is works.Can anyone help me for that?? -
i want to integrate my android studio app with paypal restapi using django server
i want to integrate my app with paypal using Rest-API .I am using django on server-side .i need server-side implementation code to integrate my app? -
Serving file asyncronously with Django and uvicorn
I have a Django view that serves the content of a file. The Django application was running with WSGI until recently. This worked fine. Then I adapted my application to use ASGI running uvicorn. The file serving is now broken as it seems to loose the connection. How can I serve the file asynchronously with Django and uvicorn? Current view: class FileServeView(View): def get(self, request, *args, **kwargs): # ... return HttpResponse( FileWrapper(file_content), content_type="application/octet-stream" ) The server is throwing the following error: ERROR: Exception in ASGI application Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/uvicorn/protocols/http/h11_impl.py", line 377, in run_asgi result = await app(self.scope, self.receive, self.send) File "/usr/local/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__ return await self.app(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/uvicorn/middleware/asgi2.py", line 17, in __call__ await instance(receive, send) File "/usr/local/lib/python3.8/site-packages/channels/http.py", line 192, in __call__ await self.handle(body_stream) File "/usr/local/lib/python3.8/site-packages/asgiref/sync.py", line 382, in __call__ raise RuntimeError( RuntimeError: Single thread executor already being used, would deadlock I'm using: Django 3.2.13 uvicorn 0.17.1 channels 2.3.1 asgiref 3.5.0 -
Limit prefetch_related to 1 by a certain criteria
So I have models like these class Status(models.Mode): name = models.CharField(max_length=255, choices=StatusName.choices, unique=True) class Case(models.Model): # has some fields class CaseStatus(models.Model): case = models.ForeignKey("cases.Case", on_delete=models.CASCADE, related_name="case_statuses") status = models.ForeignKey("cases.Status", on_delete=models.CASCADE, related_name="case_statuses") created = models.DateTimeField(auto_now_add=True) class Status(models.Model): I need to filter the cases on the basis of the status of their case-status but the catch is only the latest case-status should be taken into account. To get Case objects based on all the case-statuses, this query works: Case.objects.filter(case_statuses__status=status_name) I need to get the Case objects such that only their latest case_status object (descending created) is taken into account. Something like this is what I am looking for: Case.objects.filter(case_statuses__order_by_created_first__status=status_name) I have tried Prefetch as well but doesnt seem to work with my use-case sub_query = CaseStatus.objects.filter( id=CaseStatus.objects.select_related('case').order_by('-created').first().id) Case.objects.prefetch_related(Prefetch('case_statuses', queryset=sub_query)).filter( case_statuses__status=status_name) This would be easy to solve in raw postgres by using limit 1. But not sure how can I make this work in Django ORM. -
How to debug a React.js/Django-Rest-Framework application in VS Code?
How can I do debugging in VS Code for React.js/Django-Rest-Framework Application. I'm to do debugging in solo django application but When I use react as frontend, it not stop at breakpoint. -
Django Management Command not workingcif i run for loop
I write this management command but not working from django.core.management.base import BaseCommand from name.models import ProductName class Command(BaseCommand): def handle(self, *args, **options): ids=id[2704, 2709, 2711, 2824, 2825, 2826, 3101, 3102, 3437, 3438, 3439, 3440, 3441, 4256, 4257, 4258, 4260, 4261, 4262, 4263, 4264, 4265, 4266, 4424, 5125, 17315, 17320, 17322, 17328, 17345, 17356, 17375, 17386, 17390, 17415, 17425, 17437, 17443, 17445, 17447, 17451, 17454, 17515, 17519, 17525, 17604, 17610, 17624, 17627, 17634, 17636, 17642, 17648, 17656, 17659, 17680, 17690, 17694, 17700, 17704, 17721, 17724, 17734, 17737, 17744, 17746, 17749, 17752, 17767, 17780, 17786, 17792, 17798, 17801, 17813, 17837, 17839, 17851, 17853, 17863, 17881, 17919, 17925, 17945, 17947, 17952, 17955, 17976, 17986, 18016, 18018, 18022, 18030, 18040, 18046, 18055, 18066, 18072, 18108, 18155, 18163, 18173, 18188, 18205, 18211, 18221, 18234, 18247, 18260, 18273, 18294, 18297, 18321, 18519] for i in ids: name = ProductName.objects.filter(i).update(active=False) print(f"The total number of activated ProductName {name}") -
How to use forloop.counter using key and value in django template language
I have a for loop in template. But it has key and value so when I try to use {{forloop.counter0}} it counts by twos. I guess it consider keys and values while counting My code is this: {% for key,value in LANGUAGES %} <p>{{ forloop.counter0 }}</p> <p>{{ key }}</p> <p>{{ value }}</p> <br> {% endfor %} But returns: 0 en English 2 es Spanish But I need this result: 0 en English 1 es Spanish -
Processing multiple files in django filefield
I'm trying to let the user upload several files in a fileuploadfield, which are processed and stored in a database. models.py class MyModel(Model): user = ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE) title = CharField(max_length=200, default='') text = TextField(default='', blank=True, null=True) document = FileField(null=True, blank=True, upload_to="documents") forms.py class MyModelForm(ModelForm): class Meta: model = MyModel fields = [ 'document' ] labels = { 'document': 'upload documents here' } widgets = { 'document': ClearableFileInput(attrs={'multiple': True}) } views.py if form.is_valid(): counter = 0 for f in request.FILES.getlist('document'): instance = form2.save(commit=False) instance.user = request.user instance.title = counter instance.save() counter += 1 return redirect('overview', num) What happens here is that this loop keeps getting applied to only one instance for every document i upload. If I upload 3 documents, I am supposed to get three separate stored entries in the database called 0, 1, 2. But what happens is that I only get one called 2. What am I doing wrong? -
Python Django Oauth Toolkit with JWT
How can i replace random string token to JWT token in django oauth toolkit? Anyone explain to me with sample? 1 i want to be like this 2 -
How to use forloop.counter if key, value in django template language
I have a fro loop in template. But it has key,value so when I try to use {{forloop.counter}} it counts by twos. {% for job in jobs %} <p>{{ forloop.counter }}</p> <p>{{ job.title }}</p> <br> {% endfor %} Result is: 1 job1 2 job2 What I need is this: {% for job,value in jobs %} <p>{{ forloop.counter }}</p> <p>{{ job.title }}</p> <br> {% endfor %} But result is: 1 job1 4 job2 I need: 1 job1 4 job2 -
docker mysql ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
I have created a MySQL container and hope to execute shell script in the container and execute SQL statement to get the return result, which is a part of my Django project. Using docker library to create container and execute script in Python program, I get ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)。 But when I execute the same command in the shell to create the container and execute the script, there will be no error. I want to know why. Who can help me, thank you! enter image description here enter image description here -
Django sitemap url page is still showing example.com in the place of my domain, domain.com
I pushed my code to production server and updated sites in Django admin page. But when i check sitemap.xml url, its still showing with example.com domain. Tried many ways of updation, but not working. would be helpful if I get some inputs to clear the error and move forward. -
Django : Media file not found when deleting despite it's correctly written when creating (PROD)
I've been searching in vain for a long time the origin of this issue. Everything works well on development : csv file upload + deletion but in production, file is well uploaded when saving my model but it's not found when I want to delete it. views.py (file_name = sources/newone/egr-2022-light_copie.csv) os.remove(f"media/{str(flow.fl_file_name)}") settings.py. (custom settings file for prod) BASE_DIR = Path(__file__).resolve().parent.parent [...] MEDIA_ROOT = '/home/django/httpdocs/gsm2/media' MEDIA_URL = '/media/' apache conf (+ssl) [...] Alias /static /home/django/httpdocs/gsm2/static <Directory /home/django/httpdocs/gsm2/static> Require all granted </Directory> Alias /media /home/django/httpdocs/gsm2/media <Directory /home/django/httpdocs/gsm2/media> Require all granted </Directory> <Directory /home/django/httpdocs/gsm2/gsm2> [...] I have tried to : modify the path used in remove() by removing media/... without success. modify the path used in remove() by adding gsm2/in front of media/ ... uselessly. to replace my settings.py media path with MEDIA_ROOT = os.path.join(BASE_DIR, 'media')... not better Changed folder rights to 777 and ownership to 'django' ... in vain Any idea about the possible origins of my pains ?