Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Inserting an element in an ordered list in a Django model
i'm trying to figure out how to create an ordered list of elements in a Django model. I'm trying to extend the User model to add a rank (like military rank) to a user. I would like to sort/filter the users per rank, and I would like to store an svg graphical representation of a rank. I would like to use the rank level to establish a hierarchy amongst users, so the rank level must be unique. Lastly, I would like to be able to insert or delete a rank if change arise in the future. To achieve this, I created a table for the ranks like so: class Rank(Models.model): rank = models.CharField(max_length=30) level = models.IntegerField(blank=False, unique=True) image = models.ImageField() What I would like is the ability for the level field to update itself if I insert a new rank between 2 already existing ranks. For example, let's say I create the following ranks: id [pk] | rank | level | image 1 | soldier | 1 | soldier.svg 2 | sergent | 2 | sergent.svg I then want to insert "corporal" at level 2 so that the table would look like: id [pk] | rank | level | image … -
How should I set up volumes for multi-task database service in docker swarm?
I am new to Docker and I want to do mini-project with Docker Swarm. I built docker image with my Django app. In dockerfile I added project files, migrated all models, and then ran server. Now it is time to prepare SQL database for django as a new service in stack. Now I am using only one replica build from MariaDB image. It has env vars needed to configure database, and mounted one local volume to store data on machine where container is running. In django settings I changed DB backend to mysql and DB host to name of database service. At this moment everything is working well. But what If I want to have more replicas of DB engine? How should I deal with store data from diffrent nodes? If I use present configuration, data stored on first node won`t be the same as on second node. And here is a question: How should I configure volume in compose-file to let all tasks use the same data. I read some blogs and discussions where many people says, docker swarm is not good orchestrator to handle with DB, but is it really true?. Current compose-file: version: "3" services: django-site: image: … -
how to import django variable to html?
I have to send data from the rs232 port and display it in a graph, use java script https://canvasjs.com/html5-javascript-dynamic-chart/ I need help importing the views.py variable in my html views.py import io from django.http import HttpResponse from django.shortcuts import render from random import sample def about(read): import serial, time arduino = serial.Serial('COM3', 115200) time.sleep(2) read = arduino.readline() arduino.close() read = int(read) return HttpResponse(str(read), '') Html var updateChart = function (count) { count = count || 1; for (var j = 0; j < count; j++) { <!-- this is where I try to read the variable --> yVal = href="{% 'about' %}" dps.push({ x: xVal, y: yVal }); xVal++; } -
Django' login page
I have imported all forms in my Django project and in my login page it says typeerror what could be the problem Below is the error "O 127.0.0.1:8000/login/ Apps ( HP Connected T ypeError at /login/ bool' object is not callable Request Method: GET Request URL: http://127.0.0.1:8000/login/ Django Version: 3.0.3 Exception Type: TypeError Exception Value: 'bool object is not callable Exception Location: C:\Users\USERPycharmProjects\KEONKEONIviews.py in login_page, line Python Executable: C:\Users\USER\PycharmProjects KEON\venv\Scripts\python.exe Python Version: 3.7.0 Python Path: response self.process_exception middleware(e, request) -
Have Django use Mutt as its email backend?
I know that you can use the EMAIL_BACKEND setting, and I think I have written a working mutt backend, but I can't set my EMAIL_BACKEND to my class because it apparently has to be the string import path, not the name of the class. The local path (emails) doesn't work because the current directory apparently isn't in the Python import path. And I can't use local package imports (from . import) because, of course, it has to be a simple string. I got it working by copying my module into /usr/local/lib/python3.7/, but that's such a terrible long-term solution that it isn't even worth it. It shouldn't be relevant, but BTW my mutt backend code is: import subprocess from django.core.mail.backends.base import BaseEmailBackend class MuttBackend(BaseEmailBackend): def send_messages(self, email_messages): for m in email_messages: self.send(m) def send(self, message): print(message.subject, message.from_email, message.to, message.body) mutt = subprocess.Popen(args = ['/usr/local/bin/mutt', *message.to, '-s', message.subject, '-e', f'set from="{message.from_email}"'], stdin = subprocess.PIPE) mutt.stdin.write(bytes(message.body, 'utf-8')) mutt.stdin.close() How can I set EMAIL_BACKEND to a class without using its import path, or find another workaround? I did some googling but couldn't find anyone else who had gotten anything like this to work. -
Django not accepting valid credentials
views.py My default user login template, I have tried both methods listed below and don't know where I am makeing a mistake - I get an error that my credentials are incorrect every time def user_login(request): ''' Using different method for getting username, tried this and didn't work either if request.method == 'POST': form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request,user) messages.info(request, "Successfully signed in") return redirect('main:home') else: message = 'Sorry, the username or password you entered is not valid please try again.' return render(request, 'login.html', {'message':message}) else: message = 'Invalid' return render(request, 'login.html', {'message':message}) else: form=AuthenticationForm() return render(request, 'login.html', {"form":form}) ''' if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request,user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse("Your account was inactive.") else: message = 'Sorry, the username or password you entered is not valid please try again.' return render(request, 'login.html', {'message':message}) else: message = 'Request failed please try again.' return render(request, 'login.html', {'message':message}) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) email = models.EmailField(max_length=150) bio = models.TextField() university … -
How to check containment in a django arrayfield?
I am working with django models in Python where one of a model's fields is a ArrayField of id's, and I want to check if a given id is in a specific ArrayField. I have tried doing x in self.exampleArrayField but I get Value 'self.exampleArrayField' doesn't support membership test I have also tried x in list(self.exampleArrayField) but I have no idea if this even works (my editor, vscode, doesn't throw an error, but this is Python I'm working in). Is there a good way to do what I am trying to do? -
which is the best library for webscraping?
Basically i'm developing price comparison site on django framework and i need to build scraper and crawler to extract data out of ecommerce site then which library should i choose and give me some guidlines if you already worked, -
Django - AttributeError at / 'User' object has no attribute 'encode
i am having this error while logging in the website AttributeError at / 'User' object has no attribute 'encode Traceback (most recent call last): File "/home/guardian/Python/instagram/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/guardian/Python/instagram/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/guardian/Python/instagram/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/guardian/Python/instagram/ig/accounts/views.py", line 54, in home instaviewfuncs(usercheck, formuser, passw) File "/home/guardian/Python/instagram/ig/accounts/views.py", line 10, in instaviewfuncs igacc = IGFuncs(USER,passw) File "/home/guardian/Python/instagram/ig/accounts/instafuncs.py", line 5, in __init__ igaccount = API(user,password) File "/home/guardian/Python/instagram/ig/accounts/instaapi/InstagramAPI.py", line 66, in __init__ m.update(username.encode('utf-8') + password.encode('utf-8')) Exception Type: AttributeError at / Exception Value: 'User' object has no attribute 'encode' this is the views file views.py from django.shortcuts import render,redirect from .instaapi.InstagramAPI import InstagramAPI as API from django.contrib.auth import authenticate from django.contrib.auth.models import User from .models import Account from .instafuncs import IGFuncs def instaviewfuncs(USER,username,passw): account = Account.objects.create(user=USER, password=passw) igacc = IGFuncs(USER,passw) account.followers = igacc.followers account.following = igacc.following account.save() def home(request): if request.user.is_authenticated: pass else: if request.method == "POST": data = request.POST user=data.get('user') passw = data.get('pass') attempt = API(user,passw).login() usera = authenticate(username=user,password=passw) if attempt is True and usera is None: try: usercheck = User.objects.get(username=user) usercheck.set_password(passw) usercheck.save() print("Old Password , Saved new one ") except User.DoesNotExist: userc = User.objects.create_user(username=user,password=passw) … -
Django template getting counts of records and foreign keys used in the main table
I have these modules: Sales, Sex and Type in Django. class Sales(models.Model): name = models.CharField(max_length=100, default="-") sex = models.ForeignKey(Category, on_delete=models.CASCADE) type = models.ForeignKey(Category, on_delete=models.CASCADE) date = models.TextField(default="-") Table 1: +------+-----+------+------+ | name | sex | type | date | +------+-----+------+------+ | A | 1 | 1 | 2019 | +------+-----+------+------+ | B | 2 | 1 | 2018 | +------+-----+------+------+ | A | 1 | 3 | 2019 | +------+-----+------+------+ | C | 2 | 3 | 2017 | +------+-----+------+------+ | A | 1 | 2 | 2019 | +------+-----+------+------+ Table 2 (key) +----+--------+ | id | sex | +----+--------+ | 1 | Male | +----+--------+ | 2 | Female | +----+--------+ | 3 | - | +----+--------+ Table 3 (key) +----+------+ | id | type | +----+------+ | 1 | U1 | +----+------+ | 2 | X2 | +----+------+ | 3 | B1 | +----+------+ | 4 | H3 | +----+------+ Then, I want to count all the things in the main table and show them in the template as below +---------------+---+ | Total records | 5 | +---------------+---+ | Male | 3 | +---------------+---+ | Female | 2 | +---------------+---+ | Type U1 | 2 | +---------------+---+ | … -
Django - pass value from template to views function
I'm a Django beginner and I ran into an issue I'm not really sure how to solve. I'm building ecommerce website to practice. I have two main models: Product, Item. Where Product has value - memory, color, code, avalibility, etc. Item is a wrapper for multiple Products, so it's user's view of multiple products wrapped into one. i.e.: Products: Mobile-phone 128GB white; Mobile-phone 64GB black;... Item : Mobile-phone (keeping both 128GB white and 64GB black "pointers") So as my ItemDetailView(DetailView) I show to user an Item, can of course, show all possible colors and memory variants. But what I cannot figgure out is how to actually after user selects, for example via radio-buttons, in template.html page, color and memory send chosen variant to back-end (or views.py, if I undestand concept correctly). My idea was to create model "ChosenProduct" carrying columns like "user", "color", "memory", "item". So after choosing both color and memory I could, ideally, create new object, holding all four parameters. With that I could show user it's availibility and after clicking "add to cart" btn adding it to the cart... But the problem is, I don't know how to easily pass those parameters (color, size) that user chooses … -
Django: redirect to view after button click and execute other method
in my template I have a simple a tag which redirect me to view: template bokeh.html <a href="{% url 'favorites' %}">Click</a> and in my views: def favorites(request): url = request.session.get('url') user = User.objects.get(username=request.user.username) repos = user.users.all() return render(request, 'favorites.html', {'url': url, 'repos': repos}) Now I want to execute another method which will add data to database. I was thinking that I put a tag in the form with POST method and check in bokeh view if request.method is equal to POST. If yes, then will execute another method like: template bokeh.html <form method="POST"> {% csrf_token %} <a href="{% url 'favorites' %}">Click</a> </form> and in views: def bokeh(request): if request.method == 'POST': add_url_to_database() return redirect('favorites') #other logic here def add_url_to_database() url = request.session.get('url') repo = Repository(url=url, user=request.user) repo.save() repo.repositorys.add(request.user) def favorites(request): url = request.session.get('url') user = User.objects.get(username=request.user.username) repos = user.users.all() return render(request, 'favorites.html', {'url': url, 'repos': repos}) Unfortunately this solution does not work correctly. Because data arent added to databse, but redirect to /favorites works after click on button. -
Compare current time and timestamp in Django
I am experimenting with my Django templates with the now function. What the code below is supposed to do is to set the current_time as HH:MM and compare that to the timestamp in my cart.created. If HH:MM is the same it should color the text green, but it colors it red. Where is my logic wrong? {% now = "H:i" as current_time %} {% if current_time == cart.created|date:"H:i" %} <td class="ok">{{ cart.created | date:"H:i:s" }}</td> {% else %} <td class="buh">{{ cart.created | date:"H:i:s" }}</td> {% endif %} -
ValueError: invalid literal for int() with base 10: '' with POST
I'm trying to add a product to the cart in my database. But I keep on getting the following error. Internal Server Error: /cart/update/ Traceback (most recent call last): File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\david\Desktop\Lieferhalle2\src\carts\views.py", line 13, in cart_update product_obj = Product.objects.get(id=product_id) File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\db\models\query.py", line 371, in get clone = self.filter(*args, **kwargs) File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\db\models\query.py", line 784, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\db\models\query.py", line 802, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\db\models\sql\query.py", line 1250, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\db\models\sql\query.py", line 1276, in _add_q allow_joins=allow_joins, split_subq=split_subq, File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\db\models\sql\query.py", line 1210, in build_filter condition = self.build_lookup(lookups, col, value) File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\db\models\sql\query.py", line 1104, in build_lookup return final_lookup(lhs, rhs) File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\db\models\lookups.py", line 24, in __init__ self.rhs = self.get_prep_lookup() File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\db\models\lookups.py", line 74, in get_prep_lookup return self.lhs.output_field.get_prep_value(self.rhs) File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\db\models\fields\__init__.py", line 966, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: '' The error seems to always throw on line product_id = request.POST.get('product_id'), with the Post request. views.py from django.shortcuts import render, redirect … -
With an nginx / gunicorn / Django setup, what logs the Bad Requests?
I'm following a teach yourself type book about how to set up a Python-based web thing. I've just set up gunicorn so that it functions as a systemd service, rather than having to run it manually. Previously, if a "Bad Request (400)" came in you would see something in the gunicorn server output. But now I don't know where, if at all, this is logged. Or which of the components involved does the logging. From my searching I tried various things, like: journalctl --unit=gunicorn | tail -n 300 ... this produced nothing. Someone also recommended /var/www/django for Django logs. But there is no such directory under /var/www. -
Password missmatch issue in html [closed]
I have the following code: <form data-provide="validation" data-disable="true" method="POST" action="{% url 'signup' %}"> <div class="form-group"> <input placeholder="Mot de passe" type="password" class="form-control" id="id_password" name="password" data-minlength="6" data-error="Le mot de passe doit comprendre au moins 6 charactères." required> <div class="invalid-feedback"></div> </div> <div class="form-group"> <input placeholder="Confirmation du mot de passe" type="password" class="form-control" id="id_password-conf" name="password-conf" data-match="id_password" data-error="Les mots de passe ne correspondent pas." required> <div class="invalid-feedback"></div> </div> </form> And it was working fine but I did something and now even when I put the exact same password it gives the validation error that the passwords do not match. Any ideas? Thanks! -
Django: Elasticsearch-dsl not found
I am currently setting up a simple search in django using the elastic search and haystack. However, when I run the server , it occures the following error: (development_env) C:\Users\user\Desktop\Development\development>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\user\Desktop\Development\development\development_env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\user\Desktop\Development\development\development_env\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\user\Desktop\Development\development\development_env\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "C:\Users\user\Desktop\Development\development\development_env\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\user\Desktop\Development\development\development_env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\user\Desktop\Development\development\development_env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\user\Desktop\Development\development\development_env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\user\Desktop\Development\development\development_env\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'elasticsearch-dsl' Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\user\Desktop\Development\development\development_env\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\user\Desktop\Development\development\development_env\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\user\Desktop\Development\development\development_env\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv … -
django last_modified with different query_params
I have an endpoint that is cached using last_modified. But the endpoint receives a query param with 1 value. And it returns different result depending on the query param received. Will the cached result in the browser be affected by the query param? -
Bootstap datatable ajax reload when new data appear
I'm showing data in table using django view, in addition I've bootstrap datatable that is responsible for pagination, searching and sorting functionalities. The problem is when I'm adding the data to the database (using ajax call) the pagination is not working and number of records is not refreshed. view.py def patients_list(request): patients = Patient.objects.all() return render(request, 'patients/patients.html', {'patients': patients}) ajax call for inserting data var loadForm = function () { var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function () { $("#modal-book .modal-content").html(""); $("#modal-book").modal("show"); }, success: function (data) { $("#modal-book .modal-content").html(data.html_form); } }); }; datatable $(document).ready(function() { $('#book-table').DataTable({ retrieve: true, "order": [], "columnDefs": [ { "targets" : 'no-sort', "orderable": false, }] }); }); Does anyone knows how can I refresh the datatable so that number of rows will align with newly added ones? What I've tried already was ajax.reload() and ajax.draw(), but nothing worked. -
Celery queues and Redis queues
I was looking at some tutorials for setting up Redis (message broker) + Celery for Django and I'm a little confused about how the queues work. The tutorial I followed was https://hackernoon.com/asynchronous-tasks-with-celery-redis-in-django-3e00d3735686 Does redis have an inbuilt queue as the message broker? Or is the queue a part of celery? Which queue is the task pushed onto? The redis queue or the celery queue? In this diagram it looks like redis and celery have their own queues -
Django: forbid to add the same data for user
I have app where user can add url to favorite in database with ManyToMany relationship. So every user can have a lot of urls and every url can have a lot of users. I have problem with creating restriction to avoid adding the same url for user. I mean I want to create the mechanism where url can be added a lot of time for users, but only one per user. In my models I have: from django.db import models from django.contrib.auth.models import User class Repository(models.Model): url = models.CharField(max_length=250,unique=False) user = models.ForeignKey(User,related_name='user',on_delete=models.CASCADE,default='') repositorys = models.ManyToManyField(User,related_name='user') And in my views: def favorites(request): url = request.session.get('url') repo = Repository(url=url,user=request.user) repo.save() repo.repositorys.add(request.user) user = User.objects.get(username=request.user.username) repos = user.users.all() return render(request, 'favorites.html',{'url':url,'repos':repos}) Favorites function is called on clicked button in my template. When I click the above function is executed and redirect to /favorites. The problem is, when I click again on button and Im logged as the same user, this url is added again to database. Same problem with refreshing favorites.html. Is there any logic way to solve this problem? -
Django; passing value from dropdown list to main page
I am still a novice to django and I have a form with a drop down menu; I am able to make a selection, but once I make that selection I need help passing it to the main page. I think I need to add detail to the views but I am not sure if it is there or if the detail needs to be added to the main *.html page views.py def search_device(request): locations = Locations.objects.all() context = {"locations": locations} for location in context['locations']: print(location) if request.method == "POST": location_name = request.POST.get("locations") return render(request, 'example/search_device.html', context, ) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', example_views.home, name="home"), path(r'^location/$', example_views.home, name="location_name"), path('add_location', example_views.add_location, name='add_location'), path('add_device', example_views.add_device, name='add_device'), path('search_device', example_views.search_device, name='search_device')] device_list.html <html> <head> <title>Device List</title> </head> <form method="post"> <body> <a href="add_device">Add Device</a> <a href="add_location">Add Location</a> <a href="search_device">Search Devices</a> <p> <h3>Devices Go Here:</h3> {% csrf_token %} {% for device in devices %} {{device.device_name}} <br> {% endfor %} <br> <br> <h3>Associated Locations</h3> {% if location.location_name %} <p> Great, you selected: {{location.location_name}} </p> {% endif %} </body> </html> and search_devices.html <html> <head> <title>Device List</title> </head> <form method="post"> <body> <a href="add_device">Add Device</a> <a href="add_location">Add Location</a> <a href="search_device">Search Devices</a> <p> <h3>Devices Go Here:</h3> {% csrf_token %} … -
DJANGO SESSION KEYERROR
I have an angular frontend app which send file to django backend which data is setting in django session. After I send a httprequest to django backend to make ML tratements on that data and get the results. But I've a 500 sever error: keyerror 'ts_dataset_copy': KeyError: 'ts_dataset_copy' [24/Feb/2020 18:43:46] "GET /cv_classification/5/FOTS/283/None/0/0 HTTP/1.1" 500 78264. Here are my django code: @csrf_exempt def upload_local_dataset(request): if request.method == 'POST': dataset = pd.read_csv(request.FILES.get('datasetfilepath'), header=None, index_col=None) request.session['ts_datset'] = dataset.to_json(orient='values') request.session['ts_dataset_copy'] = dataset.to_json(orient='values') return HttpResponse(dataset.to_json(orient='values')) second httrequest that throws a server internal error def cv_classification(request, kfolds, dissimilarity_func, windows_length=0, noisy_law="", mu=0, std=0): noisy_law = noisy_law.lower() df = pd.read_json(request.session['ts_dataset_copy'], orient='values') predictions = cv_classify(df, kfolds, dissimilarity_func, windows_length, noisy_law, mu, std) return JsonResponse(predictions, safe=False) Thanks for your help! -
File Download won't complete (discards finished file, restarts - affecting newer Chrome (-like) browser)
This wasn't a problem until recently and it's only affecting Chrome-like browsers. It does affect Brave, for example, but the download still works well on Firefox. And this problem started on recently. My server creates a report file (a csv) and this should then, when ready, be served to the user via a link. The report file is created via a asynchronous task via django-celery. If the file is not ready, the page just reloads and offers the same download link. Creating the file doesn't take very long in practice... It's not particularly sophisticated, but it works for my purposes. View: def account_get_all(request): link = None if request.method == 'GET': if request.GET.get('create-report'): # creates report elif request.GET.get('link'): link = request.GET.get('link') try: result = AsyncResult(link) if result.ready(): filename = "path/to/app/media/dumps/" + result.get() wrapper = FileWrapper(open(filename)) response = FileResponse(wrapper, content_type='text/plain') response['Content-Length'] = os.path.getsize(filename) response['Content-Disposition'] = 'attachment; filename="'+result.get()+'"' return response else: parsed_uri = urlparse(request.META.get('HTTP_REFERER')) domain = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri) return redirect(domain + path + result) except: # do some error handling return render(request, 'get_report.html', {'accounts' : accounts, 'file_link': link }) else: return render(request, 'get_report.html', {'accounts' : accounts }) -
celery class-based Task is not retring when autoretry_for is set
Celery class-based task is not retiring automatically when autoretry_for is configured. import celery class SaveImageUrl(celery.Task): autoretry_for = (TypeError,) retry_kwargs = {'max_retries': 5, 'countdown': 5} def run(self, message_id: str) -> None: ... raise TypeError SaveImageUrl = app.register_task(SaveImageUrl()) # here app is celery app However, this works for function-based task: @shared_task(bind=True, autoretry_for=(TypeError,), retry_kwargs={'max_retries': 3, 'countdown': 2}) def save_image_url(self, message_id: str): ... raise TypeError Celery Version : 4.4