Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can anyone suggest me a best Logging System for my applications?
I am trying to implement a log system in my flask and django apps. I don't want to store it in a text document. Because these files are keep on storing all the logs and at some stage I can not open/read them because of the larger size. Is there any other way to have a log system apart from this? -
How to run a process in Django view without "Apps aren't loaded yet" error?
In Django view, I'm trying to run a process as shown below. *I use Django 3.1.7: # "views.py" from multiprocessing import Process from django.http import HttpResponse def test(): print("Test") def test(request): process = Process(target=test) process.start() process.join() return HttpResponse("Test") But, I got this error below: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. So, I put the code below to settings.py to solve the error above following this solution: # "settings.py" import django django.setup() But, another error below is raised even though my SECRET_KEY setting is not empty: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. So, how can I run a process in Django view without Apps aren't loaded yet error: -
No module named 'core' django app deployed in Railway
Hi i'm having this error when i'm trying to make a post through admin, everything else works fine except for this module error. Let me be clear i'm a complete newbie, but i think that maybe is path problem?, but i don't know how to modified or change it while is hosted on Railway. my requirements.txt asgiref==3.5.2 boto3==1.26.4 botocore==1.29.4 Django==4.1.2 django-cors-headers==3.13.0 django-crispy-forms==1.14.0 django-environ==0.9.0 django-storages==1.13.1 environ==1.0 gunicorn==20.1.0 jmespath==1.0.1 Pillow==9.2.0 psycopg2==2.9.5 python-dateutil==2.8.2 s3transfer==0.6.0 six==1.16.0 sqlparse==0.4.3 tzdata==2022.5 urllib3==1.26.12 my procfile: web: gunicorn proyecto_web.wsgi --log-file - Change the path on virtual environment but i don't know how. -
Django Verbatum like template tag to show verbatim and rendered nodes
I am trying to make a template tag that will show a section of code verbatim, and also render it, it is to help me demo some code for my own tooling. Say I have this in a template: {% example %}import * as fancy from "{% static 'jslib/fancy.min.js' %}";{% endexample %} I wish to output it as (I will add some divs and styling, but this is distilling the problem into it's simplest form): import * as fancy from "{% static 'jslib/fancy.min.js' %}"; import * as fancy from "/static/jslib/fancy.min.js"; I looked at the django {% verbatum %} tag and tried to copy the logic: # django.template.defaulttags.py @register.tag def verbatim(parser, token): nodelist = parser.parse(('endverbatim',)) parser.delete_first_token() return VerbatimNode(nodelist.render(Context())) nodelist.render(Context()) prints out text nodes for the django verbatim tag, but if I copy the code my example tag prints out say StaticNodes and other types of nodes. The reason why is I think the django parser has some special checks to see if it is a verbatim node and handles if differently, as shown in the code below: # django.template.base.py -> def create_token if self.verbatim: # Then a verbatim block is being processed. if content != self.verbatim: return Token(TokenType.TEXT, token_string, position, lineno) … -
Django does not recognize my {% endblock %} tag in the html file
I get this error while trying to run my Django project: "Invalid block tag on line 7: 'endblock'. Did you forget to register or load this tag?" I am trying to make a base-template (base.html) and use it on my html file (index.html). The name of my Django project is "mysite", the name of the app in my Django project is "myapp" It looks like Django does not recognize my {% endblock %} tag, but i don't know why. This is the base-template file (base.html): {% load static %} <html lang="en"> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet", href="{% static 'myapp/style.css' %}"> <title>Document</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button … -
How to create order in admin after payment is completed
I'm making a website where you buy stuff and pay through PayPal. I am done with the PayPal part now I am trying to get a situation where after the payment is complete in checkout the item purchased goes to orders in the admin. This is the order model.py: class Order (models.Model): product = models.ForeignKey(Coinpack, max_length=200, null=True, blank=True, on_delete = models.SET_NULL) created = models.DateTimeField(auto_now_add=True) this is the PayPal code part in checkout.html: <script src="https://www.paypal.com/sdk/js?client-id=idexample&currency=USD"></script> <script> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); var total = '{{checkout.price}}' var productId = '{{checkout.id}}' function completeOrder(){ var url = "{% url 'complete' %}" fecth(url, { method: 'POST', headers:{ 'content-type':'aplication/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({'productId':productId}) }) } // Render the PayPal button into #paypal-button-container paypal.Buttons({ // Set up the transaction createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: total } … -
How speech_recognition with base64 audio?
I cannot get the base64 of an audio to extract the text, it shows me the following message "the source must be an audio source". If someone has experience with this library, I would appreciate the support from contextlib import nullcontext from django import http from django.http import HttpResponse, JsonResponse import speech_recognition as sr import base64 class Reconnition(): solicitud = nullcontext method = nullcontext def __init__(self, request, method): self.solicitud = request self.method = method def recognition_voice(self, base64P = ''): error = 'false' try: reconocimiento = sr.Recognizer() if self.method == 'internal': with sr.AudioFile("C:\\Users\\bgonzalez\\Downloads\\audiotesting.wav") as archivo: audio = reconocimiento.record(archivo) texto = reconocimiento.recognize_google(audio, language='es-MX') else: decode_bytes = base64.b64decode(base64P) audio = reconocimiento.record(b''+decode_bytes) # audio = sr. # texto = reconocimiento.recognize_google(audio, language='es-MX') audio = sr.AudioData(decode_bytes) texto = reconocimiento.recognize_google(audio, language='es-MX') error = 'false' except Exception as e: # work on python 3.x error = 'true' texto = str(e) return JsonResponse({'texto': texto, 'error':error}, safe=False, status=200) #HttpResponse("Hola") -
Docker can not find /app/entrypoint.sh: 4: ./wait-for-postgres.sh: not found
My OS is windows. Backend django, frontend React. databa pgadmin. All containers runds but the backend cannot found the entrypoint, but it is indeed here. I try the instruction on stackoverflow with similar issues but none of them fix it. Any one can helo me with this? I attached log file and related fiels here. /app/entrypoint.sh: 4: ./wait-for-postgres.sh: not found 51 static files copied to '/app/static', 142 post-processed. No changes detected Operations to perform: Apply all migrations: accounts, auth, campaigns, cases, common, contacts, contenttypes, django_celery_beat, django_celery_results, django_ses, emails, events, invoices, leads, opportunity, planner, sessions, tasks, teams Running migrations: No migrations to apply. Installed 1 object(s) from 1 fixture(s) Installed 1 object(s) from 1 fixture(s) Installed 1 object(s) from 1 fixture(s) -------------- celery@47bc8292147e v5.2.0b3 (dawn-chorus) --- ***** ----- -- ******* ---- Linux-5.10.16.3-microsoft-standard-WSL2-x86_64-with-debian-11.5 2022-11-09 20:04:14 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: crm:0x7fa12453a080 - ** ---------- .> transport: redis://redis:6379// - ** ---------- .> results: - *** --- * --- .> concurrency: 2 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . accounts.tasks.send_email . accounts.tasks.send_email_to_assigned_user . accounts.tasks.send_scheduled_emails . … -
KeyError: How to exclude certain parts when a part of the serializer is empty
I have this piece in my serializer which is using a nested serializer field. When i try to submit my form it will return a KeyError if I don't add anything inside "assigned facilities". I tried adding an else statement but that doesn't seem to be helping. The debugger is actually complaining about line two when the field is empty so how do i exclude it when there is no data submited in assigned_facilities field? I`m already using required=False, allow_null=True inside the serializer. def create(self, validated_data): assigned_facilities = validated_data.pop("assigned_facilities") instance = Lead.objects.create(**validated_data) for item in assigned_facilities: instance.leadfacility.create(**item) else: print("No Facilities Added!") return instance -
SSO manager, trying to pass cookies between websites
I have an application in python for SSO purposes. Users redirect from their website to this app, and the app returns an ACCESS_TOKEN to the website the user got redirected from. I want to redirect the user back to his website after the process and return the ACCESS_TOKEN as a COOKIE, but I don't know how to send the cookie to the user's browser. Thanks for any help. -
Define field in Django which can be of any type
Pymodm is being used to define my model for the MongoDB collection in Django. I want to declare a field that can store values of any type (List, String, or Integer). from pymodm import MongoModel, fields class DefinitionEntity(MongoModel): version = fields.IntegerField(required=True) value = fields.CharField(required=True) I want the "value" field to accept multiple types. Please tell me how to define that. Thanks in advance! -
Why isn't the data sent again after resfresh page in a POST request
I have used axios to send a POST request after pressing a button. I want to make sure not to send the data again after refreshing the page or clicking the button right after. When I refresh the page or click the button the data is not being sent. I suppose it's good but I don't know why. I'm using Vue for the front and Django for the back. In Vue: axios.post('http://127.0.0.1:8000/sendAbility/', params).then(response=>{...}) In Django: return Response({'success':'true'}) -
No module named 'graphene_djangographql_jwt'
I got error when I add graphql_jwt.refresh_token.apps.RefreshTokenConfig in INSTALLED_APPS. I ran the command " pip install django-graphql-jwt" but there is still some packages problems. Does anybody know about it? I am expecting to use GraphQL url with Django. I was going to give request access only auth users. -
How to prevent these malicious requests with nginx config?
My nginx server (using django) is getting hit with thousands of these types of requests per second: 199.127.61.178 - - [09/Nov/2022:08:20:42 +0000] "GET http://www.wuqiaoxianzajituan.com/ HTTP/1.1" 500 186 "http://www.wuqiaoxianzajituan.com" "Mozilla/5.0 (Linux; U; Android 2.3.5; en-in; Micromax A87 Build/GINGERBREAD) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1" 104.238.222.87 - - [09/Nov/2022:08:20:42 +0000] "GET http://www.wuqiaoxianzajituan.com/ HTTP/1.1" 400 55440 "http://www.wuqiaoxianzajituan.com" "Mozilla/5.0 (Linux; Android 8.0.0; SM-G950F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36" 172.93.110.55 - - [09/Nov/2022:08:20:42 +0000] "GET http://tucgd.lixil-kitchen.cn/ HTTP/1.1" 400 55373 "http://tucgd.lixil-kitchen.cn" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/537.86.4" 104.243.37.94 - - [09/Nov/2022:08:20:42 +0000] "GET http://you.br-sx.com/ HTTP/1.1" 400 55205 "http://you.br-sx.com" "Mozilla/5.0 (iPhone; CPU iPhone OS 11_2 like Mac OS X) AppleWebKit/604.4.7 (KHTML, like Gecko) Version/11.0 Mobile/15C114 Safari/604.1" 104.238.222.9 - - [09/Nov/2022:08:20:42 +0000] "GET https://skype.gmw.cn/?nf91C2a99VqP4D43fy6uPrgt0 HTTP/1.1" 400 55722 "https://skype.gmw.cn" "Mozilla/5.0 (iPad; U; CPU OS 4_3_5 like Mac OS X; de-de) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8L1 Safari/6533.18.5" 104.238.205.70 - - [09/Nov/2022:08:20:42 +0000] "GET http://eqksp.drtjy.com/ HTTP/1.1" 400 55224 "http://eqksp.drtjy.com" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36" 103.195.103.32 - - [09/Nov/2022:08:20:42 +0000] "GET http://eqksp.drtjy.com/ HTTP/1.1" 400 55192 "http://eqksp.drtjy.com" "Mozilla/5.0 (Windows NT 5.1; rv:40.0) Gecko/20100101 Firefox/40.0" 104.243.37.94 - - [09/Nov/2022:08:20:42 +0000] "GET http://you.br-sx.com/ HTTP/1.1" 400 55133 "http://you.br-sx.com" … -
failed to format database fetching values
i am trying to format the values for inserting to table of remote server database but i failing to format the values the get_values() failing to format the values and it is exit from script def get_values(listval): for i, x in enumerate(listval): if isinstance(x, unicode): listval[i] = x.encode('ascii', 'ignore') elif isinstance(x, datetime.datetime): listval[i] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") else: listval[i] = x return listval def cluster_template(): try: # Table Name: admin_learnings cmd = "SELECT * FROM cluster_templates" cursor1.execute(cmd) cluster_tmpls = cursor1.fetchall() for cluster in cluster_tmpls: # cluster['id'] = 19 cols = cluster.keys() print(cluster['id']) vals = get_values(cluster.values()) print(vals) try: print('try.................') # cursor2.execute("INSERT INTO %s (%s) VALUES (%s)" % ( # "cluster_templates", ",".join(cols), str(vals)[1:-1])) # dstconn.commit() print("success") except: print('failed to move') break return except Exception as e: srcconn.close() dstconn.close() i am calling get_values() function but it failing and exiting from script -
Django / Laravel Blade - send data from 1 module into 2 different blade templates
I have a blog section created in django which uses blade template files to display on the front end. This allows the user to add the blog content and set featured (yes/no) which will display the 'featured blog' first on the blog page. I am trying to create a separate module to include on the homepage which will grab the first 2 'featured' blogs. I have this in the models.py file. class New(models.Model): IS_FEATURED = ( (0, "No"), (1, "Yes") ) IS_POPULAR = ( (0, "No"), (1, "Yes") ) title = models.CharField(max_length=200, null=False, verbose_name='Title') slug = models.CharField(max_length=255, null=False, unique=True, verbose_name='Slug') keywords = models.CharField(max_length=300, blank=True, default="") description = models.CharField(max_length=300, blank=True, default="") genre = models.CharField(max_length=100, blank=True, default="") is_featured = models.IntegerField(choices=IS_FEATURED, default=0, null=False) is_popular = models.IntegerField(choices=IS_POPULAR, default=0, null=False) custom_meta_copy = models.TextField(blank=True, default="", help_text="Will be rendered inside head tag") og_title = models.CharField(max_length=300, blank=True, default="") og_description = models.CharField(max_length=300, blank=True, default="") og_image = models.FileField(upload_to='social/', blank=True, default="") twitter_title = models.CharField(max_length=300, blank=True, default="") twitter_description = models.CharField(max_length=300, blank=True, default="") twitter_image = models.FileField(upload_to='social/', blank=True, default="") intro_copy = models.CharField(max_length=200, null=False) content_copy = models.TextField(null=True, default="") image = models.FileField(upload_to=get_news_upload_path, blank=True, verbose_name="image", default="", help_text="Recommended: 1140x600") image_alt_text = models.CharField(max_length=300, blank=True, default="") published_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Meta: verbose_name = … -
Using the URLconf defined in ''.urls, Django tried these URL patterns, in this order:
First I know this is a common question. But I can't figure it out. So I have a application with name main. and I have in the main forlder a templates folder and a main folder. and in this folder I have all the html templates, like home.html. So the html page home.html looks like: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> TEST PAGE </body> </html> and my views.py: def home(request): return render(request, "main/home.html") and urls.py in main: path('', views.home), urls.py: path('main/', include('main.urls')), and settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', ] STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = 'C:\\static_files_cdbn' But if I go to: http://127.0.0.1:8000/main/home or http://127.0.0.1:8000/home I just get this error: Using the URLconf defined in schoolfruitnvwa.urls, Django tried these URL patterns, in this order: admin/ main/ [name='index'] main/ The current path, main/home, didn’t match any of these. Question. How to tackle this? -
How to put image in a pdf generated by reportlab which is stored in DO spaces - Django
I want to put my logo in pdf that is stored in digital ocean spaces. The code that I wrote was pdf.drawImage('https://dummycompany.sgp1.cdn.digitaloceanspaces.com/static/images/logo_name_header.svg', -0.10*cm,10*cm) this throws the below error fileName=<_io.BytesIO object at 0x000001D1CE603A90> identity=[ImageReader@0x1d1ce5e6f70] cannot identify image file <_io.BytesIO object at 0x000001D1CE603A90> The file is accessible if entered in the address bar. I do not understand what this error is, please suggest me what to do? -
Django and database MD5-based query
I have a model that represents a program written by the user in some programming language and the results of executing it against some test cases. The model looks like this: class UserProgram(models.Model): code = models.TextField(blank=True) execution_results = models.JSONField(blank=True, null=True) The user first types some code, which is autosaved by the frontend into the code field, then at some point they click a "Run" button, which causes a task to be scheduled which runs the current code inside of a sandbox, which returns a JSON object which details the results of the execution (the fields of this dict aren't relevant to my question), which is ultimately saved into the execution_results field. I want to be able to check whether the execution results object refers to the latest version of the code, i.e. the current value of the code field. This is used to check if, so to speak, the saved results are up to date or whether the user has made modifications to the code since the last time it was run which haven't been run yet. One solution could be to just add a field named code inside of execution_results which just contains the code the results refer to, … -
how to solve the secret key error in django project?
I was trying to run a django project from github and i keep getting this error i dont know how to solve it settings.py is split in to common.py and production.py This is common.py file from pathlib import Path import environ import os BASE_DIR = environ.Path(__file__) - 3 env = environ.Env( DEBUG=(bool, False) ) environ.Env.read_env() SECRET_KEY = env.str('SECRET_KEY') # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'storages', 'accounts', 'issues' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'tracker.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'tracker.wsgi.application' # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'EST' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) FIXTURE_DIRS = [ os.path.join(BASE_DIR, 'fixtures'), ] LOGIN_REDIRECT_URL = 'issues:my-issues' LOGOUT_REDIRECT_URL = 'login' below is production.py file … -
Django: How do i remove currently:""image_url" in django image edit form?
When i am trying to edit an image field, you can see the current image path and the upload field. What I want to do is to be able to replace the shown path(the "Currently: /image_url_path.jpg" with the actual image or even remove it totally. How can i achieve this? Template <label class="btn btn-icon btn-circle btn-active-color-primary w-25px h-25px bg-body shadow" data-kt-image-input-action="change" data-bs-toggle="tooltip" title="Change avatar"> <i class="bi bi-pencil-fill fs-7"></i> {{p_form.image}} <input type="file" name="avatar" accept=".png, .jpg, .jpeg" /> <input type="hidden" name="avatar_remove" /> </label> Output -
Improving Django Performance ideas
I have an application with such architecture: BACKEND: Python + Django SERVER: gunicorn + uvicorn + openshift ASYNC: Celery + Redis DB: Oracle STORAGE: S3 Celery, Redis and API are within the same namespace in openshift. I have Django-Toolbar installed for monitoring performance. I have observed that I have veeery long response time for my application: I have already optimized django queries, but I haven't noticed signifant improvement in performance. I know that there is a lot of variables and unknowns, but do you have any ideas where to look for possible improvements? Or maybe how to investigate it better? -
Can you parameterize a template tag library on template directory?
Let's say I'm writing a form template tag library for Django, but want to be able to render both Bootstrap and UIKit forms. The Python code will be identical, except for the template reference. Simplified @register.inclusion_tag('myforms/bootstrap/formrow.html') def form_row(fieldname, labelpos, labelsize, widgetsize): return {...} vs. @register.inclusion_tag('myforms/uikit/formrow.html') def form_row(fieldname, labelpos, labelsize, widgetsize): return {...} I would like to prevent the duplication of the python code, but the @register.inclusion_tag(..) function runs very early in the Django lifecycle, so I'm not sure if it is possible, or how to do it..? -
Getting the date from the form field before calling the template in UpdateView
to update the data in the table, I use the class o inherited from Updateview, the fields are automatically filled from the database, but can I somehow in my class get the data from the user_guid field? Here is my form and class code: class CampaignEditor(UpdateView): model = Campaigns template_name = 'mailsinfo/add_campaign.html' form_class = CampaignsForm def get_context_data(self): context = super().get_context_data() data = list(Emails.objects.values()) # you may want to further filter for update purposes data = MailsTableWithoutPass(data) context['data'] = data return context class CampaignsForm(ModelForm): class Meta: model = Campaigns fields = ['name', 'subject', 'body', 'user_guid'] widgets = { 'name': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Name' }), 'subject': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Subject' }), 'body': Textarea(attrs={ 'class': 'form-control', 'placeholder': 'Body' }), 'user_guid': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'User GuID' }), } -
Docker cache file permission
I use py-staticmaps repository for generate static map image, In normally I run this repo via python .main.py, it is working but I use the repo in Django and docker, I have a problem with cache files,. following error. What can I do? I build it locally al of them working normally but in server I run via docker-compose that is to be problem with cache