Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with upload FileField and ImageField in new django 3.0.4
I'm with a big issue about django 3.0.4. I'm using virtualenv with python3.6.9 and django==3.0.4, In my models at upload process the picture be saved in correct folder, but return error 500 on server and the data field (title, category, file_attach) aren't saved in database. If I change django to version==2.2 in virtualenv the picture be stored and save in database without errors. Some bug or hack in django==3.0.4? The project was created in django 3 but work fine in 2.2. Some solution? -
Check if user is in the manager column in order to create a post/task
I'm learning in DJango and I have learned alot of stuff from the documentation and also in StackOverflow. Right now, I'm kinda stuck and I just want to know who can I check in a class based view, if the user is in the manager column in job model/ It can also be in the manager model that's fine too. I tried using UserPassesTestMixinin order to check if user is part of it but I'm getting an error of Generic detail view createjob must be called with either an object pk or a slug in the URLconf. I just need someone to point me to the right direction or give me a hint.I also tried, this: class createjob (LoginRequiredMixin,CreateView): model = Job fields = ['member','title', 'description', 'file'] def form_valid(self,form): form.instance.manager=self.request.user return super().form_valid(form) But it's giving me an error of Cannot assign "<SimpleLazyObject: <User: edlabra>>": "Job.manager" must be a "Manager" instance. Here's my views.py: from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import ListView, CreateView from .models import Job, Member from profiles.models import User from django.contrib.auth.decorators import login_required # Create your views here. class jobs(LoginRequiredMixin,ListView): model = Job template_name = 'users/user_jobs.html' context_object_name = 'jobs' def get_queryset(self): return Job.objects.filter(member__member=self.request.user) … -
Override Bootstrap 4 Colors in PyCharm Django Project - Error: Can't find stylesheet to import
I am trying to import Bootstrap 4's bootstrap.scss file as described in Bootstrap's theming documentation. My IDE is PyCharm. My ultimate goal is to override Bootstrap 4's colors by importing bootstrap and overriding certain aspects that I want. The problem is, I can't seem to import bootstrap.scss into my custom.scss file relative to the node_modules directory in my project. Here is the structure of my project: learnsass - learnsass <-- main Django project files (ex: settings.py) - myapp - static - myapp - css - custom.scss <-- file I'm trying to import bootstrap from - custom.css <-- automatically generated from file watcher - custom.css.map <-- automatically generated from file watcher - ... - node_modules - bootstrap - dist - js - scss - bootstrap.scss <-- the bootstrap scss I'm trying to import in custom.scss - ... - jquery - popper.js - static - templates - venv - db.sqlite3 - manage.py - package.json - package-lock.json custom.scss My custom.scss file looks like this. $theme-colors: ( "primary": #cccccc, "danger": #840383, ); @import "~bootstrap/scss/bootstrap"; A terminal with the output message shows "Error: Can't find stylesheet to import." cmd.exe /D /C call C:\Users\Jarad\AppData\Roaming\npm\sass.cmd custom.scss:custom.css Error: Can't find stylesheet to import. ╷ 5 │ @import "~bootstrap/scss/bootstrap"; … -
Use of MinIO in Django rest framework
I am new to Django Rest environment. Now what I want to do is posting multiple images in Minio container using Django rest API s. Can please someone guide me how to achieve that. -
How to keep everything retained in memory while learning Django?
What is the best way to learn Django so that it retains in memory everytime we start to build something? I have tried learning Login and Registration processes and stuffs like these in Django via video lectures but I forget them after some time. I also try to retain the working logic behind it but still I forget those logics after some time. Is this problem caused to every newbie or it's happening with me only? Please help me on how to become pro in this, so that every time I use Django after a break I don't need to watch the whole video lectures!! -
How to execute the content based on dictionary data using if and else condition in django template?
Here the code snippet that working fine if "Triglycerides" is not in value2.test_name but providing me the output content twice (executing both if condition and the other when "Triglycerides" is in value2.test_name). <tr class="info"> <td>1</td> <td>Triglycerides</td> <td> {% for key, value in data.items %} {% for key2,value2 in value.items %} {% if value2.test_name == "Triglycerides" %} <div class="form-group"> <input type="text" class="form-control" name="triglycerides_result" value="{{ value2.results }}"> </div> </td> <td><div class="form-group"> <input type="text" class="form-control" name="triglycerides_uom" value="{{ value2.units }}"> </div></td> <td><div class="form-group"> <input type="text" class="form-control" value="10.00" name="triglycerides_lr"> </div></td> <td><div class="form-group"> <input type="text" class="form-control" value="190.00" name="triglycerides_hr"> </div></td> {% endif %} {% endfor %} {% endfor %} <td> <div class="form-group"> <input type="text" class="form-control" name="triglycerides_result" value=""> </div> </td> <td><div class="form-group"> <input type="text" class="form-control" name="triglycerides_uom" value=""> </div></td> <td><div class="form-group"> <input type="text" class="form-control" value="10.00" name="triglycerides_lr"> </div></td> <td><div class="form-group"> <input type="text" class="form-control" value="190.00" name="triglycerides_hr"> </div></td> </tr> I'm sure it's not a proper way to apply conditions to get the data. please let me know how will I make the above code works. Thanks. -
Inline formsets with django viewflow frontend
I can get an inline formset to work fine with django, but when trying to use viewflow and the built-in workflow frontend, I can't seem to get the inline form to work during the workflow. What is the proper way to reference the formset? Since the workflow models inherit from the viewflow.models.Process object, I can't seem to understand how to create the inline related model. Use case: I have a workflow with about 50 various fields and I can run the workflow just fine using the Flow and breaking up the process in logical parts in about 10 steps. However, After the process is started and the first 3 or 4 fields are entered, I want step 2 to be an inline form where various roles are assigned to users for this particular workflow event. I already have a separate table where they are manually assigned to roles and I can have the Flow assign the next task to whomever is assigned to that "steps" role and it works fine, but I want the action of assigning the roles to be part of the actual workflow itself. I suspect I should add the inlineformset as a field of the parent … -
sending the image to server through post request django
I am trying to send an image from python client to django server. But i failed to upload the file. The django code is models.py from django.db import models class File(models.Model): file = models.FileField() def __str__(self): return self.file.name Serializers.py from rest_framework import serializers from .models import File class FileSerializer(serializers.ModelSerializer): class Meta: model = File fields = "__all__" urls.py from django.urls import path from .views import * urlpatterns = [ path('', FileUploadView.as_view()) ] views.py class FileUploadView(APIView): parser_class = (FileUploadParser,) def post(self, request, *args, **kwargs): file_serializer = FileSerializer(data=request.FILES) print(type(file_serializer)) if file_serializer.is_valid(): print('abc') file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) python client code is import requests as req name = {'name': open('im.jpeg', 'rb')} resp = req.post('http://127.0.0.1:8000/upload', name) print(resp) print(resp.text) the output is {"file":["No file was submitted."]} Kindly help me on this -
crispy error |as_crispy_field got passed an invalid or inexistent field
I want to customize the django Model field according to my needs and submit the data into database. I did all the things accordingly. But after running the app i getting the crispy error. I can't able to find my errors. Please help me friends. Models.py is as follows from django.db import models from datetime import date from configration.models import AddSite, AddDepartment, AddCategory, AddDesignation, Rate # Create your models here. class EmployeeRegistration(models.Model): #Departmental Details EmpId = models.IntegerField(verbose_name='EmpId') Site = models.ForeignKey(AddSite,on_delete=models.CASCADE,max_length=150,verbose_name='Site') Department = models.ForeignKey(AddDepartment,on_delete=models.CASCADE,max_length=150,verbose_name='Department') Category = models.ForeignKey(AddCategory,on_delete=models.CASCADE,max_length=150,verbose_name='Category') Designation = models.ForeignKey(AddDesignation,on_delete=models.CASCADE,max_length=150,verbose_name='Designation') PfAllowance = models.BooleanField(default = True) EsiAllowance = models.BooleanField(default = True) Uan = models.PositiveIntegerField(null = False,verbose_name='Uan') Pf = models.PositiveIntegerField(null = True,verbose_name='Pf') AttendenceAward = models.BooleanField(default = True) AttendenceAllowance = models.BooleanField(default = True) ProfesionalTax = models.BooleanField(default = False) Rate = models.PositiveIntegerField(null = True) # Personal Details Name = models.CharField(max_length=150,verbose_name='Name') Father = models.CharField(max_length=150,verbose_name='Father') Dob = models.DateField() Gender = models.BooleanField(default = True) #Female = models.BooleanField(default = False) MaritalStatus = models.BooleanField(default = True) Address = models.CharField(max_length=200,verbose_name='Address') Aadhar = models.PositiveIntegerField(null=True) pan = models.CharField(max_length=10) choices = [('Working','WORKING'),('NotWorking','NOT WORKING')] Status = models.CharField(choices=choices,blank = False,max_length=10,verbose_name='Status') Doj = models.DateField(default = date.today) Doe = models.DateField(blank = True,verbose_name = 'Doe',null = True) def __str__(self): return '{name}'.format(name=self.Name) views.py is as follows from django.shortcuts import render … -
How to create a weekly summary of dated records in model django
I have a model that has entries for each day. I want to create a queryset with a subtotals (annotates) for a selection of fields in the model. This is what i have so far. Here is the model (or some of it!) class Shiftlog(models.Model): date = models.DateField(default=timezone.now) onlinetime = models.DurationField() trips = models.IntegerField(default=0) km = models.IntegerField(default=0) def weekcom(self): weekcom = self.date - timedelta(days=self.date.weekday()) return weekcom Here is the view code that represents what I am trying to achieve. report = Shiftlog.objects.values('weekcom').annotate(Sum('km')) Now this does not work. I see from other posts that the annotate functionality only works with model fields. I appreciate I can create a dictionary of weekcom (weekcommencing rows) and iterate through the model to populate some k,v buckets for each row (weekcom). However, this does not feel right. I also appreciate that this can be done in SQL directly (I have not gone to this option yet so i don't have the code), but I am trying to avoid this option too. Any guidance, much appreciated. Thanks! -
Django ORM: Filtering by array contains OuterRef within a subquery yields zero results
Here's an isolated ORM query: Purpose.objects.annotate( conversation_count=SubqueryCount( Conversation.objects.filter(goal_slugs__contains=[OuterRef("slug")]).values("id") ) ) Where SubqueryCount is: from django.db.models import IntegerField from django.db.models.expressions import Subquery class SubqueryCount(Subquery): template = "(SELECT count(*) FROM (%(subquery)s) _count)" output_field = IntegerField() When that query is run, the following sql is used (via djdt explain): SELECT "taxonomy_purpose"."id", "taxonomy_purpose"."slug", ( SELECT count(*) FROM ( SELECT U0."id" FROM "conversations_conversation" U0 WHERE U0."goal_slugs" @> ARRAY['ResolvedOuterRef(slug)']::varchar(100)[] ) _count ) AS "conversation_count" FROM "taxonomy_purpose" Note the ResolvedOuterRef(slug) injected into the ARRAY lookup as a string. Am I doing something wrong, or should I report this as a bug? If this is a bug, is there a known workaround (maybe creating a custom OuterRef class)? -
RecursionError when uploading certain images
I am attempting to create a model with an image input that is to be resized and hashed along with a thumbnail on save. However, I appear to to have created an infinite recursive call. Some images upload, create thumbnails, and generate hashes without issues, but one image causes the program to call self.thumbnail.save(new_name, img_file) (the last line of generate_thumbnail) endlessly. How can I save the image and avoid the recursive call? Any help is appreciated. This is a slightly different issue than my last question, RecursionError when trying to save image. Below are some properties of the image files I used which may or may not be relevant. Successful image properties: 3888x2592 JPEG RGB 1920x1280 PNG RGB Unsuccessful image properties: 360x720 PNG RGBA models.py import hashlib import os import re from base64 import b16encode from functools import partial from io import BytesIO from PIL import Image from django.db import models from mtm.settings import MEDIA_ROOT class Person(models.Model): prefix = models.CharField(blank=True, null=True, max_length=5) first_name = models.CharField(max_length=35) last_name = models.CharField(max_length=35) suffix = models.CharField(blank=True, null=True, max_length=5) image = models.ImageField(default=None, upload_to='people/') _image_hash = models.BinaryField(blank=True, null=True, default=None, max_length=16) thumbnail = models.ImageField(editable=False, null=True, default=None, upload_to='people/') _thumbnail_hash = models.BinaryField(blank=True, null=True, default=None, max_length=16) bio = models.TextField() phone = … -
image Not upload in Django and not created media folder
this is my code I am try to upload image to in media folder. all other field have been uploaded but image is not move to media folder and endly when i make migration do not create media folder url.py from django.contrib import admin from django.urls import path,include from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf.urls.static import static # for media from django.conf import settings # for media file install pillow package urlpatterns = [ path('admin/', admin.site.urls), path('user/', include('AdminDashboard.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += staticfiles_urlpatterns() Model.py from django.db import models from django.core import validators # this library is used for form validation from django.core.validators import ValidationError # Create your models here. class movie(models.Model): def min_length_check(self): if len(self)> 10: raise validators.ValidationError("value must be greater than 10") title = models.CharField(max_length=255) description = models.TextField(max_length=300) created_at = models.DateTimeField(auto_now_add=True) # this will add at one time updated_at = models.DateTimeField(auto_now=True) # created and updated every image = models.ImageField(upload_to='images',default='default.png') View.py from django.shortcuts import render, redirect from django.http import HttpResponse ,HttpResponseRedirect # this include for model for http request from .forms import movieForm #from .models import movie # Create your views here. def index(request): return render(request,"index.html") def userRegister(request): return render(request,"userReg.html") def adminRegister(request): return render(request,"admin/adminReg.html") def movieRegister(request, id=0): if … -
How can I get a response of from view model?
How can I get a response of an (object post) from View model. I have tried the code below I hashed to be sure that code has worked and thanks for god it succeeded. How can I get a response and make all objects showed in the View model case views.py from django.shortcuts import render, redirect from django.http import HttpResponse, HttpRequest, HttpResponseRedirect from django.views.generic import View from .forms import PostForm from .models import Post class PostView(View): all_objects = Post.objects.all() post_form = PostForm template_name = 'myapp/index.html' def get(self, request): post_form = self.post_form(None) return render(request, self.template_name, {'form': post_form}) def post(self, request): post_form = self.post_form(request.POST) if post_form.is_valid(): post_form.save() return redirect('myapp:index') return render(request, self.template_name, {'form': post_form, 'all_objects': self.all_objects}) ''' def index(request): all_objects = Post.objects.all() post_form = PostForm if request.method == "POST": post_form = PostForm(request.POST) if post_form.is_valid(): post_form.save() return render(request, 'myapp/index.html', {'form': post_form, 'all_objects': all_objects}) return render(request, 'myapp/index.html', {'form': post_form, 'all_objects': all_objects}) ''' -
Angular 8 datatables with django rest framework
I have to use angular 8 datatables with django rest framework. I have written the serverside code which return a restful api. Any help in writing the server side angular code will be of great help. I have tried using the documentation it is not working. Here is the rest framework code class DataTableListCreateAPIView(ListCreateAPIView): pagination_class = DataTablePagination search_parameters = () default_order_by = '' unfiltered_query_set = None def get_queryset(self): self.unfiltered_query_set = query_set = super(DataTableListCreateAPIView, self).get_queryset() order_by_index = int(self.request.query_params.get('order[0][column]',0)) orderable = bool(self.request.query_params.get('columns[{}][orderable]'.format(order_by_index), self.default_order_by).replace('.','__')) if order_by_index == 0 or not orderable: order_by_index = 1 order_by = self.request.query_params.get('columns[{}][data]'.format(order_by_index), self.default_order_by).replace('.','__') order_by_dir = self.request.query_params.get('order[0][dir]','asc') if order_by_dir == 'desc': order_by = '-{}'.format(order_by) search_queries = self.request.query_params.get('search[value]','').strip().split(' ') q = Q() if len(search_queries) > 0 and search_queries[0] != u'': for params in self.search_parameters: for query in search_queries: temp = { '{}__contains'.format(params):query, } q |= Q(**temp) query_set = query_set.filter(q) if order_by == '': return query_set return query_set.order_by(order_by) def get(self,request,*args,**kwargs): result = super(DataTableListCreateAPIView, self).get(request,*args,*kwargs) result.data['draw'] = int(request.query_params.get('draw',0)) result.data['recordsFiltered'] = result.data['count'] result.data['recordsTotal'] = self.unfiltered_query_set.count() del result.data['count'] result.data['data'] = result.data['results'] del result.data['results'] return result class ReligionDataTableView(DataTableListCreateAPIView): serializer_class = ReligionSerializer search_parameters = ('name',) default_order_by = 'name' queryset = Religion.objects.all() Which return the following result {"next":null,"previous":null,"draw":0,"recordsFiltered":10,"recordsTotal":10,"data":[{"id":5,"name":"Christian","created_date":"2020-02-09T03:13:11.892478Z","staff":null},{"id":1,"name":"Christian union","created_date":"2019-12-14T01:36:35.384599Z","staff":null},{"id":6,"name":"Jewish","created_date":"2020-02-09T03:13:29.611206Z","staff":null},{"id":4,"name":"Seventh Day Adventist","created_date":"2019-12-18T05:58:31.359246Z","staff":null},{"id":3,"name":"Seventh Day Adventist","created_date":"2019-12-14T01:52:52.485440Z","staff":null},{"id":8,"name":"Seventh day","created_date":"2020-03-08T01:45:57.534001Z","staff":null},{"id":7,"name":"YCS","created_date":"2020-03-08T01:44:46.555526Z","staff":null},{"id":2,"name":"Young Christian Association","created_date":"2019-12-14T01:36:54.039418Z","staff":null},{"id":12,"name":"ghdsghdsghsd","created_date":"2020-03-08T13:45:09.238152Z","staff":3},{"id":10,"name":"hhdhshjds","created_date":"2020-03-08T13:44:57.133368Z","staff":3}]} I … -
Django Annotated Query to Count all entities used in a Reverse Relationship
This question is a follow up question for this SO question : Django Annotated Query to Count Only Latest from Reverse Relationship Given these models: class Candidate(BaseModel): name = models.CharField(max_length=128) class Status(BaseModel): name = models.CharField(max_length=128) class StatusChange(BaseModel): candidate = models.ForeignKey("Candidate", related_name="status_changes") status = models.ForeignKey("Status", related_name="status_changes") created_at = models.DateTimeField(auto_now_add=True, blank=True) Represented by these tables: candidates +----+--------------+ | id | name | +----+--------------+ | 1 | Beth | | 2 | Mark | | 3 | Mike | | 4 | Ryan | +----+--------------+ status +----+--------------+ | id | name | +----+--------------+ | 1 | Review | | 2 | Accepted | | 3 | Rejected | +----+--------------+ status_change +----+--------------+-----------+------------+ | id | candidate_id | status_id | created_at | +----+--------------+-----------+------------+ | 1 | 1 | 1 | 03-01-2019 | | 2 | 1 | 2 | 05-01-2019 | | 4 | 2 | 1 | 01-01-2019 | | 5 | 3 | 1 | 01-01-2019 | | 6 | 4 | 3 | 01-01-2019 | +----+--------------+-----------+------------+ I wanted to get a count of each status type, but only include the last status for each candidate: last_status_count +-----------+-------------+--------+ | status_id | status_name | count | +-----------+-------------+--------+ | 1 | Review | 2 | … -
Change between muiltiple databases with Django
I have software that centralizes a database to group users, group permission and other things in common, such as the companies that each one can manage. Together, I have an area where I can switch between companies I manage. Each company has its database, but the users are the same. Is there a possibility to integrate something like this with the django admin? All companies manage the same tables on different bases, are companies in the same industry, but the data is separate. -
Django templates won't load but HttpResponse will
I recently began learning django and have been running into some trouble and I can't figure out why. My problem is quite simple: whenever I try to run my homepage with a template, it throws up a 404 error. My file hierarchy is as such: crm accounts templates accounts dashboard.html urls.py views.py crm urls.py In crm/urls, I have from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('accounts.urls')) Then in accounts/urls, there is, from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ] And in views, I have from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, 'dashboard.html') My dashboard.html is just a basic html file with a title and h1, that's it. Also, whenever I change return render(request, 'dashboard.html') to return HttpResponse('home') in my home function, it decides to show. -
Custom Field Validation Message Django
I have a field 'Reference_Number' in both my form and my model. The form should not be saved if this field is blank, and if it is blank, a customer error message should appear by the field. I have this set up currently as you see it below, but still I just get the django standard message 'Please Fill Out This Field'. What change do I need to make to show the error message that I defined in the forms.py? models.py class PackingList(models.Model): Reference_Number = models.CharField(max_length=100, null=True) .... forms.py class PackingListForm(forms.ModelForm): class Meta: model = PackingList fields = ['Reference_Number'] def Clean_Reference_Value(self): Ref = self.cleaned_data.get('Reference_Number') if not Ref: raise forms.ValidationError('This field is required') #this is the message that should show packlist.html (template) ... <td colspan="1">Reference: {{ form.Reference_Number }} {% for error in form.Reference_Number.errors %}<p>{{ error }}</p> {% endfor %}</td> ... views.py def PackingListView(request): if request.method == "POST": form = PackingListForm(request.POST) if form.is_valid(): if 'preview' in request.POST: request.session['data'] = form.cleaned_data return redirect('myview') elif 'save' in request.POST: form.save() messages.success(request, "Success: Packing List Has Been Created!") return redirect('HomeView') else: form = PackingListForm() return render(request, 'packlist.html', {'form': form}) -
Why doesn't my dynamically generated stylesheet (Django) get applied by my html pages?
I am using Django and have set up a view that returns a dynamically generated stylesheet to allow for user themes. I link the stylesheet in the head section of my pages with, <link href="/theme.css" rel="stylesheet"> I can see the request for /theme.css at the server and a successful response. I can also view the source of the page in the browser and it shows the correct contents for the stylesheet. However, for some reason the styles in theme.css are not applied to the page. If I place the contents of the dynamically created stylesheet into a static file and change the link like so, <link href="/static/rml/css/theme.css" rel="stylesheet"> the styles are correctly applied. I can't see why there is a difference. I have looked for answers and can't find anything relevant. -
How make local http request in flutter?
I'm making an app, and i already have a server running in my local. I can acess trought my navigator the url: Request URL: http://localhost:4444/categorie?page_size=15&page=1 Request Method: GET Status Code: 200 OK Remote Address: 127.0.0.1:4444 Referrer Policy: no-referrer-when-downgrade Preview: { "count": 4, "next": null, "previous": null, "results": [ { "uid": "_b656062d3754", "name": "Pinga" }, { "uid": "_0c644473c244", "name": "Cerveja" }, { "uid": "_75df557ccbaa", "name": "Vinhos" }, { "uid": "_8e32ce3baded", "name": "Refrigerantes" } ] } But when i try in flutter, the request never respond: getCategories() async { String url = 'http://localhost:4444/categorie?page_size=15&page=1'; var response = await http.get(url); if (response.statusCode == 200) { // If the call to the server was successful, parse the JSON return response.body; } else { // If that call was not successful, throw an error. throw Exception('Failed to load post'); } } I'm running the server in my Windows10 using Django. And my flutter app is in the Android Studio using a Virtual Machine as device. I tryed to change the ip to 127.0.0.1 and 10.0.0.1 but still not working. Have i change the host of Django or enable any configuration in my flutter or inside VirutalBox? My dependencies: environment: sdk: ">=2.1.0 <3.0.0" dependencies: flutter: sdk: flutter … -
class mixing with MRO
I want to override a method of django.db.backend class and calling super() but leaving other method states untouched. These are bult-in classes in utils.py class CursorWrapper(object): def execute(self, sql, params=None): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if params is None: return self.cursor.execute(sql) else: return self.cursor.execute(sql, params) class CursorDebugWrapper(CursorWrapper): # XXX callproc isn't instrumented at this time. def execute(self, sql, params=None): start = time() try: return super(CursorDebugWrapper, self).execute(sql, params) finally: stop = time() duration = stop - start sql = self.db.ops.last_executed_query(self.cursor, sql, params) self.db.queries_log.append({ 'sql': sql, 'time': "%.3f" % duration, }) logger.debug('(%.3f) %s; args=%s' % (duration, sql, params), extra={'duration': duration, 'sql': sql, 'params': params} ) def executemany(self, sql, param_list): ... Now i created make own implementation of execute method to log. class Mixin(object): def execute(self, sql, params=None): start = time() try: temp = super(Mixin, self).execute(sql, params) stop = time() duration = stop - start sql = self.db.ops.last_executed_query(self.cursor, sql, params) self.db.queries_log.append({ 'sql': sql, 'time': "%.3f" % duration, }) logger.debug('(%.3f) %s; args=%s' % (duration, sql, params), extra={'duration': duration, 'sql': sql, 'params': params} ) return temp except Error as e: stop = time() duration = stop - start sql = self.db.ops.last_executed_query(self.cursor, sql, params) self.db.queries_log.append({ 'sql': sql, 'time': "%.3f" % duration, }) logger.error('(%.3f) %s; args=%s' % (duration, sql, … -
Multiple audio players are not working - only the first one (Javascript)
I have product cards that each have a player. What is expected: Each player should play its own track when clicked on the play button. What is happening right now: When I click on any of the play buttons it plays the first track only. Here is my code: let isPlaying = false let playBtn = document.querySelectorAll('.playerButton'); for (var i = 0; i < player.length; i++) { if (playBtn != null) { playBtn[i].addEventListener('click', togglePlay); } } // Controls & Sounds Methods // ---------------------------------------------------------- function togglePlay() { let player = document.querySelectorAll('.player') if (player.paused === false) { player.pause(); isPlaying = false; document.querySelector(".fa-pause") .style.display = 'none'; document.querySelector(".fa-play") .style.display = 'block'; } else { player[0].play(); document.querySelector(".fa-play") .style.display = 'none'; document.querySelector(".fa-pause") .style.display = 'block'; isPlaying = true; } } {% for product in products %} <div class="card-trip"> <div class="player-section"> <img src="{{ product.image.url }}" /> <div class="audio-player"> <a class="playerButton"> <span> <i class="fas fa-play"></i> </span> <span> <i class="fas fa-pause"></i> </span> </a> <audio id="player" class="player"> <source src="https://api.coderrocketfuel.com/assets/pomodoro-times-up.mp3"> Your browser does not support the audio element. </audio> </div> </div> <div class="card-trip-infos"> <div> <h2>{{product.name}}</h2> <p>{{product.description}}</p> <button class="btn" type="button">buy now - ${{product.price}}</button> <p>{{product.tag}}</p> </div> </div> </div> {% endfor %} -
Django 3.0.4 brings ASGI. Makes sense continue patching things with gevent?
I've tried run my django project through uvicorn but it led to the following error: DatabaseWrapper objects created in a thread can only be used in that same thread My django project patched things for gevent: the default gevent path_all plus psycogreen patch. Remove these patches makes the uvicorn works. But Why this errors occurs, is ASGI incompatible with gevent? -
How would I create a page fo a tournament that lets the user choose who won the match?
I currently have a page for each tournament on my website and this shows basic info (rules, creator, etc.). I want to create a page (linked to on this page) which shows all the matches for the round of the tournament I have calculated and then lets you pick which team won from the two. For example Team1 vs Team2 Click the winner I have a table called Match class Match(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE) score = models.IntegerField(db_column='Score', null=True) tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE) winner = models.BooleanField(db_column='Winner', null=True) How do I create a page that enables me to change the winner field with a button or something else? Please let me know if you need any more information