Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can 2 urls file in the same app have the same app name in Django?
The question is honestly completely self-explanatory. Can 2 urls.py files in the same app have the same app_name in Django? -
Django - import processes breaks if multiple S3 backends configured
I have a import process that should fetch multiple S3 backends for objects. Actually the process is working fine if I just have a single s3 backend configured. As soon as I have multiple S3 backends setup to fetch data from, my whole import process fails as no entries are written to my "Files" table. I have my import process packed as a celery task, please see below: @app.task(name="Fetch Descriptor JSON", base=Singleton) @transaction.atomic def fetch_descriptors(*args, **kwargs): keys = [] urls = [] for resource in S3Backend.objects.filter(backend_type=0): endpoint = resource.endpoint bucket = resource.bucket access_key = resource.access_key secret_key = resource.secret_key region = resource.region for obj in s3_get_resource(endpoint=endpoint, access_key=access_key, secret_key=secret_key, region=region).Bucket(bucket).objects.all(): keys.append(obj.key) for key in keys: descriptor = s3_get_client(endpoint=endpoint, access_key=access_key, secret_key=secret_key, region=region).generate_presigned_url( ClientMethod='get_object', Params={'Bucket': bucket, 'Key': key}, ExpiresIn=432000, ) new_file, create = Files.objects.get_or_create(descriptor=strip_descriptor_url_scheme(descriptor), file_path=key, file_name=Path(key).name, s3_backend=resource ) urls.append(descriptor) workflow_extract_descriptors = ( group([extract_descriptors.s(descriptor) for descriptor in urls]).apply_async() ) Are there maybe any problems with my for loop construct if S3Backend.objects.filter(backend_type=0) returns more than one entry? Thanks in advance -
Creating a blockchain game integrated on the web using python
Basically i need advice on which packages / frameworks to use in order to create this. My goal is to create a sort of cards/dice game (its called orlog) and im planning to use web3 to fetch a players data from the blockchain The game is in browser as well so i dont know what to use, whether its pygame + opengl django web framework etc etc Note: the game will be online 1 vs 1 -
How can I implement a database (ER) table where the values of a foreign key depend on another foreign key within the same table? (Django, e-commerce)
Please bare with me as I am a newbie to database design. I am trying to implement an e-commerce store in Django with product variations as shown in the attached image. For the ProductVariations model/table, I would like to have a foreign key for Options (which would represent something like size) and then based on that foreign key, I would like to have another foreign key for OptionValues (e.g. small). The possible values for the latter foreign key should be limited by the former foreign key. More specifically, I want don't want the drop-down in the admin site to display "small, red, blue, 32, 33, large" when the previous foreign key was "size". In that case, I would only want it to display "small, large". How do I go about doing this? I'd be grateful for any ideas either specific to Django or just database design in general. Image of my ER model. I might consider also adding the Product relationship to the Option which would mean now the option_value depends on the option which depends on the product. -
Django - creating super user
I created the model User And i added this two lines " is_superuser=models.BooleanField(default=False) is_staff=models.BooleanField(default=False)" just to by pass the probleme and create a super user by the model not the default one but this can't be the solution to my probleme i need to create a default django super uesr from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): first_name= models.CharField(max_length=30) last_name= models.CharField(max_length=30) cin = models.IntegerField() username= models.CharField(max_length=30,unique=True) password= models.CharField(max_length=30) codeQR = models.CharField(max_length=30) poste = models.CharField(max_length=30) image = models.CharField(max_length=30) email = models.EmailField() telephone= models.IntegerField() is_superuser=models.BooleanField(default=False) is_staff=models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] class pointage(models.Model): entre = models.CharField(max_length=30) sortie = models.CharField(max_length=30) retard = models.CharField(max_length=30) absance = models.CharField(max_length=30) user = models.ManyToManyField(User) class salaire(models.Model): mois = models.IntegerField() heurs_base= models.FloatField() heurs_sup = models.FloatField() primes = models.FloatField() total = models.FloatField() user = models.ManyToManyField(User) But i get the following error PS C:\py\pointage> py manage.py createsuperuser Username: a Password: Password (again): Error: Your passwords didn't match. Password: Password (again): The password is too similar to the username. This password is too short. It must contain at least 8 characters. This password is too common. Bypass password validation and create user anyway? [y/N]: y Traceback (most recent call last): File "C:\Users\moezm\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, … -
How to connect many to many relationaship if I save them via form.save() (django)?
This link https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_many/ explains that I need to make an object of the class to save the connection. Because I have many fields in my classes I used form.save() to save them, but that doesn't fill the connection ManyToMany in the class. How to fill that field? def create(response): if response.method == "POST": if "next" in response.POST: form = CreateNewPerson(response.POST) form.save() form2 = CreateNewDog() # form doesn't have filed many_to_many to Person, but class Dog does class CreateNewDog(forms.ModelForm): class Meta: model = Dog fields = ['name','years_old', 'sex', 'blood_type', 'image'] class Dog(models.Model): owner = models.ForeignKey(Person, on_delete=models.SET_NULL, null=True) user = models.ManyToManyField(User) -
Django save a change to Database
I'm trying to update the is_admin column of the model user_profile. I've written the following code in views.py but it's not updating in the DB. How can I save the change (user_object[0].is_admin = True) to the database? def post(self, request, format=None): users_provided = request.data.get('user_ids') for each_user in users_provided: user_object = UserProfile.objects.filter(user__is_active=True, user_id=each_user) if (user_object.exists()): user_object[0].is_admin = True user_object.update() -
reques.POST.get, always returns none
I'm trying to get the value of the template's select field, using request.POST.get. But even with the correct name the value that the view receives and always None, can someone help me how to solve this? Here are the codes: view: def efetuar_pagamento(request, id_pagamento): if request.POST: objPagamento = Pagamento.objects.select_related( "Matricula", "FormaPagamento").get(pk=id_pagamento) valorPago = request.POST.get("Valor_%s" % id_pagamento, None) formaPaga = request.POST.get("Forma_%s" % id_pagamento, None) print(formaPaga, valorPago) objFormaPG = FormaPagamento.objects.get(pk=formaPaga) objPagamento.ValorParcial = valorPago.replace(',', '.') objPagamento.FormaPagamento = objFormaPG objPagamento.save() if objPagamento.ValorParcial < objPagamento.Matricula.Plano.Valor and objPagamento.ValorParcial: objPagamento.Status = "PC" elif objPagamento.ValorParcial >= objPagamento.Matricula.Plano.Valor: objPagamento.Status = "PG" Template: <div class="body table-responsive"> <table class="table table-bordered table-striped table-hover js-basic-example dataTable"> <thead> <tr> <th>Data Vencimento</th> <th>Status Pagamento</th> <th>Valor Total</th> <th>Valor Pago</th> <th>Ações</th> </tr> </thead> <tbody> {% for objPagamento in listPagamentos %} <tr> <td>{{objPagamento.DataVencimento}}</td> <td>{{objPagamento.get_Status_display}}</td> <td>{{objMatricula.Plano.Valor}}</td> <td>{{objPagamento.ValorParcial|default_if_none:"0,00"}}</td> <td> {% if objMatricula.Plano.Valor >= objPagamento.ValorParcial %} <a type="button" class="btn btn-primary waves-effect" data-toggle="modal" data-target="#id_Status_{{objPagamento.id}}" data-toggle="tooltip" data-placement="top" title="Pagar!"><i class="material-icons" >attach_money</i></a> {% else %} <a type="button" class="btn btn-success waves-effect" data-toggle="tooltip" data-placement="top" title="Liquidado!"><i class="material-icons" >price_check</i></a> {% endif %} </td> </tr> <div class="modal fade" id="id_Status_{{objPagamento.id}}" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="defaultModalLabel"> <p>Efetuar Pagamento</p> </h4> </div> <form action="{% url 'efetuar_pagamento' objPagamento.id %}" id="id_form_{{objPagamento.id}}" method="POST"> {% csrf_token %} <div class="modal-body col-xs-12"> <h4>Valor … -
How to integrate Tron (TRX) crypto currency with python ? I am confused in their code can someone please help me to understand their code
import requests url = "https://api.trongrid.io/wallet/createtransaction" payload = "{\n \"to_address\": \"41e9d79cc47518930bc322d9bf7cddd260a0260a8d\",\n \"owner_address\": \"41D1E7A6BC354106CB410E65FF8B181C600FF14292\",\n \"amount\": 1000\n}" headers = { 'Content-Type': "application/json", 'TRON-PRO-API-KEY': "25f66928-0b70-48cd-9ac6-da6f5465447c663" } response = requests.request("POST", url, data=payload, headers=headers) print(response.text) I am creating a django based app where I will accept payments in Tron My Doubt is Do I have to keep "to_address"\ and "Owner Address"\ in code Where to pass Owners address and Clients address [as they have specified in the code Owner_address but to_address means we are paying "to" (someone) so I am not sure where to pass which address.] so where to pass owner's address as it is written in code but their is also to_address so I am confused with to_address and owner_address please help me to understand this, Thank you. -
Pre-populating Selected Values in Django Admin FilteredSelectmultiple Widget
I want to be able to set some default selected users on the right side of a Django Admin FilteredSelectMultiple widget. This is my model: class UserAdminForm(forms.ModelForm): users = forms.ModelMultipleChoiceField( queryset=User.objects.all(), widget=FilteredSelectMultiple("Users", is_stacked=False)) class Meta: model = User exclude = () Is there a way to do this with JavaScript so that I don't have to hand-select these defaults each time I create a new item? -
Not showing the Form in html
This is my model class showroom(models.Model): serialno=models.IntegerField(db_index=True,primary_key=True) carname=models.CharField(max_length=50) carmodel=models.CharField(max_length=50) price=models.IntegerField() rating=models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)]) This is my forms.py class RegisterForm(ModelForm): class Meta: model = showroom fields =("__all__") views.py class carform(CreateView): model = showroom form_class=RegisterForm template_name = "carbrand/carregister.html" context_object_name='registerform' html page {% block content %} {{registerform}} {% endblock content %} It's just showing a blank screen. I have imported all the necessary classes and views. It will make this too long for you so i removed it.can anyone please tell me if anything wrong in my view/form. -
How can i implement advanced search in django?
How can i implement advanced search like the below image in Django? I want the user can selects OR/AND operator. When I searched, I don't want the page to be refresh. What is the best technique for doing that? Ajax, rest framework, or other things...? -
How to remove the querysets '< [ <]>(code markers?)' for html (Django)
Am trying to just get a list of the made up gigs, (and hopefully make them links, to view them in a different html). Page result right now looks like this; <QuerySet [<Gig: Fulltime assistent needed from fall 2021!>, <Gig: Looking for event staff!>]> I don't know how to remove queryset 'code markers(or what are they called?)'. Just want the gig names listed. How can I fix that, to just show the gig titles? This is my code: Html: <div class="col"> {% if profile %} <div class="row justify-content-between"> <div class="col-9"> <p><b>My Gigs:</b></p> <p>{{profile.my_gigs}}</p> </div> <div class="col-3"> <p class="text-center"><b>No:</b></p> <p class="text-center"> {{profile.num_gigs}}</p> </div> <br> </div> {% endif %} </div> Views: def my_gigs(request): profile = Profileuser.objects.get(user=request.user) template = 'profileusers/my_gigs.html' context = { 'profile': profile, } return render(request, template, context) def create_gig(request): profile = Profileuser.objects.get(user=request.user) template = 'profileusers/create_gig.html' context = { 'profile': profile, } return render(request, template, context) Model: def my_gigs(self): return self.gig_set.all() @property def num_gigs(self): # pylint: disable=maybe-no-member return self.gig_set.all().count() -
django api for upload is very slow
My django api is soo slow when uploading files to a server, but very fast when using it on localhost. The api is supposed to receive files and save them to disk. I am expecting uploaded files to be between 70mb to about 600mb and save them in a storage. The files are binary files with a .svo extention created by stereolabs zed camera. Running this on localhost is very fast but when I deploy it to the server is becomes incredily slow. My internet speed is around 50mbps and the test file I am using is just 69mb. It takes over 24mins to upload the file, which is unacceptable. What could be the issue with why the uploading to the server is soo slow. This is my views.py to request and create a directory and save it import os import pathlib # external libraries from django.http import JsonResponse from rest_framework.views import APIView from django.core.files.storage import FileSystemStorage # environment variables from keys import USER_DIR # this is just a directory from .env class SaveRosBag(APIView): def post(self, request, *args, **kwargs): # integer_key & timestamp integer_key = self.kwargs['integer_key'] timestamp = self.kwargs['timestamp'] # required files if "zed_svo" in self.request.FILES: zed_svo = self.request.FILES["zed_svo"] else: … -
How to start Celery Beat with Supervisor
I am working on setting up Celery Beat with Supervisord. /etc/supervisor/conf.d/website.conf: [program:website-beat] command=bash /home/david/PycharmProjects/website/config/script.sh directory=/home/david/PycharmProjects/website user=www-data autostart=true autorestart=true stdout_logfile=/home/david/PycharmProjects/website/logs/celeryd.log [program:website] command=/home/david/PycharmProjects/website/venv/bin/celery -A config worker --loglevel=INFO -n worker1@%%h directory=/home/david/PycharmProjects/website user=www-data autostart=true autorestart=true stdout_logfile=/home/david/PycharmProjects/website/logs/celeryd.log redirect_stderr=true script.sh: #!/bin/bash cd /home/david/PycharmProjects/website/ source ../venv/bin/activate celery -A config beat -l info When I run sudo supervisorctl start all I get the output: website: started website-beat: ERROR (spawn error) When I run the script.sh file or celery -A config beat -l info manually, Celery Beat works. Thoughts on why this could be happening and how to fix it? -
Django how to use blocks in templates
Basicly my django project consists of the templates with html. I would like to fill the context of the site using blocks. My problem is that I would like to send the block to sidebar and the base part of the page from application's .html files. Templates: sidebar.html footer.html header.html base.html In my base.html I use: {% include 'partials/_sidebar.html' %} {% block content %}{% endblock %} in my sidebar.html I use {% block sidebar %}{% endblock %} and in my Application index.html i try to use: {% extends 'base.html' %} {% load static %} {% block content %} <h1>Home Page</h1> {% endblock %} {% block sidebar %} <div class="bg-white py-2 collapse-inner rounded"></div> <h6 class="collapse-header">Custom Components:</h6> <a class="collapse-item" href="{% url 'veggies' %}">veggies</a> <a class="collapse-item" href="{% url 'fruits' %}">fruits</a> </div> {% endblock %} But it is obviously not working. The starting page triggers app/index.html with a view. How to workaround such a problem? [i cant add post][1] [1]: https://i.stack.imgur.com/FV3Co.png -
I could not upload on wagtail admin when my project was deployed to Heroku
When I uploaded image files on wagtail, although it is going well to read image title but images itself was destroyed. so the titles is showed on the display of both admin and user side. I browsed through some blogs and websites on media and static, but this problem has not been resolved for almost three days. Development environment python==3.7.3 Django==3.2.6 gunicorn==20.1.0 psycopg2==2.9.1 wagtail==2.14 whitenoise==5.3.0 DB == postgres server == Heroku stack-18 my try and error ①added the follow code to urls.py python + static(settings.STATIC_URL, document_root=settings.STATICFILES_DIRS) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ②changed like follow application = get_wsgi_application() application = DjangoWhiteNoise(application) ↓ application = Cling(get_wsgi_application()) related code (those are possible to relate into this problem) #production.py from __future__ import absolute_import, unicode_literals import dj_database_url import os from .base import * #省略 STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' COMPRESS_OFFLINE = True COMPRESS_CSS_FILTERS = [ 'compressor.filters.css_default.CssAbsoluteFilter', 'compressor.filters.cssmin.CSSMinFilter', ] COMPRESS_CSS_HASHING_METHOD = 'content' #省略 #urls.py urlpatterns = [ path('django-admin/', admin.site.urls), path('admin/', include(wagtailadmin_urls)), ] + static(settings.STATIC_URL, document_root=settings.STATICFILES_DIRS) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #wsgi.py import os from dj_static import Cling from django.core.wsgi import get_wsgi_application application = Cling(get_wsgi_application()) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "squjap.settings.production") #base.py MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', ] STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(PROJECT_DIR, 'static')] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = … -
Django ModelAdmin get_urls not registering correctly
I'm trying to add a custom url and page to use to display certain data on the admin side of Django for a model of mine. Here is my code in admin.py class AdminUserEventHistory(admin.ModelAdmin): def get_urls(self): # get the default urls urls = super().get_urls() # define urls my_urls = [ path('userhistory/<int:pk>/>/', self.admin_site.admin_view(self.admin_user_event_view)) ] # make sure here you place the new url first then default urls return my_urls + urls def admin_user_event_view(self, request): context = {} context['history'] = None return HttpResponse('Success!') Then towards the bottom I register it with admin.site.register(EventAttendee, AdminUserEventHistory) The url should be /admin/events/eventattendee/userhistory/1/ if i'm not mistaken as I want it to take in the primary key of the user so I can pull info based on the user id. Sadly I am getting the following error. Event Attendee with ID “userhistory/1” doesn’t exist. Perhaps it was deleted? I do have two test records in that table and able to display them with the /admin/events/eventattendee/2/change. Did I miss something? This is all based on the Django documentation for 3.2 found here -
Django Circular Import Issue
so my django project was working completely fine and everything worked. I wanted to rename an app something else so I did and updated all the associated files in including the app.py config file. I also cleared the database and removed all migration files from each app. Ever since then I have never been able to finish makemigrations onto my apps. I even recreated the app I renamed, by doing django-admin startapp "appname" and then copied the contents of models.py admin.py, etc over to see if I somehow cause an internal issue but I just can't figure out what's going on?. I did manage to get all the makemigrations to success for all apps including the one I remade when I removed this (below) from another apps admin.py file # accounts/admin.py class SigBotSettingsInLine(admin.StackedInline): model = SigBotSettings @admin.register(Bot) class BotAdmin(admin.ModelAdmin,): ... inlines = [SigBotSettingsInLine] but in the end the python manage.py migrate, still Failed. If someone would help it would be highly appreciated. Here is the error-code: (dguacENV) PS C:\Users\Admin\Desktop\djangoProjects\dguac> python manage.py makemigrations accounts Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Admin\anaconda3\envs\dguacENV\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File … -
How to run periodic task using crontab inside docker container?
I'm building Django+Angular web application which is deployed on server using docker-compose. And I need to periodically run one django management command. I was searching SO a bit and tried following: docker-compose: version: '3.7' services: db: restart: always image: postgres:12-alpine environment: POSTGRES_DB: ${DB_NAME} POSTGRES_USER: ${DB_USER} POSTGRES_PASSWORD: ${DB_PASSWORD} ports: - "5432:5432" volumes: - ./db:/var/lib/postgresql/data api: restart: always image: registry.gitlab.com/*******/price_comparison_tool/backend:${CI_COMMIT_REF_NAME:-latest} build: ./backend ports: - "8000:8000" volumes: - ./backend:/code environment: - SUPERUSER_PASSWORD=******** - DB_HOST=db - DB_PORT=5432 - DB_NAME=price_tool - DB_USER=price_tool - DB_PASSWORD=********* depends_on: - db web: restart: always image: registry.gitlab.com/**********/price_comparison_tool/frontend:${CI_COMMIT_REF_NAME:-latest} build: context: ./frontend dockerfile: Dockerfile volumes: - .:/frontend ports: - "80:80" depends_on: - api volumes: backend: db: Dockerfile (backend): FROM python:3.8.3-alpine ENV PYTHONUNBUFFERED 1 RUN apk add postgresql-dev gcc python3-dev musl-dev && pip3 install psycopg2 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ ADD entrypoint.sh /entrypoint.sh ADD crontab_task /crontab_task ADD run_boto.sh /run_boto.sh RUN chmod a+x /entrypoint.sh RUN chmod a+x /run_boto.sh RUN /usr/bin/crontab /crontab_task RUN pip install -r requirements.txt ADD . /code/ RUN mkdir -p db RUN mkdir -p logs ENTRYPOINT ["/entrypoint.sh"] CMD ["gunicorn", "-w", "3", "--timeout", "300", "--bind", "0.0.0.0:8000", "--access-logfile", "-", "price_tool_project.wsgi> crontab_task: */1 * * * * /run_boto.sh > /proc/1/fd/1 2>/proc/1/fd/2 run_boto.sh: #!/bin/bash -e cd price_comparison_tool/backend/ python manage.py boto.py But when I … -
react doesnt see django localhost when loading images
Name: {item.name} <img src={item.photo} alt="description "></img> json: { "id": 9, "name": "name", "photo": "http://127.0.0.1:8000/media/image.jpg", } item.photo is loaded from django rest framework api and it returns: GET http://127.0.0.1:8000/media/image.jpg 404 (Not Found) ,item.name works normally. When i cut off "http://127.0.0.1:8000" from json image is displaying. How to reapair that? -
Django Get image from s3 bucket if image source is stored in a database
I have a model where users upload pictures to an s3 bucket. class Curso(models.Model): titulo = models.TextField() foto = models.ImageField(upload_to='media/cursos') #this goes to mybucket/media/cursos alt = models.TextField() ... It uploads fine to the s3 bucket but the source to the images gets stored in the database like "media/cursos/theimage.jpg" And I would like to display the images from the objects in a template like this <img class='curso__tarjeta--imagen' loading="lazy" src="{{curso.foto}}" alt={{curso.alt}}"> But it doesn't work because the path is not the whole path my s3 bucket My static tag is pointing to my s3 bucket. My question is: is there a way to do something like this -> {% load static %} <img class='curso__tarjeta--imagen' loading="lazy" src="{%static%}{{curso.foto}}" alt={{curso.alt}}"> I'm trying like that but it doesn't work! What should I do? Help! And thank you in advance -
DRF Pagination page_size not working with ModelViewSet
I am trying to use ModelViewSet and PageNumberPagination together but can't seem to get page_size working. I have set my size to 200 but it lists 200+ items always. Here is my code snippet: class ExamplePagination(pagination.PageNumberPagination): page_size = 200 max_page_size = 200 class VideosViewSet(viewsets.ModelViewSet): parser_classes = (FormParser, JSONParser) serializer_class = VideoSerializer pagination_class = ExamplePagination queryset = Video.objects.all() @swagger_auto_schema(responses={200: VideoSerializer}) def list(self, request): """ Request to list all videos """ queryset = Video.objects.all().order_by("-published_at") if queryset.exists(): page = self.paginate_queryset(queryset) if page is not None: serialized = VideoSerializer(queryset, many=True) return self.get_paginated_response(serialized.data) return Response(status=http_status.HTTP_404_NOT_FOUND) I tried everything from custom mixins to setting the page size in settings.py Here is my settings.py as well REST_FRAMEWORK = { "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination", 'PAGE_SIZE': 200, } -
Django serialize object return array
Django serialize object return an array, and i cant get it in template with js my view.py: def MyExempleView(request): data = serializers.serialize("json", myModel.objects.all()) context = { "data" : json.loads(data) } return render(request, 'consulta/myTemplateExemple.html', context=context) my template: {{ data|json_script:"data" }} if ($("#data").length) { var data= JSON.parse(document.getElementById('data').textContent); } my result exemple: "[{"key": "value"}, {"key2": "value2"}]" -
Django API for upload taking to long to upload files
I am working on a django rest api to upload 3 files and save it to disk. The files are [file.svo, file.db3 and file.yaml]. The code below works fine and fast when I test it locally. However, when I put it on a server the files it takes a really long time to upload the files. When I comment out the upload and saving the file.svo part from the code the upload run very fast. # in built libraries import os from time import sleep from pathlib import Path # external libraries import requests from django.http import JsonResponse from rest_framework.views import APIView from django.core.files.storage import FileSystemStorage # environment variables from keys import USER_DIR #this is a directory class SaveRosBag(APIView): def post(self, request, *args, **kwargs): # integer_key & timestamp integer_key = self.kwargs['integer_key'] timestamp = self.kwargs['timestamp'] # required files if "db3_file" in request.FILES: db3_file = self.request.FILES["db3_file"] else: return JsonResponse({"error":"KeyError [db3_file]"}) if "yaml_file" in request.FILES: yaml_file = self.request.FILES["yaml_file"] else: return JsonResponse({"error":"KeyError [yaml_file]"}) if "svo_file" in request.FILES: svo_file = self.request.FILES["svo_file"] else: return JsonResponse({"error":"KeyError [svo_file]"}) # make directory if it doesn't exit Path(os.path.join(USER_DIR, str(integer_key), str(timestamp), 'chdir') ).mkdir(parents=True,exist_ok=True) # define paths svo_folder = os.path.join(USER_DIR,str(integer_key),str(timestamp)) yaml_db3_folder = os.path.join(ride_folder,'chdir') # saving rosbag save_db3 = FileSystemStorage(location=yaml_db3_folder) save_db3.save(db3_file.name, db3_file) # …