Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Django smat_selects
I have been trying to get around to populating a dependent field based upon a foreign key field in my app. After trying to find a way to do it without resorting to additional (3rd party) installation realized that currently no native solution is there (yet). Then I came across this. For this I carried out the steps as explained in their doc: Installed django-smart-selects-1.5.4 Added smart_selects to the settings.py under INSTALLED_APP. Also added USE_DJANGO_JQUERY = True in the settings.py file. Added the following path to project urls.py path('chaining/', include('smart_selects.urls')), Create the following objects: Models.py class Continent(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Meta: ordering = ['name'] class Contry(models.Model): continent = models.ForeignKey(Continent, on_delete=models.CASCADE) name = models.CharField(max_length=255) def __str__(self): return self.name class Meta: ordering = ['name'] class Location(models.Model): continent = models.ForeignKey(Continent, on_delete=models.CASCADE) contry = ChainedForeignKey( Contry, chained_field="continent", chained_model_field="continent", show_all=True) city = models.CharField(max_length=50) Admin.py class ContinentAdmin(admin.ModelAdmin): list_display = ('name',) class ContryAdmin(admin.ModelAdmin): list_display = ('name', 'continent') class LocationAdmin(admin.ModelAdmin): list_display = ('city', 'continent', 'contry') fields = ('city', 'continent', 'contry') admin.site.register(Continent, ContinentAdmin) admin.site.register(Contry, ContryAdmin) admin.site.register(Location, LocationAdmin) However when I try it in the Django Admin interface, I get to see all the values of field contry. (Kindly see the image). I have also … -
Django, Cant give kirilic names for files in forms slugfield
I made a simple form for upload images and give it names. It works ok if i give names for files in my slugfield on english, but if i using russian for example, ive got an error: local variable 'obj' referenced before assignment Cant understand why it happening. The same thing if i dong give any name to file. my views.py def index(request): if request.method == "POST": form = InputForm(request.POST,request.FILES) if form.is_valid(): slu = request.POST['slugf'] pic = request.FILES['imagef'] obj = image.objects.create( slug = slu, image = pic ) return redirect('main:detail', pk=obj.pk) else: form = InputForm() return render(request, 'main/index.html', {'form':form,}) Models.py from django.db import models class image(models.Model): slug = models.SlugField(max_length=20, blank=True) image = models.ImageField(upload_to="media") class Meta: verbose_name = 'Картинки' verbose_name_plural = 'Картинки' def __str__(self): return self.slug Forms.py from django import forms class InputForm(forms.Form): slugf = forms.SlugField(required=False, widget=forms.TextInput(attrs={'maxlength':'30', 'id':'slug'}),) imagef = forms.ImageField(widget=forms.FileInput(attrs={'id':'image'}), required=True) form in template <form method="POST" enctype="multipart/form-data" id='upl_form'> {% csrf_token %} <p class='v_class'>Название картинки: {{form.slugf}}</p> <p class='v_class'>Загрузите изображение: {{form.imagef}}</p> <p class='v_class'><button type='submit' class="upl_button">Сжать</button></p> </form> I also tryed change my view from slu = request.POST['slugf'] to slu = form.cleaned_data, but got same result. -
Python refresh sqlite3 connection to retrieve latest values
I have a Djanjo application which allows users to enter data which is submitted to a database. This database is immediately accesed via python scripts running on the same machine. Scenario User logs in Django website from Raspberry Pi (RPi) User enters desired data. Data submitted to database. User pushes push button connected to RPi, which prompts database query. Separate python scripts perform calculations based on user input. My problem is that if step 4 is performed immediately after step 3, the query does not get the latest data entered by the user, but previous data already stored in the database. If the user presses the push button, 30 seconds later, then, the query will be performed succesfully. My code to get latest data from database: conn = sqlite3.connect('Line3_Data.db') c = conn.cursor() c.execute("SELECT tact FROM LineOEE03 ORDER BY tact desc limit 1") current_tact = c.fetchone() tact ----------------- 45 <- old value retrieved 60 <- new value from step 3 not retrieved 60 <- new value from step 3 not retrieved Is there any way to refresh the connection to make sure that only the very latest values are retrieved? -
Django custom template tag
I have defined a custom template tag, in a file called custom_tags.py: from django.conf import settings from django import template register = template.Library() @register.simple_tag def currencysymbol(): if settings.LANGUAGE_CODE == 'en-gb': return '£' else: return 'unknown' Which is referenced in a template: {% load custom_tags %} {{ currencysymbol }} The problem, is that it doesn't render. It is certainly loading the library, as I modified the load to tag to {% load foo %} and it correctly told me that this library does not exist, and listed 'custom_tags' as one of the available options. However, {{ currencysymbol }} renders to nothing at all. To ensure that it wasn't my function, I modified it to simply return a string (without the if/else and the settings. stuff), but it still rendered nothing. I believe that I have followed the docs, so I'm not sure what's happening. The page renders without errors, but my tag is simply not there. -
Get Live console output/
I have a button when pressed calls a django view which in turn execute a python function which has multiple print statements. Now is there any way that I can get live print statements as they execute in the httpresponse on the same page as a popup or some other way and not as a combined print statement in a single httpresponse. For example: HTML Code <a href="{% url 'execute_case' 0 %}" class="btn btn-primary" >Test live output</a> Django View def testing_live_output(): print "1" time.sleep(1) print "2" time.sleep(1) print "4" time.sleep(1) print "4" def execute_case(request,n): if(n==0): with Capturing() as output: testing_live_output() return HttpResponse(output) Capturing is a class use to caputre output in the function class Capturing(list): def __enter__(self): self._stdout = sys.stdout sys.stdout = self._stringio = StringIO() return self def __exit__(self, *args): self.extend(self._stringio.getvalue().splitlines()) del self._stringio # free up some memory sys.stdout = self._stdout Code to Capturing class found from here -
Where do print statements from Django app go?
I have some debugging statements that I need to print out from my Django out, but I cannot find which file to look for them. They do not appear in the access logs or the error logs. Where can I find the file which they appear? -
Django-templates: Concatenate string variables with strings in with block
So I'm looking to do something like this to keep things DRY: {% with share_text=author.name + "released" + book.title + "via:myapp" %} do stuff with {{share_text}} {% endwith %} However, I'm getting Django template errors like "could not parse remainder" and "with received invalid operator +". -
Django API raises an error "No such file or directory: 'manage.py'" when requested
This might seem like an already asked question but I have searched for an answer for a week now and got nothing. The problem is I have developed an API using Django which is hosted on a server. Now when i run the following command to initiate the server : python manage.py runserver 0.0.0.0:9000 The server starts as usual. Its only when I send request to the server via "Postman" that i see the following error: FileNotFoundError: [Errno 2] No such file or directory: 'manage.py' The strange thing is there is no error in running the server but only when I send a request to it. Also I have many more Django APIs running on the same server with same python version(Python 3.4.3) and same virtual environment (but different port) that are running just fine. Full error traceback : Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/ubuntu/py3env/lib/python3.4/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/ubuntu/py3env/lib/python3.4/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/py3env/lib/python3.4/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/py3env/lib/python3.4/site-packages/django/core/management/commands/runserver.py", line 61, in execute super().execute(*args, **options) File "/home/ubuntu/py3env/lib/python3.4/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/home/ubuntu/py3env/lib/python3.4/site-packages/django/core/management/commands/runserver.py", line 98, in handle self.run(**options) File "/home/ubuntu/py3env/lib/python3.4/site-packages/django/core/management/commands/runserver.py", … -
Is there a way to query by id/pk/some lookup in 1 query rather than getting all nodes filtered and using the id?
https://github.com/graphql-python/graphene-django/issues/349 http://docs.graphene-python.org/projects/django/en/latest/tutorial-relay/ This queries all ingredients and then grab the specific ingredient using the previous query. Is this a normal design pattern in Relay/Graphene or can it be done in 1 query? query { allIngredients { edges { node { id, name } } } } query { # Graphene creates globally unique IDs for all objects. # You may need to copy this value from the results of the first query ingredient(id: "SW5ncmVkaWVudE5vZGU6MQ==") { name } } -
Django apache internal server error
I got "500 Internal Server Error", when I try to connect to my django project. I try lots of way to setting the configuration file, include some method on stackoverflow. But I still can't solve the problem.Can someone help? Thank you very much. This is my vhost wsgi config <Directory "/home/antus/bazoo/Antus_Bazoo_Web"> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess antus_bazoo python- path=/home/antus/bazoo:/home/antus/bazoo/bazoo_env/lib/python3.7/site- packages display-name=antus_bazoo python-home=/home/antus/bazoo/bazoo_env WSGIProcessGroup antus_bazoo WSGIScriptAlias / /home/antus/bazoo/Antus_Bazoo_Web/wsgi.py process- group=antus_bazoo This is the wsgi file import os import sys import site # Add the site-packages of the chosen virtualenv to work with site.addsitedir('/home/antus/bazoo/bazoo_env/lib/python3.7/site-packages') # Add the app's directory to the PYTHONPATH sys.path.append('/home/antus/bazoo') sys.path.append('/home/antus/bazoo/Antus_Bazoo_Web') sys.path.append('/home/antus/bazoo/antus_bazoo') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Antus_Bazoo_Web.settings") fh = open('/home/antus/bazoo/wsgi_hello.txt', 'w') fh.write('wsgi execution') fh.close() from django.core.wsgi import get_wsgi_application application = get_wsgi_application() enter code here enter code here I do also save the errors in error log but it does not have anything to consider and even the file is not created. -
Python Django and DecimalField
In my MySQL database I have such values: +-------+----------------------------------+----------------------+ | id | balance | max(length(balance)) | +-------+----------------------------------+----------------------+ | 39081 | 1.1102230246251565e-16 | 22 | | 41565 | 0.00000000000002930988785010413 | 31 | | 37692 | 0.0000000000000315303338993544 | 30 | | 39409 | 0.00000000000004263256414560601 | 31 | | 37498 | 0.000000000000049737991503207 | 29 | | 39943 | 0.000000000000050912399296443305 | 32 | | 35856 | 0.000000000000116351372980716 | 29 | | 41163 | 0.0000000000004618527782440651 | 30 | | 44612 | 0.0000000000006898925875020723 | 30 | | 40211 | 0.0000000000009268141809570807 | 30 | +-------+----------------------------------+----------------------+ 'balance' column type is 'double'. If I use FloatFiled in my model or in django rest framework serializers I get original values from table. For money recommend using DecimalField (Python's Decimal) For example: balance = serializers.DecimalField(decimal_places=35, max_digits=40, default=0) And 1.1102230246251565e-16 from MySQL table is becoming 0.00000000000000011102230246251565000. Not bad, but if balance value from table = 263.74645817644887 I will have 263.74645817644887000000000000000000000 after processing etc. And if balance = 0 I will have 0.00000000000000000000000000000000000. In mathematics of course 263.74645817644887 and 263.74645817644887000000000000000000000 are the same as well as 0 equal 0.00000000000000000000000000000000000. But I want to ask question: I'm doing everything right in this case with such values? My doubts are that if third-party script in … -
Passing a class to a form field in Django to trigget Jquery
I have this form. I want to trigger a Jquery event when someone clicks on the dia_de_entrega field. class RepartoForm(forms.Form): productos = forms.ModelMultipleChoiceField(queryset=Producto.objects.none()) nodos = forms.ModelMultipleChoiceField(queryset=Nodo.objects.none()) dia_de_entrega = forms.DateField(widget=forms.DateInput(attrs={'class': 'datepicker'})) def __init__(self, *args, productor_pk=None, **kwargs): super(forms.Form, self).__init__(*args, **kwargs) if productor_pk is not None: self.fields['productos'].queryset = Producto.objects.filter(productor=productor_pk) self.fields['nodos'].queryset = Nodo.objects.exclude(productores_kickeados = productor_pk) self.fields['dia_de_entrega'].widget.attrs.update({'class': 'datepicker'}) This is my html <!DOCTYPE html> <html> <head> <title>Crea un reparto nuevo</title> <link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css”> <link rel=”stylesheet” href=”/resources/demos/style.css”> <script src=”https://code.jquery.com/jquery-1.12.4.js”></script> <script src=”https://code.jquery.com/ui/1.12.1/jquery-ui.js”></script> </head> <body> <div> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="Enviar">Enviar</button> </form> </div> <script> $(document).ready(function(){ $(".datepicker").click(function(){ alert("adasd"); }); }); </script> </body> </html> I'm not sure if this is the correct way to do it. I searched online and it seems right -
Django 1.11 : adding variable to request
I'm currently updating an old app from Django 1.4 to 1.11, but I've run into the following problem: The logic of one of the forms in the app contains the following code: if not self.request.company: raise forms.ValidationError(_('You are not logged in to a company!')) request.company is set in a custom middleware class, using the following line: request.company = SimpleLazyObject(lambda: get_school(request)) This code works fine on Django 1.4, but when running it under 1.11 the form throws the following error: 'WSGIRequest' object has no attribute 'company' I assume the method to append variables to a request has changed, so I tried changing all the calls to request.company to request.session['company'] = VALUE and request.session.get('company') But this keeps returning None, whilst a direct call to request.session['company'] . throws a KeyError. So though the request.VARIABLE = VALUE method no longer works in django 1.11, I've been unable to find its replacement. Does anyone know what method has replaced it / what I am doing wrong? -
Django: Making queries the efficient way
Would you consider this the right/efficient way to make queries? discount_code_get = request.GET.get('discount') discount_code = Discount.objects.filter(code=discount_code_get) discount_code_exists = discount_code.exists() if discount_code_exists: print(discount_code.first().value) -
It not showed the menu bar that i designed in base.css file
I have a problem to show menu bar at first page in mysite(Django) I use "jsbin.com" for checking HTML and css. And as the first pix, i showed the menu bar that i want it to show AS USING "jsbin.com", It shows the menu bar that i wanted it to show that way However, when i see in mysite in django, it showed that way strangely (python manage.py runserver 0.0.0.0:8000) However, i showed that way in django So, please help me out if you have solution... This is base.html code. <!doctype html> <html lang="en"> <head> <title>{% block title %}Daniel Homepage</title> {% load staticfiles %} <link rel="stylesheet" href="{% static "css/base.css" %}" type="text/css"> <link rel="stylesheet" href="{% block extrastyle %}{% endblock %}"> </head> <body> <!--NAVIGATION --> <nav class = "navbar"> <div class = "container"> <a class =“brand-name“ id="name">Daniel</a> <div class ="navbar-section"> <ul class= "navbar-nav ml-auto"> <a href="{% url 'home'%}">Home</a> <a href="#">About</a> <div class="dropdown"> <button class="dropbtn">Project <i class="fa fa-caret-down"></i> </button> <div class="dropdown-content"> <a href="#">MENU</a> </div> </div> <div class="dropdown"> <button class="dropbtn">Photo <i class="fa fa-caret-down"></i> <div class="dropdown-content"> <a href="#">F1</a> <a href="#">C1</a> <a href="#">W1</a> <a href="#">B1</a> </div> </div> <a href="#">Other Pages</a> </ul> </div> </div> </nav> {% block content %}{% endblock %} {% block footer %}{% endblock %} … -
How to match two querysets by id in Django?
I have the following class: class TypeandTime(models.Model): pkid = models.BigAutoField(primary_key=True) identifier = models.BigIntegerField(blank=True, null=True) type = models.BigIntegerField(blank=True, null=True) timepoint = models.DateTimeField(blank=True, null=True) [...] The type attribute contains different numbers which stand for e.g. start (type = 1) or end (type = 2) of an event. I need to calculate the duration (timepoint where type = 2 minus timepoint where type = 1 but identifier is the same) and have no idea how to do this in Django (it works if I use the raw SQL statement but there must be a better way). So I need a result set including the identifier and the duration or both timepoints in one line. Thanks in advance! -
Try Django class 21 - .get( )
Doing the try Django from the code for entrepreneurs, I 've been having problems with the class 21. The beginning of the class he asks to type produc.objects.get(id=1) to get the objects of the class, but I am having an error in my Shell and I can't identify what is it. I copied the error. obj = product.objects.get(id=1) Traceback (most recent call last): File "/Users/pedrosantos/.local/share/virtualenvs/try_django-xpD0_Dxa/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/Users/pedrosantos/.local/share/virtualenvs/try_django-xpD0_Dxa/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 296, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: products_product The above exception was the direct cause of the following exception: Traceback (most recent call last): File "", line 1, in File "/Users/pedrosantos/.local/share/virtualenvs/try_django-xpD0_Dxa/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/pedrosantos/.local/share/virtualenvs/try_django-xpD0_Dxa/lib/python3.6/site-packages/django/db/models/query.py", line 393, in get num = len(clone) File "/Users/pedrosantos/.local/share/virtualenvs/try_django-xpD0_Dxa/lib/python3.6/site-packages/django/db/models/query.py", line 250, in len self._fetch_all() File "/Users/pedrosantos/.local/share/virtualenvs/try_django-xpD0_Dxa/lib/python3.6/site-packages/django/db/models/query.py", line 1183, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/Users/pedrosantos/.local/share/virtualenvs/try_django-xpD0_Dxa/lib/python3.6/site-packages/django/db/models/query.py", line 54, in iter results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/Users/pedrosantos/.local/share/virtualenvs/try_django-xpD0_Dxa/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1061, in execute_sql cursor.execute(sql, params) File "/Users/pedrosantos/.local/share/virtualenvs/try_django-xpD0_Dxa/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute return super().execute(sql, params) File "/Users/pedrosantos/.local/share/virtualenvs/try_django-xpD0_Dxa/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/Users/pedrosantos/.local/share/virtualenvs/try_django-xpD0_Dxa/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "/Users/pedrosantos/.local/share/virtualenvs/try_django-xpD0_Dxa/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, … -
How to log in a user to a remote site using a post request in Django
I have a two sites with different domains but single backend (Django). As is: Client fill the form on a landing Landing send POST request to Server Server register user User visit main site (server) and fill login form again to log in To be: Client fill the form on a landing Landing send POST request to Server Server register and login user User visit main site (server) and he is already logged in What are the ideas? -
How to implement the paginator in Django 2.1?
To product page of my project I need to add paginator. I did according to the Django Documentation but I have the following error: object of type 'InsuranceProducts' has no len() Here is the my views.py: def farmer_types(request, type_id): product_areas = InsuranceProducts.objects.filter(product_type="Фермерам") product_types = get_object_or_404(InsuranceProducts, id=type_id) paginator = Paginator(product_types, 6) page = request.GET.get('page') types = paginator.get_page(page) context = {'product_types': product_types, 'product_areas': product_areas, 'types': types} return render(request, 'insurance_products/farmer/farmer_types.html', context) Here is the my models.py: class InsuranceProducts(models.Model): product_area = models.CharField(max_length=100) product_description = models.TextField() product_type = models.CharField(max_length=50) def __str__(self): return "{}-{}".format(self.product_area, self.product_type) class ProductType(models.Model): product_area = models.ForeignKey(InsuranceProducts, on_delete=models.CASCADE) title = models.CharField(max_length=100) description = models.TextField() body = HTMLField('Content') def __str__(self): return "{} - {}".format(self.product_area, self.title) Here is the code from the template: {% for product in types.producttype_set.all %} <div class="btmspace-80"> <h3>{{ product.title|upper }}</h3> <img class="imgr borderedbox inspace-5" src="{% static 'img/imgr.gif' %}" alt=""> <p> {{ product.description|upper }} </p> <p> Подробно вы можете узнать о новости <a href="{% url 'main:farmer_product' product_types.id product.id %}">здесь</a></a> </p> </div> {% endfor %} <div class="pagination"> <span class="step-links"> {% if types.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ types.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ types.number }} of {{ types.paginator.num_pages }}. </span> {% if types.has_next %} <a href="?page={{ types.next_page_number }}">next</a> <a … -
django retrieve data from mysql database
I am new to Django. I need help on retrieving data from mysql database and displaying it on the html page. Can someone advice please. Much appreciated! :) Models.py: class testing(models.Model): name = models.TextField(null=True) title = models.CharField(max_length=70, null=False) def __unicode__(self): return self.name Views.py: def testing_view(request): test = testing.objects.all() return render(request, 'testing/testing.html', {'test': test}) testing.html: Name: {{ test.name }} Title: {{ test.title }} -
"plugin" Vue components from Django backend
I'd like to create a web aaplication that consists of plugins, meaning loosely-coupled modules that can have dependencies etc., maybe with an ecosystem ("app store" etc.). How do I manage the "distribution" of these plugins: I don't have decided yet if a SPA is needed (I saw question vue js + django app architecture). Example: The main django app (core plugin) builds the UI (having tha Vue app in it's assets' folder. There can be a plugin A as django app which dynamically provides some Vue components that "somehow" snap into place in the main UI. My Django code has a REST (and probably a GraphQL) API and a custom plugin system. I just don't get how Vue components that are provided by "plugged in" django apps render their code into the main application frontend. What I thought so far is: at the server start, my plugin system checks for all available Vue components on disk and does a Vue "build" step (and manage.py collectstatic) to automatize this process? Can Webpack help here? I'm stuck. -
Applications that are not for TENANT appear on the tenant's website
I was trying a script from TomTurner, and got an oddity that bothered me. This is my project: https://github.com/githubfans/DjangoTenants/tree/master/examples/tenant_tutorial The script runs on virtualenv: env02, dir env02/ is there. settings.py SHARED_APPS = ( 'django_tenants', # mandatory 'customers', 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) TENANT_APPS = ( 'rest_framework', 'barang', 'tenant_only', ) Question: Why is there a "customers" on the website of tenant "tenant1.aji.com/admin" ? Thank you for the solution. Sorry bad english. -
Django: Hyperlink from Admin of Model to documentation
I have an application which uses the django admin interface extensively. Some things in the admin GUI need explanations (domain/model specific docs) We use sphinx and screenshots do explain details. Is there a generic/automated way to create hyperlinks from the django admin interface of a model instance to the matching part in the docs? I know that I could alter the admin templates of the models, but somehow I guess someone has a better idea how to solved this in a more professional way. -
how to parse amazon fullfillment fee/comission from python-mws-api using ASIN ,codes in python
mwsparse.py from mws import mws orders_api=mws.Reports(access_key='XXXXXXXXXXX',secret_key='XXXXXXXXXXXXXXXXXXXXX',account_id='XXXXXXXXXXXXX',region='US') report = orders_api.get_report_list(requestids=['B07DFCMBNJ',],types=['_GET_AMAZON_FULFILLED_SHIPMENTS_DATA_',]) response_data = report.original print response_data ERROR mws.mws.MWSError: 400 Client Error: Bad Request for url: https://mws.amazonservices.com/?AWSAccessKeyId=AK XXXXXXXXXXX&Action=GetReportList&Merchant=XXXXXXXXXXX&ReportRequestIdList.Id.1=B07DFCMBNJ&Report TypeList.Type.1=_GET_AMAZON_FULFILLED_SHIPMENTS_DATA_&SignatureMethod=HmacSHA256&SignatureVersion=2&Timest amp=2018-08-24T07%3A05%3A03Z&Version=2009-01-01&Signature=XXXXXXXXXXX/lRtwUVR%2BbdkV/dfSc%3D -
How to run Django background task only once
I am trying to crop images (thousands of images) on button click bellow is my code! @background(schedule=5) def initialize(): allimages = [] number = 0 if not os.path.exists('thumbnails'): os.makedirs('thumbnails') path = '/Users/shoaibrafa/Data/*.jpg' for image in glob.glob(path): print(image,"=====",number) im = Image.open(image) im.thumbnail((512, 512), Image.ANTIALIAS) im.save("thumbnails/" + os.path.basename(image), "JPEG") number = number + 1 but I face two problems: when clicking the button from the template gives Object of type 'WSGIRequest' is not JSON serializable error! if I call the method initialize() directly when the page loads the background task starts cropping the images, but when the all images are cropped it starts again from beginning cropping the images and continues for ever. What I need is to crop the images and end the background task. bellow is my template: {% extends 'layout.html' %} {% block title %} Login {% endblock %} {% block content %} <a class="btn btn-primary" href="{% url 'home:init'%}">Initialize...</a> {% endblock %} thanks in advance