Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django localization / Language from model
I'm trying to take user language from UserProfile model. User choosing language in form, and after that website have to be translated on that language. I created switcher which can change language but it's not what i need because it doesn't communicate with my model. I know that i have to rewrite LocaleMiddleware, but i don't know how to do it in right way. I've tried some solution from stackoverflow, but it doesn't work for me. So the question is: what i'm doing wrong? or maybe there is no problem with middleware but problem somewhere else? My middleware: from django.utils import translation class LocaleMiddleware(object): """ This is a very simple middleware that parses a request and decides what translation object to install in the current thread context. This allows pages to be dynamically translated to the language the user desires (if the language is available, of course). """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): language_code = request.LANGUAGE_CODE translation.activate(language_code) response = self.get_response(request) translation.deactivate() return response def process_request(self, request): language = translation.get_language_from_request(request) translation.activate(language) request.LANGUAGE_CODE = translation.get_language() def process_response(self, request, response): translation.deactivate() return response My model: from core.settings.base import LANGUAGES, LANGUAGE_CODE class UserProfile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name="user_profile" ) … -
Depending on the selection of product variations, the link in the forwarding button also changes
I prepared the variation features of the products with the html buttons. As I select the properties of the variations, I could not enable the other variation properties to be activated and selected. After all these variation selections, I couldn't make the forward button's link orientation change according to the selected variations. Link that can be changed automatically as you add variants to products. How can I prepare the link that the next button will open when I click on the product additional feature buttons that I created with html and css, with python django? -
No module named 'signals' in Django Project
I'm practice Django and I'm trying to make function ( Ready ) in the app.py and import ( users.signals ) into this function and I already used pip install signals to install signals package and didn't solve it yet. apps.py `from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals` signals.py `from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save()` No module named 'signals' -
Next.js not receiving cookie from Django
I am messing around with Next.js and regular Django to do some testing, study etc. I am trying to make a basic authentication system that simply takes the email and password, send to the Django server and it simply returns a cookie with the user id. When I login with valid credentials, the server returns an "OK" (as it is supposed to do), however I don't get any of the cookies I'm supposed to have (not even the default csrf token from Django). (sample data for design testing) Using Django 4.0.6 and Next.js 12.3.1 Login route on Django @csrf_exempt def login(req): body = json.loads(req.body.decode("utf-8")) res = None if (User.objects.filter(email=body["email"])): user = User.objects.get(email=body["email"]) if (user.password == body["password"]): res = JsonResponse({"success": True}) res.status_code = 200 res.set_cookie("AuthToken", json.dumps( {"id": user.id}), max_age=60 * 60 * 24, httponly=False, samesite="strict", ) else: res = JsonResponse({"success": False}) res.status_code = 401 else: res = JsonResponse({"success": False}) res.status_code = 404 res.__setitem__("Access-Control-Allow-Origin", "*") print(res.cookies) return res My login page on Next import Link from "next/link"; import { useRouter } from "next/router"; import React, { FormEvent, useState } from "react"; import styled from "styled-components"; import { CONFIG } from "../../../DESIGN_CONFIG"; export default function Login() { const [email, setEmail] = useState(""); const … -
how to create django model by pressing button
I am fairly new django user a few months of project creation and messing around with it, and I have created models before using forms, but this would be my first time trying to create one using just a button, and I have no idea how to do that, I looked for examples on stackOverFlow and I found a few but I couldn't figure out how to apply them to my project I have a products model that uses a category model class Category(models.Model): class Meta: verbose_name_plural = 'Categories' name = models.CharField(max_length=254) friendly_name = models.CharField(max_length=254, null=True, blank=True) def __str__(self): return self.name def get_friendly_name(self): return self.friendly_name class Product(models.Model): category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.SET_NULL) sku = models.CharField(max_length=254, null=True, blank=True) name = models.CharField(max_length=254) description = models.TextField() has_tiers = models.BooleanField(default=False, null=True, blank=True) price = models.DecimalField(max_digits=6, decimal_places=2) image_url = models.URLField(max_length=1024, null=True, blank=True) image = models.ImageField(null=True, blank=True) favorites = models.ManyToManyField( User, related_name='product_favorites', blank=True) def __str__(self): return self.name and I have a favorite model class Favorite(models.Model): """ A Favorite model so users can save products as their favorites """ user = models.OneToOneField(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, null=False, blank=False, on_delete=models.CASCADE) I want that when a user is on the products_details.html page, which is just a normal page … -
Counting the number of rows with the same date but different type?
I have a model like this: class Class(models.TextChoices): STANDARD = "Standard", _("Standard") JWW = "JWW", _("JWW") class Competition(models.Model): cls = models.CharField(choices=Class.choices) date = models.DateField() I would like to get all of the dates where a Standard Competition occurred AND a JWW Competition occurred. My current solution takes a long time for a low number of rows (~300), and relies on an intersection query. I have a large amount of data upon which this calculation will need to be performed, so the faster the query, the better. Memory is not a concern. -
GraphQL - AssertionError: resolved field 'attributes' with 'exact' lookup to an unrecognized field type JSONBField
I'm trying to query a JSONBField in Python-Django. But Graphql throws this error: AssertionError: ResponseFilterSet resolved field 'attributes' with 'exact' lookup to an unrecognized field type JSONBField. Try adding an override to 'Meta.filter_overrides'. See: https://django-filter.readthedocs.io/en/main/ref/filterset.html#customise-filter-generation-with-filter-overrides Here is my query in my test.py: attributes_to_query = {"Priority": ["low"], "Category": ["Service", "Speed"]} response = self.query( """ query responses($attributes: GenericScalar){ responses(attributes: $attributes){ edges { node { id name attributes } } } } """, headers=self.get_auth_headers(), variables={ "attributes": attributes_to_query, }, ) Here is the schema.py class Response(AuthorizedObjectType): class Meta: model = models.Response fields = [ "id", "name", "attributes", ] filter_fields = ["id", "name"] >>>>>>> Adding "attributes" to this list causes the error mentioned above. filter_overrides = { models.Response: { "filter_class": django_filters.CharFilter, "extra": lambda f: { "lookup_expr": "icontains", }, }, } interfaces = (relay.Node,) class Query: response = relay.Node.Field(Response) responses = DjangoFilterConnectionField( Response, variables=graphene.Argument(GenericScalar), attributes=graphene.Argument(GenericScalar), ) def resolve_responses(self, info, **kwargs): queryset = models.Response.objects.all() if (attributes := kwargs.get("attributes")) is not None: queryset = queryset.filter( Q(attributes__icontains=attributes["Category"][0]) | Q(attributes__icontains=attributes["Category"][1]) ) queryset = queryset.filter(attributes__icontains=attributes["Priority"][0]) # TODO - Here I have the right 2 Responses, but test returns all, Why ? print("Qset", queryset.values()) return queryset # The values in this queryset are fine ! But in the tests they are different … -
query a user and the date range in which the user had an event using django
As the tile says, I want to specify a user and a date range in which an event happen for that user. I have the date range bit down but I'm not sure how i can specify what user i want to see in my query. Here is what I have VIEW def attendance_detail(request): form = DateRangeForm() emp = AttendanceForm() queryset = None if request.method == 'POST': form = DateRangeForm(data=request.POST) emp = AttendanceForm(data=request.POST) if form.is_valid(): start_date = form.cleaned_data.get('start_date') end_date = form.cleaned_data.get('end_date') + timedelta(days=1) queryset = Attendance.objects.filter(date_created__range = [start_date, end_date]) context = { 'form':form, 'queryset':queryset, 'emp':emp, } return render(request, 'employee_management/attendance_detail.html', context) So i need a drop down that will allow me to pick from the users that are listed on the site and tie it to the date range that has been chosen. FORMS class AttendanceForm(forms.ModelForm): class Meta: model = Attendance widgets = { 'time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'), } fields = [ 'emp_name', 'absent', 'tardy', 'left_early', 'details', 'excused_or_not', 'time', ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['excused_or_not'].label = "Was this excused?" self.fields['time'].label = "Date and time" class DateRangeForm(forms.Form): start_date = forms.DateField() end_date = forms.DateField() TEMPLATE {% block content %} <link href="{% static 'css/styles.css' %}" rel="stylesheet" /> <div class="card"> <div class="card-header text-dark"> … -
Populate Django python pdf after submition from user input
I've done the HTML as well as the pdf blank file for my web framework, but when it comes to the submission POST, I cannot seem to get it to work. Its supposed that once you press the submit it will save the user input to the blank pdf created, to later through a button (which is already created and functional, but downloads blank) download a pdf with the users inputed data. Home1.html {% extends "users/base.html" %} {% block title%} Home2 {%endblock title%} {%block Formulario%} <form id="form" method='post'> {%csrf_token%} <div class="form-control"> <label for="fecha" id="label-fecha"> Fecha </label> <input type="date" id="date" placeholder="Ingrese fecha" /> </div> <div class="form-control"> <label for="Cargo Actual" id="label-Cargo Actual" >Su cargo actual</label > <input type="text" id="cargo" placeholder="Ingrese Cargo" /> </div> <div class="form-control"> <label for="Lugar y Fecha de Nacimiento" id="label-F/L nac" >Lugar y fecha de Nacimiento</label > <input type="text" id="FLNac" /> </div> <div class="form-control"> <label for="Discapacidad" id="label-Disc">Grado de discapacidad</label> <input type"text" id='discapacidad' placeholder='En caso de tener discapacidad ingrese el grado,caso contrario deje vacio '> </div> <div class="form-control"> <label for="edad" id="label-edad"> Edad: </label> <input type="text" id="edad" placeholder="Ingrese edad" /> </div> <div class="form-control"> <label for="tipo_sangre" id="label-tipo_sangre">Tipo de Sangre:</label> <input type ="text" id="tipo_sangre" placeholder="Ingrese tipo de sangre" /> </div> <div class="form-control"> <label for="Estatura" … -
'AnonymousUser' object has no attribute '_meta' error in Django Register function
I was trying to do Register and Login form but I am taking "'AnonymousUser' object has no attribute '_meta'" error. How can I solve this error. And also if you have suggestion for better code writing or better way for this form I would be happy. Here is my views.py. from django.shortcuts import render,redirect from .forms import RegisterationForm from django.contrib import messages from django.contrib.auth import login as dj_login from django.contrib.auth import authenticate from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import logout as dj_logout def register(request): if request.method == "POST": form = RegisterationForm(request.POST) if form.is_valid(): user = { "username" : form.cleaned_data["username"], "email" : form.cleaned_data["email"], "password1" : form.cleaned_data["password1"], "password2" : form.cleaned_data["password2"] } user = form.save() dj_login(request,user) messages.success(request,"Kayıt İşleminiz Başarıyla Gerçekleştirilmiştir.") return redirect("index") else: messages.error(request,"Kayıt İşlemi Sırasında Bir Hata Meydana Geldi.") return render(request,"register.html",context={"RegisterForm":form}) else: form = RegisterationForm() return render(request,"register.html",context={"RegisterForm":form}) And here is my register.html file. {% extends 'layout.html' %} {% load crispy_forms_tags %} {% block title %} Register {% endblock title %} {% block body %} <h1>Register</h1> <form method="post"> {% csrf_token %} {{RegisterForm.username.label}} {{RegisterForm.username}} <br><br> {{RegisterForm.email.label}} {{RegisterForm.email}} <br><br> {{RegisterForm.password1.label}} {{RegisterForm.password1}} <br><br> {{RegisterForm.password2.label}} {{RegisterForm.password2}} <br><br> <button type="submit">Kayıt Ol</button> </form> {% endblock body %} and this is my error. Environment: Request Method: POST Request URL: http://localhost:8000/users/register/ … -
how to make an Image qualifier project in django
first of all I must say that I am new to django and I am practicing. I explain, I am creating a project to rate images by showing the user several pairs of images and the user must select the one they like the most. And I'm stuck on how I can do to show the records of the images in pairs according to whether there was already a rating. It shows you a couple of images, you select the one you like the most and they must change the images for two others, that's the idea. Here is my models, the image model contain the image field atribute and the likes atribute who stores the likes of users. The UserLike model contain just the like of one user who will be add in the likes atribute (possibly i defines the class models incorrectly, 'couse i dont find the foreign key 'user_like' in users table) from django.db import models from django.core.validators import FileExtensionValidator from django.contrib.auth.models import User # Create your models here. class UserLike(models.Model): user_like = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) class Images(models.Model): image = models.ImageField(validators=[FileExtensionValidator]) likes = models.ManyToManyField(UserLike, blank=True) def __str__(self): return f'Image: {self.image}' Here is my views, i already made … -
Django display images on custom domain directly without showing Digital Ocean Endpoint on webaddres
I have an django app that hosts images on digitalocean spaces. The images are correctly uploaded to my digital ocean spaces. But when I click on the image it is shown with the digital ocean web address. With CDN and custom domain, I thought the web address for the image will be my custom domain (e.g. media.mydoamin.com) but it is directed to digital ocean's endpoint still. sfo3.digtialoceanspaces.com. I already included a custom domain url in the settings and added a CNAME record to my domain registry media.mydomain.com to an alias as domainname.sfo3.cdn.digitaloceanspaces.com I can see the cname record is already updated online. what am I missing? -
Read the image as Array from Django Model
The django model is a follows class Post(models.Model): title = models.CharField(max_length=100) file = models.FileField(null=True,blank=True,upload_to='Files') content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) I want to read the file. Let's say its an image. I want to read this image in an array format. I tried this but it doesnt work. img = Post.objects.all()[0].file print(img) OR print(np.array(img)) Output is : car-1.jpg Expected output : 2d Array -
Is there any solution for this Django register post method.?
!this is register syntax in views.py](https://i.stack.imgur.com/US67H.jpg) I've registration form attached as shown above I've created helloworld_Register table in But the data is fetching to user_auth but not to the helloworld_register However data is fetching in user_auth but while logging in with registered credentials it's not logging in !this is login syntax in views.py](https://i.stack.imgur.com/MvV4m.jpg) Can any one sort me this it'll be helpful :) "I've tried fetching data to the helloworld_register but couldn't It's fetching to user_auth However data exist in user_auth It's unable to login." -
How to implement AbstractBaseUser with two user types ("Individual" & "Business"), where user can be both types
I am working on a custom user using AbstractBaseUser, where there are multiple types of user ("individual" users and "business" users). I have defined a User model with these two types and created a separate app for their profiles which will be different depending on the user type. I have used two models to split this out, both with a OnetoOne relationship to the User model, then used proxy models & managers to filter each queryset. The part which I'm struggling with is in that I would like for a user to be able to sign up to both an Individual account, and a Business account using the same email authentication. I.e. one user, can be two types, and therefore access application components which relate to both user types. At the moment I believe they can only be one or the other. Has anyone come across this before or have any ideas of how I might implement this? The tutorials I have found haven't covered this as they have said it is "too complex", but I thought it might just be a case of making the type field a multiple choice field, but not sure if this is the case? -
get_serving_url silently fails with django-storages, app engine, python 3.x
I am trying to get the seving_url for a project that uses django-storages with google cloud storage for media files. I am trying to serve the files with get_serving_url, but I get a silent failure here with no text logged in the exception. The blobkey generates correctly from what I can see however the image = images.get_serving_url(blobkey, secure_url=True) raises an exception with no error text. This is what I have done: #storage_backends.py class GoogleCloudMediaStorage(GoogleCloudStorage): """GoogleCloudStorage suitable for Django's Media files.""" def __init__(self, *args, **kwargs): if not settings.MEDIA_URL: raise Exception('MEDIA_URL has not been configured') kwargs['bucket_name'] = setting('GS_MEDIA_BUCKET_NAME') super(GoogleCloudMediaStorage, self).__init__(*args, **kwargs) #this works fine def url(self, name): """.url that doesn't call Google.""" return urljoin(settings.MEDIA_URL, name) #https://programtalk.com/python-examples/google.appengine.api.images.get_serving_url/_ #This does not work yet def serving_url(self, name): logging.info('serving url called') if settings.DEBUG: return urljoin(settings.MEDIA_URL, name) else: # Your app's GCS bucket and any folder structure you have used. try: logging.info('trying to get serving_url') filename = settings.GS_MEDIA_BUCKET_NAME + '/' + name logging.info(filename) blobkey = blobstore.create_gs_key('/gs/' + filename) logging.info('This is a blobkey') logging.info(blobkey) image = images.get_serving_url(blobkey, secure_url=True) return image except Exception as e: logging.warn('didnt work') logging.warn(e) return urljoin(settings.MEDIA_URL, name) I have appengine-python-standard installed and I have wrapped my application #main.py from antiques_project.wsgi import application from google.appengine.api import … -
Wagtail 4 FieldPanel issue with ForeignKey
I have the following setup in wagtail 4.0.4: @register_snippet class Copyright(models.Model): class CopyrightType(models.TextChoices): PH1 = "PH1", _("Phase 1") PH2 = "PH2", _("Phase 2") type = models.CharField( max_length=3, choices=CopyrightType.choices, unique=True, ) class ReportPage(Page): copyright = models.ForeignKey( Copyright, to_field="type", default="PH2", on_delete=models.SET_DEFAULT, ) Now the set up works just fine. But if I add the FieldPanel: class ReportPage(Page): copyright = models.ForeignKey( Copyright, to_field="type", default="PH2", on_delete=models.SET_DEFAULT, ) promote_panels = Page.promote_panels + [ FieldPanel("copyright"), ] I get the following error: ValueError: Field 'id' expected a number but got 'PH2'. Is there any way to tell the FieldPanel to look at the field referenced in the "to_field" option? -
Django apache image loading slow
I have django deployed with apache2. I'm using static files collected using "./manage.py collectstatic"; noticed png images are loading very slow. Image size is only 130Kb and its taking 2500ms to load. Following is html and css. <img class='image1' src="{% static 'index_background.png' %}" style="width:100%;"> <div class="index_feature">test</div> <img class='image2' src="{% static 'index_banner.png' %}"> .indexbar1 { position: relative; top: 0; left: 0; } .imgage1 { position: relative; top: 0; left: 0; } .image2{ position: absolute; width: 600px; top: 35%; right: 5%; } .index_feature { position: absolute; top: 65%; left: 5%; font: 50px lato-regular, Arial, Helvetica, sans-serif; font-weight: 900; line-height: 150%; color: white; } apache2 is deployed on ubuntu 20.04 vm with 16vcpu and 32gb memory. I could see the same issue while using vscode to run django locally without apache2. I'm missing something in django and need some help. -
Static files are served on django admin site but not on the main website after migrating from Django 1.5 to 2.2.5
My trouble is the following. I did a migration from django 1.5 to 2.2.5. All fine on development environment, but when I deployed it to the internet, static files were being served on admin site but not on the main website. I debug this problem and realize that scheme of the request is passed from http to https and console panel shows the following messages: The scheme is https instead of http. But in django admin site the static files are served under http scheme. For this reason, the static files can be loaded on the site. Also, the login page is loaded correctly, but when I reach the next page, the same problem occurs. I am deploying the application on server without SSL certificates for testing. Initially the web server was apache but I changed it to nginx. I thought the problem was the web server but I was wrong. I want the application can serve the static files correctly under http protocol. -
Optimizing Django Aggregation Over Subsets
I'm currently trying to do some summary statistics calculations for date-based subsets of a large "competition" table (~3M rows) stored in SQLite. Specifically, I'm trying to calculate statistics for: this year last year the lifetime of the competitor Here's a model breakdown: class Competitor(models.Model): # ... ID is the only important part here class Venue(models.Model): # ... ID is the only important part here class Division(models.Model): venue = models.ForeignKey(Venue) # ... class Level(models.Model): division = models.ForeignKey(Division) # ... class Class(models.TextChoices): STANDARD = "Standard", _("Standard") JWW = "JWW", _("JWW") class Run(models.Model): competitor_id = models.ForeignKey(Competitor, related_name="runs", db_index=True) date = models.DateField(verbose_name="Date created", db_index=True) MACH = models.IntegerField(..., db_index=True) PACH = models.IntegerField(..., db_index=True) yps = models.FloatField(..., db_index=True) score = models.IntegerField(..., db_index=True) qualified = models.BooleanField(..., db_index=True) division = models.ForeignKey(Division, db_index=True) level = models.ForeignKey(Level, db_index=True) cls = models.CharField(max_length=..., choices=Class.choices) # ... Other fields that aren't relevant For each Competitor, I want to generate summary statistics that describe their performance this year, last year, and over all time, and store that in a Report model: class CurrPrevLifetime(models.Model): curr_yr = models.FloatField(default=0) prev_yr = models.FloatField(default=0) lifetime = models.FloatField(default=0) class Report(models.Model): ... = models.ForeignKey(CurrPrevLifetime, related_name=...) # repeat as needed for as many fields need this My current aggregation setup looks like … -
I am add url look like en but rosetta did not translate static html word
I am add url look like en but rosetta did not translate static html word How i can resolve this problem I a add all settings for rosetta but it did not work -
How to access the request object inside a custom logging formatter in Django?
I have setup a custom formatter to log my data into a text file in JSON format: class CustomJsonFormatter(jsonlogger.JsonFormatter): def add_fields(self, log_record, record, message_dict): super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict) log_record['timestamp'] = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ') log_record['level'] = record.levelname log_record['location'] = record.name I would like to be able to automatically access my request object within this formatted since I have a "unique request identifier" that I would like to add to my logs. This way I know which log lines belong to which request. class CustomJsonFormatter(jsonlogger.JsonFormatter): def add_fields(self, log_record, record, message_dict): super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict) log_record['timestamp'] = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ') log_record['level'] = record.levelname log_record['location'] = record.name log_record['request_id'] = request.uuid <--- Something like this Is there a way to achieve this without having to manually pass the request object to every single log line? Many thanks in advance -
How to print data from two different methods next to each other?
I hava a django application and I have two methods that returns different text. And now the data from the two methods are printed under each other. But I want to have them next to each other. So this is the combined twom methods in one method: def combine_methods(self, file_name): self.extractingText.extract_text_from_image(file_name) return '\n'.join(self.filter_verdi_total_number_fruit(file_name)) + " " + '\n'.join( self.filter_verdi_fruit_name(file_name)) And this is the output: 16 360 6 75 9 688 22 80 160 320 160 61 Watermeloenen Watermeloenen Watermeloenen Watermeloenen Watermeloenen Appels Sinaasappels Sinaasappels Sinaasappels Sinaasappels Sinaasappels Sinaasappels But I want to have it like: 16 watermeloenen 360 watermeloenen 360 watermeloenen 360 watermeloenen 360 watermeloenen 360 watermeloenen 360 watermeloenen 360 watermeloenen 360 watermeloenen 360 watermeloenen 360 watermeloenen -
Browser cant find file or directory in Django
I am trying to create a qr code and store it on disk. Running the program from my pc works fine, but when I run it on the server (deploy is done in docker), I get this error: [Errno 2] No such file or directory: '/app/static/QR /QR-1-9.png' and the browser also points me to this line of my code with open(UPLOADS_PATHS, 'wb') as f: The route is defined in the settings file like this: QR_ROOT = os.path.join(BASE_DIR, 'static/QR') And this is the view where the qr is stored on disk nombre_archivo = f'QR-{request.user.instituto.id}-{idRecibo}.png' UPLOADS_PATHS = os.path.join(settings.QR_ROOT, nombre_archivo) with open(UPLOADS_PATHS, 'wb') as f: f.write(response.content) I try this on settings.py: QR_ROOT = os.path.join(BASE_DIR, './static/QR') but it does not work -
How to access server data in a javascript file that is loaded by Django admin pages
I need to access server data in a javascript file that gets loaded with an admin page. In my case, I'll need a json variable that is set in the settings.py file (in the production version, this json-variable gets loaded from env-variable which means that the content of the variable is known at startup-time but is not hard coded). I use the javascript to validate and populate some fields in an admin-page - that is a better UX than doing it server side. Is it possible to add script-tag to the admin html-pages' head section, that contains server data, i.e. non-static data?