Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Play video uploaded by user with formset in Django
I'm not able to play videos from list made with formset in django. I want to make a video playlist with videos uploaded by user (a sort of udemy . com). Users can add fields to upload more videos or let only one field by default (there is script in javascript for that). I havent problem to upload videos, everything is ok about that (videos are uploaded correctly). The problem is to play videos. Here my models.py from django.db import models from django.utils import timezone from django.template.defaultfilters import slugify class Cours(models.Model): titre = models.CharField(max_length=100) slug = models.SlugField(max_length=100) auteur = models.CharField(max_length=42) comment = models.TextField(null=True) link = models.CharField(max_length=100) date = models.DateTimeField(default=timezone.now, verbose_name="Date de parution") categorie = models.ForeignKey('Categorie', on_delete=models.CASCADE) def save(self, *args, **kwargs): self.slug = slugify(self.titre) super(Cours, self).save(*args, **kwargs) class Meta: verbose_name = "cours" db_table = "cours" ordering = ['date'] def __str__(self): return self.titre class Categorie(models.Model): nom = models.CharField(max_length=30) def __str__(self): return self.nom class Plan_simple(models.Model): partie = models.CharField(blank=True, max_length=100) date = models.DateTimeField(default=timezone.now, verbose_name="Date de parution") vid = models.FileField() cours = models.ForeignKey(Cours, related_name = "plan_simple", on_delete=models.CASCADE) def __str__(self): return self.partie class Meta: db_table = "plan_simple" my form.py from django import forms from django.forms import ModelForm from django.template.defaultfilters import slugify from django.forms import formset_factory from … -
Error Install Django-Admin (Running setup.py install for screen ... error)
I was having no problem running django but when I was about to run 'django-admin startproject', it says there is no 'django-admin' directory in my Python folder. So I ended up trying to install using pip install django-admin. Here is the error: C:\Users\syahm>pip install django-admin Collecting django-admin Using cached django_admin-2.0.1-py2.py3-none-any.whl (7.6 kB) Collecting django-excel-response2>=3.0.0 Using cached django_excel_response2-3.0.2-py2.py3-none-any.whl (4.4 kB) Collecting django-excel-base>=1.0.4 Using cached django_excel_base-1.0.4-py2.py3-none-any.whl (4.0 kB) Requirement already satisfied: django-six>=1.0.4 in c:\users\syahm\appdata\local\programs\python\python37-32\lib\site-packages (from django-excel-response2>=3.0.0->django-admin) (1.0.4) Requirement already satisfied: xlwt in c:\users\syahm\appdata\local\programs\python\python37-32\lib\site-packages (from django-excel-base>=1.0.4->django-excel-response2>=3.0.0->django-admin) (1.3.0) Collecting screen Using cached screen-1.0.1.tar.gz (8.6 kB) Requirement already satisfied: pytz in c:\users\syahm\appdata\roaming\python\python37\site-packages (from django-excel-base>=1.0.4->django-excel-response2>=3.0.0->django-admin) (2019.2) Installing collected packages: screen, django-excel-base, django-excel-response2, django-admin Running setup.py install for screen ... error ERROR: Command errored out with exit status 1: command: 'c:\users\syahm\appdata\local\programs\python\python37-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\syahm\\AppData\\Local\\Temp\\pip-install-o89ws43u\\screen\\setup.py'"'"'; __file__='"'"'C:\\Users\\syahm\\AppData\\Local\\Temp\\pip-install-o89ws43u\\screen\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\syahm\AppData\Local\Temp\pip-record-t_rdgtfv\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\syahm\appdata\local\programs\python\python37-32\Include\screen' cwd: C:\Users\syahm\AppData\Local\Temp\pip-install-o89ws43u\screen\ Complete output (18 lines): running install running build running build_py creating build creating build\lib.win32-3.7 creating build\lib.win32-3.7\screen copying screen\compat.py -> build\lib.win32-3.7\screen copying screen\old_str_util.py -> build\lib.win32-3.7\screen copying screen\__init__.py -> build\lib.win32-3.7\screen running build_ext building 'screen.str_util' extension creating build\temp.win32-3.7 creating build\temp.win32-3.7\Release creating build\temp.win32-3.7\Release\source C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.25.28610\bin\HostX86\x86\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT -Ic:\users\syahm\appdata\local\programs\python\python37-32\include … -
Getting rid of port in URL for django installation in production
I'm trying for the first time to deploy my Django application on a server but so far I wasn't able to get rid of port in my URL. Right now I'm using Gunicorn with Nginx with the following configuration. Nginx /etc/nginx/sites-enabled/site.conf server { listen 8000; server_name example.com; location = /favicon.ico {access_log off;log_not_found off;} location /static/ { root /home/webapp/um; } location /media/ { root /home/webapp/um; } location / { include proxy_params; proxy_pass http://unix:/home/webapp/um/um.sock; } } /etc/nginx/proxy_params proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; Gunicorn /etc/systemd/system/gunicorn.service Description=gunicorn service After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/webapp/um/ ExecStart=/root/um/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/webapp/um/um.sock um.wsgi:application [Install] WantedBy=multi-user.target Gunicorn binding gunicorn --bind 0.0.0.0:8000 um.wsgi:application Changing port 8000 with port 80 in /etc/nginx/sites-enabled/site.conf gives me a 404 on nginx. Using port 8000 I'm able to see the site using http://example.com:8000/myapp but I'm aiming at using http://example.com/myapp as my address. As a side note, the VPS I'm installing the app on came with Plesk already installed with which I'm also not familiar with. I don't know if Plesk might be interferring in catching traffic from port 80. Thanks in advance -
Override parent css settings using child gives unknown property name
I'm trying to override the parent settings of a dropdown menu using a child class in CSS. Unfortunately, when I try to do this it gives me an "unknown property name" error on the child class, even though I use the exact same property on the parent class. The CSS code looks like: .dropdown { position: relative; display: inline-block; } .dropdown-content { display: none; position: absolute; overflow: hidden; min-width: 160; min-heigth: 100; background-color: #f9f9f9; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); padding: 12px 16px; z-index: 1; left:20%; } .test { min-width: 1080; min-heigth: 480; } .dropdown:hover .dropdown-content { display: inline-block; } And the HTML code (django template format) looks like: {% for info in infos %} <div class="dropdown"> <a href="#">dropdown item</a> <div class="dropdown-content"> {% if info.2 == "img" %} <!-- display image --> {% elif info.2 == "gif" %} <div class="test">Gifs and Videos are disabled for preview.</div> {% endif %} </div> </div> {% endfor %} In which info.2 will always contain either the string "gif" or "img". I have not yet implemented the image yet. However, if I use inspect element I get the following error: Which does not make any sense to me, as the css within the dropdown-content class … -
How to make media types for media shared and private
Currently, I want to make a media types which is shared and private. For media shared, all project can view the media while for media private only certain project can view it. I dont why its not working. These are my coding views.py def CONprojectnewknowledgecenter(request, id): project_dat = get_object_or_404(project_db, pk=id) if request.method == 'GET': all_format = Format.objects.all() all_category = Category.objects.all() all_mediatype = MediaType.objects.all() return render(request, 'dashboard/CONprojectnewknowledgecenter.html', {'all_format': all_format, 'all_category': all_category, 'all_mediatype': all_mediatype, 'project_dat': project_dat}) if request.method == 'POST': print("Creating new Kc, format: ", request.POST.get('format_id')) formatinstance = get_object_or_404(Format, pk=request.POST.get('format_id')) print("Creating new Kc, category: ", request.POST.get('category_id')) categorylist = get_object_or_404(Category, pk=request.POST.get('category_id')) print("Creating new Kc, media type: ", request.POST.get('mediatype_id')) mediatypes = get_object_or_404(MediaType, pk=request.POST.get('mediatype_id')) kc_submission = Kc.objects.create() image = None try: print("Checking for Kc Image ... ") image = request.FILES['image'] except: print("Error: No Kc Images Found. Revert to NULL value.") finally: print("Checking for Kc Filetype ... ") if formatinstance.filetype == 'File': print("Filetype:File") if categorylist.category == 'Category': print("Category selected") if mediatypes.mediatype == 'Media': print("Media Type selected") try: print("Checking for Kc Filesource ... ") my_uploaded_file = request.FILES['inputmediafile'] except: print("Error: No Kc Filesource Found. Redirecting back to input page.") return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) inputmedia = my_uploaded_file.name status = gcp("write", file_path="project/" + str(kc_submission.id) + "/" + inputmedia, item=my_uploaded_file.read()) else: print("Filetype:Link … -
django : nombre de choice field dynamique et pas fixe
Bonjour, Alors voila je fait un formulaire dans django et j'aimerais pouvoir faire une commande d'articles. Je ne sais pas à l'avance combien d'articles l'utilisateur va vouloir, exemple N articles. Je ne sais pas du tout comment dynamiquement les déclarer dans le form pour que plusieurs case s'affiche. En gros pour l'url articles/5/ je voudrais que 5 forms.MultipleChoiceField apparaissent, pour artciles/7/ il y en ai 7. Je sais deja comment récuperer N en fonction de l'url, mais je sais pas les déclarer. J'ai essayer une list mais rien ne s'affiche dans mon site on dirait que ca ne marche pas. Mon code dans forms est : class ArticlesForm(forms.Form): article = [] def NumArticles(self, nbArticles): self.nbArticles = nbArticles MyProp = ((1, 'Item title 1'), (2, 'Item title 2'), (3, 'Item title 3'), (4, 'Item title 4'), (5, 'Item title 5')) for i in range(nbArticles): self.article.append(forms.MultipleChoiceField(choices = MyProp)) nom = forms.CharField(max_length=100) Ici y'a un charfield nom qui s'affiche, mais la list article semble toujours vide, quand je l'appel je fait form = ArticlesForm(request.POST or None) form.NumArticles(nbArticles) Et normalement dans ma tete la list d'article est modifié mais il semble que non ? est-ce que quelqu'un à une idée de comment afficher dynamiquement … -
How to store upperbound to infinite DecimalRangeField
from django.contrib.postgres.fields import DecimalRangeField Django3 and Postgres11 I need to store inf in the DecimalRangeField() from django.contrib.postgres.fields import DecimalRangeField from psycopg2.extras import NumericRange class Premium(models.Model): sum_insured = DecimalRangeField() NumericRange with small number is work def test_range_field(self): Premium.objects.create( sum_insured=NumericRange(3, 12), ) self.assertEqual(1, Premium.objects.count()) Problem: Premium.objects.create( sum_insured=NumericRange(3, float('inf')) ) It raises error django.db.utils.ProgrammingError: syntax error at or near "Infinity" Question: How do I store the inf in the DecimalRangeField? -
function() got an unexpected keyword argument 'name1'
I am keep getting this typeerror:fun() got unexpected keywar arg, can someone tell what is the issue. Thanks in advance def register(request): if request.method =='POST': nm=request.POST['nm'] email1=request.POST['email'] pass1=request.POST['pass1'] pass2=request.POST.get('pass2') num=request.POST['num'] if pass1==pass2: new=register(name1=nm,email=email1,password=pass1,phone=num) new.save() #message.success(request,"You are register Successfully!") print("User Register") else: return redirect('/register') else: return render(request,'register.html',) -
Django models error: ValueError: Field 'cat' expected a number but got '-'
i just add 2 models to my class and i got this error: ValueError: Field 'cat' expected a number but got '-'. my code: # Create your models here. class News(models.Model): title = models.CharField(default=',', max_length=50) name = models.CharField(default=',', max_length=50) short_txt = models.TextField() body_txt = models.TextField() date = models.CharField(default=',', max_length=12) writer = models.CharField(max_length=50) catname = models.CharField(max_length=20, default='-') catid = models.IntegerField(max_length=10, default=0) def __str__(self): return self.name I had a cat model, but I removed it before... Thank you for your time<3 -
Django custom authentication using an external API endpoint
I have an API endpoint from my company that takes username and password and returns 200 response if the user is authenticated. The response body has all details about the user like user_id, name etc. Another endpoint allows a GET request with user_id as a parameter and tells if user is authenticated. For login: I use the first endpoint with POST request to check response code and also set user_id in my session so that i can later use this user_id to send a GET request to see if user is still authenticated. How can I use this in combination of login_required decorator to make sure user is authenticated for all the views in my application? Or is there any other way I can customize middleware.py for this functionality? -
get_initial() function simplification
I am populating a form with instance objects of another model like this: class ProcessingCreate(generic.CreateView): model = ProcessingActivityInstance template_name = 'dpapp/processing-create.html' fields = '__all__' def get_initial(self): initial = super(ProcessingCreate, self).get_initial() initial.update({'processing_toptype': ProcessingActivity.objects.get(id=self.kwargs['pk']), 'processing_type': ProcessingActivity.objects.get(id=self.kwargs['pk']), 'processing_description': ProcessingActivity.objects.get(id=self.kwargs['pk']), 'processing_purpose': ProcessingActivity.objects.get(id=self.kwargs['pk']), 'processing_category': ProcessingActivity.objects.get(id=self.kwargs['pk']), 'processing_legalbasis': ProcessingActivity.objects.get(id=self.kwargs['pk']), 'processing_retention': ProcessingActivity.objects.get(id=self.kwargs['pk']), }) return initial This code works but I suspect there is a cleaner way to reach the same result and I don't find it. Could someone enlighten me please? Thank you very much ! -
Best Way To Manage Model Instances Based On Attributes In Django Admin
Lets say I have a model: class Applicant(models.Model): name = models.CharField() status = Models.CharField(choices=Choices) Lets say Choices gives the choices of Reviewed, Rejected, Accepted. I want to be able to declare a choice for an instance in the admin panel, and once I save the choice, the instance is moved to another section, preferably another admin folder such as Reviewed Applicants, Rejected Applicant, etc etc. Whats the best way to achieve this? Thank you -
Cron jobs from DB in Django
I have some DB records like class Rules(models.Model): server = models.ForeignKey(Servers, on_delete=models.CASCADE) rule_text = models.CharField(max_length=2000) i.e. some rules, linked with server. Each rule is a crontab string like 0 9-17/2 * * 1-5 I want to call server_stop(server) and server_start(server) basing on all the rules, I have in DB (and add/edit/delete rules) Is it possible? -
Django serializer not returning all fields in response
I have following serializer in Django. The serializer is however not returning all the fields in the response. 'amount' and 'amount_ordered' are not returned, all other fields are.. key point: these are the only 2 fields I have in my model. So I thought I only need to add them in the fields list? class AdminOrderItemSerializer(serializers.Serializer): purchase_order = serializers.CharField(source="get_purchase_order") reference = serializers.CharField(source="get_reference") class Meta: model = OrderItem fields = [ "purchase_order", "reference", "amount", "amount_ordered", ] def create(self, validated_data): pass def update(self, instance, validated_data): pass Model: class OrderItem(models.Model): ordered_amount = models.IntegerField(validators=[MinValueValidator(0)]) amount = models.IntegerField(default=0) order = models.ForeignKey( Order, on_delete=models.CASCADE, related_name="order_items" ) def get_purchase_order(self): return self.order.purchase_order def get_reference(self): return self.order.reference -
Is it possible to add permission to a group given by the admin to see this view?
I have a problem with adding permission for a group of users ('judges') and I would like to ask if there is any possibility to add such a decorator enter image description here enter image description here -
How to run a python script in the background django
I have a python script (ml.py)that generates some data. I want it to run it in the background daily at 1 AM. How to achieve that ? I tried installing django-background-tasks and created the following files tasks.py from background_task import background @background(schedule=1) def hello(): execute('./scripts/ml.py') hello(repeat=Task.Daily) In the shell, I executed the following command: python manage.py process_tasks Now I get an error saying that the name execute is not defined My other questions are : Do I have to write the command python manage.py process_tasks everyday ? Can I exit out of the command window and does the process still run everyday ? -
Django radio buttons appearing as bullet point list, inside mark_safe()
Background I have used 'mark_safe()' inside a form in order to display bullet points in my form label: class FormFood(forms.Form): CHOICES = [ (1,'Yes'), (2, 'No')] response = forms.ChoiceField(widget=forms.RadioSelect, label=mark_safe("Do you like any of these foods? <ul><li>Pasta</li><li>Rice</li><li>Cheese</li><</ul>"), choices=CHOICES) This outputs as: The problem As you can see above, bullet points are now also appearing next to 'Yes' and 'No' despite me not wanting this. Inspecting the elementing reveals that this is because they are also structured inside an unordered list tag (somehow?): <form method="POST"> <label for="id_response_0">Do you like any of these foods? <ul> <li>Pasta</li> <li>Rice</li> <li>Cheese</li> </ul> </label> <ul id="id_response"> <li> <label for="id_response_0"> <input type="radio" name="response" value="1" required="" id="id_response_0"> Yes </label> </li> <li> <label for="id_response_1"> <input type="radio" name="response" value="2" required="" id="id_response_1"> No </label> </li> </ul> <input type="hidden" name="csrfmiddlewaretoken" value="FaOTY4WlVLFMl3gNtut8BJihJKub1Is0wRJRxxLck1e2eJocJVXRiGoOLDr9jdvx"> <input type="submit"> </form> Is there a way I could stop this and just maintain the bullet points on the 'Pasta', 'Rice' and 'Cheese' whilst removing the bullet points/ list from 'Yes' and 'No'? -
IndexError: pop from empty list Django Rest Framework
I have an existing object but I want to create an object in the nested serializer, unfortunately, I am getting an error while creating object. What I have done so far here: class AppealSerializer(serializers.ModelSerializer): resolutions = ResolutionSerializer(many=True, allow_null=True, required=False) class Meta: model = Appeal fields = ['id', 'appeal_unique_id', 'short_name', 'category', 'dept', 'state', 'appeal_desc', 'location', 'address', 'created_at', 'updated_at', 'resolutions', 'user'] def update(self, instance, validated_data): bp_data = validated_data.pop('resolutions', []) bps = (instance.resolutions).all() bps = list(bps) instance.state = validated_data['state'] instance.save() for b_p in bp_data: bp = bps.pop(0) bp.user = b_p.get('user', bp.user) bp.comment = b_p.get('comment', bp.comment) bp.is_read = b_p.get('is_read', bp.is_read) bp.save() return instance here I am going to create many to one object by updating an existing object. with this code, in another project, I can cope with it but it does not work for this project. please if anything is not clear let me know I will try to explain in more detail. The keyword is to create an object by updating an existing object. Thanks in advance -
Tell Django tests.py to use fixture instead of actual database
I need to test my database without adding or deleting elements. For this I have created a fixture. Loading the fixture seems to be fine, at least it is not giving any errors. Now, how do I tell the test functions to interact with the test database instead of the real database. Also, how do I propagate this infomration to the functions that are being tested? This is my current code: """Module to test upload app.""" import os import wave from django.test import TestCase, Client from django.urls import reverse, resolve from equestria.settings import BASE_DIR from .views import UploadProjectView from .models import File from django.core.management import call_command from scripts.models import Project from django.core.files.uploadedfile import SimpleUploadedFile class TestUpload(TestCase): """Test the upload app.""" fixtures = ['equestria/upload/db.json'] def setUp(self): self.project = Project.objects.all()[0] self.url = reverse('upload:upload_project', args=[self.project]) self.client = Client() def test_upload_url_resolves(self): self.assertEquals( resolve( self.url ).func.view_class, UploadProjectView) def test_redirect_before_auth(self): response = self.client.get(self.url, follow = True) redir_url = response.redirect_chain[0][0] redir_code = response.redirect_chain[0][1] self.assertRedirects(response,'/accounts/login/?next=/upload/1',status_code=302, target_status_code=200) self.assertEqual(redir_code, 302) self.assertEqual(redir_url, '/accounts/login/?next=/upload/1') def test_valid_file_ext_upload(self): self.client.login(username='test', password='secret') initial_files = len(File.objects.all()) audio_file = wave.open(os.path.join(BASE_DIR, "upload/test_files/test.wav"), "rb") data = { 'f':audio_file } response = self.client.post(self.url, data, format='multipart') current_files = len(File.objects.all()) print(initial_files) print(current_files) self.assertEqual(initial_files + 1, current_files) self.assertEqual(response.status_code, 200) All tests run just fine … -
Django form : how to get data in a ManyToMany field?
My objective is to implement the same kind of features than in admin panel with a many to many relationship. Everything seem to work all right, but when I submit my form, I get some strange results: I'm probably missing something but I cannot fogure out what goes wrong. For now, when I add lines, everything is OK. Problems occur when I try to remove lines from the group. I'm taking about users, I have a first list of 'all users' and the second one will make a group. When I had a user, then remove another one, the form cannot be validated; the list is empty, the removed user "disappear" (it is not in the group list nor among "all users". If I remove one user, then add a new one, the only user in my form after validation is the one I added, all other ones are removed. I hope I'm clear, many thanks in advance for your advise. Here are the related code blocks. Models: class UserComp(models.Model): """ Link between users and companies Used to restrict display to companie(s) the users belong to """ user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name="Utilisateur") company = models.ForeignKey(Company, on_delete=models.CASCADE, verbose_name="Société") phone_regex = RegexValidator(regex=r'^0[0-9]([ … -
nginx docker container as reverse proxy for services running in docker containers
I have nginx running in a docker container which I want to use as reverse proxy for services running in docker containers. ATM I have two services, django and owncloud. Both services works when accessing them directory e.g. localhost:4000 and localhost:5000. When I'm accessing localhost/owncloud I get 502 Bad Gateway Nginx log: 2020-04-27T13:21:54.852082794Z 2020/04/27 13:21:54 [error] 6#6: *2 connect() failed (111: Connection refused) while connecting to upstream, client: 172.18.0.1, server: , request: "GET /owncloud/ HTTP/1.1", upstream: "http://172.18.0.4:4000/", host: "localhost" When I'm accessing localhost/django I get page not found from Django, which is fine, but I if I try to access localhost/django/admin I get page not found from Nginx. Nginx log: 2020-04-27T13:29:11.173933857Z 2020/04/27 13:29:11 [error] 6#6: *4 "/etc/nginx/html/sv/admin/index.html" is not found (2: No such file or directory), client: 172.18.0.1, server: , request: "GET /sv/admin/ HTTP/1.1", host: "localhost" I'm new to Nginx and have messed around with the nginx.conf a lot with no success. Here are the relevant files: /docker-compose.yml version: '3' networks: nginx-net: /nginx/docker-compose.yml version: '3' services: internal-nginx: build: context: ./nginx restart: unless-stopped image: web-nginx container_name: nginx ports: - "80:80" - "443:443" networks: - nginx-net depends_on: - internal-django - internal-owncloud /nginx/Dockerfile FROM nginx COPY nginx.conf /etc/nginx/nginx.conf COPY nginx.conf /etc/nginx/nginx-raw.conf RUN rm … -
How to create Django models from oracle table-synonyms using inspectdb command
I am using Oracle legacy database from which I am creating models using inspectdb command(inspectdb table_name) for existing tables. But this command is only working for tables and views not for table-synonym. Please correct me if I am wrong: There is no way to specify schema with table name as : [schema].[table_name] in Django framework. So, I found a solution on the given link How to access tables from a different schema in oracle 11g using django? I create private table-synonym in oracle db and use inspectdb [synonyme_name] command but unable to inspect the synonym. This command working fine for table and view but not for synonym. inspectdb WASTE2 error-screenshot -
How to display a spatial field on a map?
I have a spatial field in my Django model. I want to display this field on a map. How to do it? It works just fine in Django Admin with Django built-in OSMWidget and OpenLayers. If I try to access the spatial field in my template it is of this format: SRID=4326;GEOMETRYCOLLECTION (POLYGON ((54.57842969715517 23.34800720214843, 54.53144199643833 23.29547882080078, 54.52964902093564 23.38096618652343, 54.57444978782305 23.40499877929688, 54.57842969715517 23.34800720214843))) -
when I using celery with multiple processing , the notify signal can't be received by waiting thread
when I using celery with multiple processing , the notify signal can't be received by waiting thread. but when I run the code with script, it works normally. Whether the problem is caused by celery poor support for multithreading? Please give me a hint if you can resolve the problem, thank you! # tasks.py @shared_task(bind=True) def long_time_def(self, *args, **kwargs): tp = ThreadPool(5) tp.set_tasks(pv.check_position_effective, list(args)) res = tp.final_results() while len(res) < len(args): print(res) return 'finished' # ../public/tools.py class ThreadPool: def __init__(self, max_thread_num=5): self.over = False self.results = [] self.func = None self.args_list = None self.task_num = 0 self.max_thread_num = max_thread_num self.pool = ThreadPoolExecutor(max_workers=max_thread_num) self.cond = threading.Condition() def set_tasks(self, func, args_list): self.task_num = len(args_list) self.args_list = args_list self.func = func def get_result(self, future): self.results.append(future.result()) if len(self.args_list): args = self.args_list.pop() task = self.pool.submit(self.func, *args) task.add_done_callback(self.get_result) else: print("result:%s"%self.results) while self.task_num != len(self.results): print(self.results) time.sleep(1) print('\n', 'finish') self.cond.acquire() ############ this place ############ self.cond.notify() ############ this place ############ self.cond.release() return def _start_tasks(self): for i in range(self.max_thread_num): if len(self.args_list): args = self.args_list.pop() task = self.pool.submit(self.func, *args) task.add_done_callback(self.get_result) else: break def final_results(self): self._start_tasks() if self.task_num == len(self.results): return self.results else: # print("main locked") # self.cond.acquire() ############ this place ############ print("main waiting") self.cond.wait() ############ this place ############ # print("main … -
Django application page not showing when deploying to pythonanywhere.com
My application works perfect when run locally on my mac os, but when it is deployed to pythonanywhere (and also on my partners windows os laptop) one of the pages just shows the html code instead of the actual page as shown below: I dont know what the problem is as it runs locally fine. Here is my html page: ''' {% extends "base2.html" %} {% load static %} {% block content %} <header class="masthead"> <div class="overlay"></div> <div class="container my-4"> <div class="border border-light p-3 mb-4"> <div class="text-center"> <a href="/logbook/home/"><img src="{% static 'img/maplogbook1.png' %}" class="rounded mx-auto d-block" alt=""></a> </div> </div> </div> </header> <header class="masthead"> <div class="overlay"></div> <div class="container my-4"> <div class="border border-light p-3 mb-4"> <div class="text-center"> <a href="/logbook/create/" class="btn btn-lg btn-warning">New Post - Driving Instructor &rarr;</a> <a href="/logbook/learner/" class="btn btn-lg btn-dark text-warning">New Post - Learner Driver &rarr;</a> </div> </div> </div> </header> <div class="container"> <div class="row justify-content-center"> <div class="col-md-8 mt-3"> {% for post in posts %} <div class="card mb-4"> <div class="card-body"> <div class="container p-3 my-3 bg-dark text-white"> <h2 class="card-title text-dark "> <a href="% url "logbook:detail" slug=post.slug %}" class="btn btn-lg btn-warning">New Post - Driving Instructor &rarr;</a>. </h2> <h2 class="card-title text-dark "><a href="{% url "logbook:detail" slug=post.slug %}">{{ post.title }}</a></h2> </div> <p class="card-text text-muted h6">{{ …