Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change value of dropdown in django forms
im trying to update my dropdown (which is in my django forms ) with the id that gets passed. For example views.py form = UploadRoomForm(initial={'companies': company_id}) forms.py companies = forms.ModelChoiceField(queryset=Company.objects.all().order_by('id')) but for some reason. it doesnt pick it up. what am i overlooking here ? when i output the form i get <option value="1" selected>Number 1</option> but in the loaded page i get <option value="" selected>---------</option> -
How to add tensorflow serving in my django postgres container?
Here is my Django container, docker-compose.yml version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data web: build: ./backend command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app ports: - "8000:8000" depends_on: - db My tensorflow serving run as follows docker run -p 8501:8501 --name tfserving_classifier --mount type=bind,source=C:\Users\Model\,target=/models/img_classifier -e MODEL_NAME=Model -t tensorflow/serving How can I add the above command for tensorflow serving into the same docker-compose of Django and postgres? -
Simple jwt not returning refresh token
I am using simple jwt with django rest. However i dont think the config JWT_AUTH is working. Because i have set the rotate refresh tokens to true but the token-api-refresh url only returns access token while it should also return the refresh. In the settings.py i have INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'shop', 'rest_framework_simplejwt', 'corsheaders', 'django_cleanup' ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ] } JWT_AUTH = { 'ACCESS_TOKEN_LIFETIME': datetime.timedelta(minutes=15), 'REFRESH_TOKEN_LIFETIME': datetime.timedelta(days=10), 'ROTATE_REFRESH_TOKENS': True, } -
Python's sqlite3 library sometimes returns naive datetimes and sometimes aware datetimes for the same column
I have a TIMESTAMP column in my SQLite database storing a datetime with a timezone, e.g. 2021-09-29 18:46:02.098000+00:00. When I fetch this row inside my Django app, the column is returned as an aware datetime object. However, when I fetch this row in a script that doesn't use Django, in the exact same code path, the column is returned as a naive object. Note that in both cases I am using the built-in sqlite3 library, not Django's ORM. Why are the return types inconsistent? -
unable to execute 'gcc': Permission denied error: command 'gcc' failed with exit status 1 on cPanel
Getting the following Error unable to execute 'gcc': Permission denied error: command 'gcc' failed with exit status 1 while installing mysqlclinet on cPanel pip install mysqlclient -
While running django machine learning model i am facing ModuleNotFoundError: No module named 'sklearn_pandas' confict
*Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, *kwargs) File "C:\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Python39\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Python39\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Python39\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Python39\lib\site-packages\django\core\checks\urls.py", line 57, in load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Python39\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python39\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python39\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python39\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) File "C:\Python39\lib\importlib_init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1030, in _gcd_import File "", line 1007, in _find_and_load File "", line 986, in _find_and_load_unlocked File "", line 680, in _load_unlocked File "", line 850, in exec_module File "", line 228, in _center code hereall_with_frames_removed File "C:\Python39\lib\site-packages\joblib\numpy_pickle.py", line 585, in load obj = _unpickle(fobj, filename, mmap_mode) File "C:\Python39\lib\site-packages\joblib\numpy_pickle.py", line 504, in _unpickle obj = unpickler.load() File "C:\Python39\lib\pickle.py", line 1212, in load dispatchkey[0] File "C:\Python39\lib\pickle.py", line 1528, in load_global … -
Getting template not found error in django
I have tried everything thing and path is correct in view.py but getting template doesn't found error in django My views.py def starting_page(request): return render(request,"tractor/index.html") def posts(request): return render(request,"tractor/all-post.html") I have also added ss of error and my directory. enter image description here enter image description here -
How to Convert Q Object of Django Queryset into SQL?
Suppose we have a Q expression like this: Q(price__lt=160) | Q(publishing_date__year__gte=2016) The SQL expression for this expression would be: price < 160 OR YEAR(publishing_date) >= 2016 I want a package which converts these Q objects of Django into the SQL equivalent. Like: q_obj = Q(price__lt=160) | Q(publishing_date__year__gte=2016) sql_expression = q_obj_to_sql(q_obj) # Please, recommend if there exists such a thing Note: Although Django provides a way to convert Querysets into SQL, but, I need to convert Q objects, and not the Querysets. -
How to disable a input field according to another select field value in bootstrap/crispy?
I'm trying to deactivate existing_name fields based on values that selected on action field I'm using crispy and rendering option for action field from models.py action = models.CharField(max_length=30, choices=[('add', 'Add'), ('delete', 'Delete'), ('modify', 'Modify'), ('rename', 'Rename')]) I had check all same question on Stackoverfllow and all suggested to deactivate it by script with changes happen action fields {% extends "KPI_App/base.html" %} {% load crispy_forms_tags %} {% block content %} <form action="" method="post" autocomplete="off" > {% csrf_token %} <div class="row"> <div class="col-md-4 id='1'">{{form.action|as_crispy_field}}</div> </div> <div class="row"> <div class="row id='existing_name' " >{{form.existing_name|as_crispy_field}}</div> <div class="row"> <div class="col-md-8"> <button type="submit" class="btn btn-success btn-block btn-lg"><i class="fas fa-database"></i> Submit</button> </div> <div class="col-md-4"> <a href="{% url 'KPI_list' %}" class="btn btn-secondary btn-block btn-lg"> <i class="fas fa-stream"></i> Back to List </a> </div> </div> </form> {% endblock content %} <script> $(document).ready(function(){ $("select[name='action']").on('change',function(){ if($(this).val()=='1'){ $("input[name='existing_name']").prop("disabled",false); }else{ $("input[name='existing_name']").prop("disabled",true); } }); }); </script> I can't assign id for these class and use it it script -
How can i make my Django API work for multiple users at the same time?
I created a Django API,lets say that take two numbers as input and returns the sum as output. I wanted my API to work even if i get multiple users request on the API. Can i solve this issue using ThreadPooling? if not can you suggest any other methods to handle multiple user request at the same time. Any kind of help will be really appreciated. Thanks in Advance -
Best practices to configure a modulable web application
I've been having trouble finding the best way to configure a javascript application (with django on the server side). For now, I created an application which is highly configurable using JSON files. For instance, I have some JSON files that defines the composition of pages. I can quickly create a page with a title, a paragraph, a form and a button to send the form by inserting elements in a JSON. So, this part is useful if I want to recreate quickly a new application based on what I already did. For now, when the user load the application, it sends an ajax that retrieve JSON configuration files and send them back where javascript properly creates pages. The thing is, I want to deploy the application using django, and I don't know if this is a good practice concerning security. Indeed django thows an error when I try to load a JSON file locally: In order to allow non-dict objects to be serialized set the safe parameter to False. I'm sure there is a way to remedy that issue but, looking up the internet, I found that django prefers loading data from a database. The thing is, I don't want … -
pyodbc.InterfaceError in pythonanywhere while deploying
I am getting this error while deploying my django website on python anywhere. Please help fixing this issue. -
Screenshot is not taking while screen sharing is on
I am doing a website using Django where i am trying to implement screenshot and screen sharing feature using javascript. I am trying to take screenshot using html2canvas which is a javascript library. In the same webpage, there is a feature of screen sharing besides screenshot. When i click on Take Screenshot, a screenshot of div of video screen is taken. But the video screen is not captured in the screenshot image. <html> <head runat="server"> <title>Demo</title> <style> #video { border: 1px solid #999; width: 50%; max-width: 860px; } .error { color: red; } #photo { width: 51%; border: 4px solid green; padding: 4px; } .warn { color: orange; } .info { color: darkgreen; } </style> <!-- Include from the CDN --> </head> <body> <h1>recording</h1> <form id="form1" runat="server"> <div> <p> This example shows you the contents of the selected part of your display. Click the Start Capture button to begin. </p> <p> <input type="button" id="start" value="Start Capture" />&nbsp; <input type="button" id="stop" value="Stop Capture" /> </p> <p> <a></a> </p> <div id="photo"> <video id="video" autoplay="autoplay"></video> <hr> <a onclick="takeshot()"> Take Screenshot </a> </div> <br /> <h1>Screenshot:</h1> <div id="output"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> const videoElem = document.getElementById("video"); const startElem = document.getElementById("start"); const stopElem = document.getElementById("stop"); // … -
Django filter data in table based on value from another table?
views.py : def dcuinterval(request): var7 = dcu.objects.all() MU_count = Meter_Mapping_Table.objects.filter(DCU_id=dcu.id).count() d = { 'MU_count': MU_count, 'var7': var7, } return render(request, 'dcu_interval.html', d) Models.py: class dcu(models.Model): id = models.AutoField(unique=True, editable=False, primary_key=True) Asset = models.CharField(max_length=128) IMEI_Number = models.CharField(max_length=128) def __str__(self): return self.Asset class Meter_Mapping_Table(models.Model): mid = models.AutoField(unique=True, editable=False, primary_key=True) Meter_id = models.CharField( max_length=128, help_text='(ID of the Meter table)') MU_id = models.CharField(max_length=150) DCU_id = models.CharField(max_length=150, null=True, blank=False) def __str__(self): return self.Meter_id how to filter the data based on the another table filed ? i need to filter the DCU_id based on the DCU tables id field DCU_id =1; DCU.id=1; ANSWER: MU_count=1 like this i need to filter and show that count -
Displaying Django DB values on index.html original path
I have a DB hat hs some values in it. I want to display these values on my index.html. i want to display them on the standard html path path('', views.index, name = "index"), I currently displaying them at path('this_is_the_path/', my_db_class.as_view()), The problem is that i am pulling the values from a class. and i can't figure out how to set the class to the original index.html path. Models.py from django.db import models class Database(models.Model): text = models.TextField() Views.py from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Database # Create your views here. def index(request): return render(request,"index.html",{}) class my_db_class(ListView): model = Database template_name = 'index.html' URLS.PY from django.urls import path from . import views from .views import my_db_class urlpatterns = [ path('', views.index, name = "index"), path('this_is_the_path/', my_db_class.as_view()), ] HTML.PY <ul> {% for post in object_list %} <li> {{ post.text }}</li> {% endfor %} </ul> So my problem is that the above code will only show my DB values at the this_is_the_path path, but i want to show it at the '' path. -
Complex Python module sorting dependency issue
I have a set of "modules" with dependencies. module B depends A module C depends on A and B module D depends on C I can represent each module as an object, and their dependencies as a property: class Module(): def __init__(self, name): self.dependencies = [] self.name = name def __repr__(self): return self.name A = Module("A") A.dependencies = [] B = Module("B") B.dependencies = [A] C = Module("C") C.dependencies = [A, B] D = Module("D") D.dependencies = [C] modules = [C, D, B, A] Suppose I have a list of modules in arbitrary order e.g. [C, D, B, A] Need to write function to take this input list and return a list of all of these modules in dependency order: e.g. [A, B, C, D] starting with A because it has no dependencies, then B because it only depends on A, then C, D for the same reasons. I am stuck in this please help with code, pseudo code """ class Module(): def __init__(self, name): self.dependencies = [] self.name = name def __repr__(self): return self.name # normal modules A = Module("A") B = Module("B") C = Module("C") D = Module("D") E = Module("E") F = Module("F") A.dependencies = [] B.dependencies … -
Django Redis-Queue pass result from background job into html
My small Django project only has one view. The user can enter some options and press submit, hence commiting the job that takes >3 minutes. I use redis-queue to carry out the jobs via a background process - the web process simply returns (and renders the .html). All this works. Question is, how can I pass the background's result (filename of file do be downloaded) after completion back into the html so I can display a download button? I guess I would have to put a small Java / jQuery script into the .html that keeps polling if the job has completed or not (perhaps making use of RQ's on_success / on_failure functions?), however, I'm unsure about the approach. Searching the matter has brought no success (see simular issue). Could anyone tell me if this is the way to go or if I have to fundamentally change my code? I do not intend to use Celery. Ideal solution would be the one providing some code. Here's a stripped example: view.py from django.shortcuts import render from django.contrib import messages from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from .forms import ScriptParamForm from .queue_job import my_job @csrf_exempt def home(request): context = {} … -
Using the TempFile Python Module to print multiple .pdf's at once
I am currently trying to print financial documents for companies based on the settings they have added to my app. These documents are checked by a Bool value (checkbox) to see if the user has this document selected. If it is selected , the document must print. However the program cannot currently print multiple documents at once for some reason. I don't know if it is because it cannot re-direct to multiple .HTML files at once? Please see the following code: import tempfile def printReports(request , reports_pk): pkForm = get_object_or_404(SettingsClass , pk=reports_pk) complexName = pkForm.Complex if pkForm.Trial_balance_Monthly == True: ### Printing Trial Balance PDF response = HttpResponse(content_type= 'application/pdf') response['Content-Disposition']= 'attachment; filename=TrialBalance' + \ str(datetime.now()) + '.pdf' response['Content-Transfer-Encoding'] = 'binary' content = {"x_AlltrbYTD":x_AlltrbYTD , 'xCreditTotal':xCreditTotal , 'xDebitTotal':xDebitTotal , 'complexName':complexName , 'openingBalances': openingBalances ,'printZero':printZero , 'printDesc':printDesc , 'printAcc':printAcc} html_string=render_to_string('main/reports/trialBalanceYear.html' , content) html=HTML(string=html_string) result=html.write_pdf() with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output.seek(0) response.write(output.read()) return response if pkForm.Trial_balance_Monthly == True: ### Printing Trial Balance PDF response = HttpResponse(content_type= 'application/pdf') response['Content-Disposition']= 'attachment; filename=TrialBalanceMonthly' + \ str(datetime.now()) + '.pdf' response['Content-Transfer-Encoding'] = 'binary' content = {"xtrbMonth":xtrbMonth , 'xCreditTotalM':xCreditTotalM , 'xDebitTotalM':xDebitTotalM , 'complexName':complexName , 'printZeroM':printZeroM} html_string=render_to_string('main/reports/trialBalanceMonthly.html' , content) html=HTML(string=html_string) result=html.write_pdf() with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output.seek(0) response.write(output.read()) else: … -
need some explanation about pillow in django
i have a caroussel and i want all my images to have the same height for that is used this to compress the image. def compressImage(uploaded_image): image_temp = Image.open(uploaded_image) outputIoStream = BytesIO() image_temp.thumbnail((500,500)) image_temp.save(outputIoStream , format='JPEG', quality=99) outputIoStream.seek(0) uploaded_image = InMemoryUploadedFile(outputIoStream,'ImageField', "%s.jpg" % uploaded_image.name.split('.')[0], 'image/jpeg', sys.getsizeof(outputIoStream), None) return uploaded_image class RecognizePost(models.Model): name = models.ForeignKey(Post,on_delete=models.CASCADE) image = models.ImageField(upload_to='files', null=True, blank=True) def __str__(self): return self.pk def save(self, *args, **kwargs): if not self.pk: self.image = compressImage(self.image) super(RecognizePost, self).save(*args, **kwargs) my question why if have two images then the compress works like this: original image1 (735x739) after compress (498x500) original image2 (880x612) after compress (500x347) why i am not getting all 2 images with this (500x500).I really need the height to be 500.why the second image has 347.am i missing something ? -
dj restauth reset password customizing template not working
I am using dj rest auth package to register and login and for resseting password i have customized the template settings to use my own email html template: class CustomPasswordResetSerializer(PasswordResetSerializer): def save(self): request = self.context.get('request') # Set some values to trigger the send_email method. opts = { 'use_https': request.is_secure(), #'from_email': 'noreply@mizbans.com', 'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'), 'request': request, # here I have set my desired template to be used # don't forget to add your templates directory in settings to be found 'email_template_name': 'password_reset_email.html', 'html_email_template_name': 'password_reset_email.html' } opts.update(self.get_email_options()) self.reset_form.save(**opts) and in a file named email.py : class MyPasswordResetSerializer(PasswordResetSerializer): context={'domain':settings.WEBSITE_DOMAIN,'site_name':'mizban'} def get_email_options(self) : return { 'email_template_name': 'password_reset_email.html', 'context':'context' } the problem is this code works on my local pc and sends emails with customized html template but when i deploy it ,it still uses the default package's html template what am i missing? -
DataTable slow rendering large amount of data
I'm using serverSide process, and I have more than 10,000 but the rendering time is to long almost a minute. also tried using deferRender and deferLoading but still too slow. Apps uploaded in heroku and using paid add-ons. Anyone can suggest how to speed up rendering time and also if able to load by page.Like:(100/1000 data load every secs)? heroku logs: dyno=web.1 connect=0ms service=2557ms status=200 bytes=9409840 protocol=https $(document).ready(function() { var table = $('#vtable').DataTable({ "serverSide": true, "scrollX": true, "scrollY": "500px", "deferRender": true, "autoWidth":true, "columns": [] .......................... <table id="vtable" class="table table-striped table-bordered" style="width:100%" data-server-side="false" data-ajax="/api/Url/?format=datatables"> -
How to pass context to a different view function?(Django)
My models.py: class fields(models.Model): name = models.CharField(max_length=18) link = models.TextField() The link contains the hyperlink of the related name. My views.py: def index(request): listing = fields.objects.all() context ={'listing':'listing'} return render(request,'index.html',context) Now, I want to pass the context of this function which only includes the link to the other view function so that another view function will be: def bypass_link(request): # get the link from above function # execute some selenium scripts in the link The simple template to illustrate this will be: {% for i in listing %} <tr> <td data-label="name">{{ i.name }}</td> <td data-label="Quote"><button><a href ="{ % url 'bypass_link' %} " target="_blank">{{ i.link }}</a></button></td> <tr> {% endfor %} -
how to override django auth password reset email method?
I am using Django's authentication password_reset system in order to reset a forgotten password. Instead of django emailing the reset password link, I would like to perform another custom action with this email message (or link), for example send the message to a random API. How do I do it? -
uwsgi_master_fifo()/mkfifo(): Permission denied
Well I am trying to get django aplication on a prodaction server using uwsgi and docker. On production server nginx is started but it does not configured for uwsgi. I install uwsgi using pip without virtual environment into docker. However when I try up service with django app I get uwsgi_master_fifo()/mkfifo(): Permission denied [core/fifo.c line 112]. My uwsgi.ini: [uwsgi] socket = :8000 chmod-socket = 777 chdir = /api/ module = MenStore.wsgi:application static-map = /staticfiles=static master = true processes = 4 offload-threads = 4 vacuum = true harakiri = 30 max-requests = 10000 stats = :9191 memory-report = true enable-threads = true logger = internalservererror file:/tmp/uwsgi-errors.log post-buffering = 1 buffer-size = 16383 uid = 1000 gid = 1000 touch-reload = uwsgi-reload master-fifo = uwsgi-fifo My django app service into docker-compose file: api: &api build: context: Backend dockerfile: Dockerfile ports: - "8000:8000" volumes: - "/root/MenStore/media/:/api/media/:rw" command: uwsgi --ini /api/uwsgi.ini depends_on: postgres: condition: service_healthy redis: condition: service_started -
How to deploy Django project with React inside as an app to Heroku
Can someone help me to deploy my Django app, first I startproject with django and then startapp for front-end and api, npm react is installed inside front-end, I follow this project from https://www.youtube.com/watch?v=JD-age0BPVo&list=PLzMcBGfZo4-kCLWnGmK0jUBmGLaJxvi4j , and I follow the deployment steps from https://dev.to/mdrhmn/deploying-react-django-app-using-heroku-2gfa, here is my github for the project https://github.com/khuongduy354/django-rest-react, beside the working project in development mode, i made changes mostly in settings.py file and package.json for the deployment When i first ran git push heroku master, it said package.json must be in root, so I moved it from frontend to root, then it said cant find matching node version, i ran node --version and made sure it's the same as the one in package.json file Most of the tutorial separate backend and frontend files, so i don't really know how to deploy my app in my situation, can someone help me, thank you very much.