Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiple filter parameters in the foreign key relation with reduce function
I have a model ToBePosted that has a foreign key to Campaign and Size. class Campaign(models.Model): name = models.CharField(max_length=100) class Size(models.Model): name = models.CharField(max_length=5) class ToBePosted(models.Model): campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, related_name='to_be_posted_posters') size = models.ForeignKey(Size, on_delete=models.CASCADE, related_name='to_be_posted_posters') My queryset in views.py: def get_to_be_posted_queryset_with_filter(self, request): filter_params = ToBePostedParameterConverter(request.GET) queryset = ToBePosted.objects.all() return queryset.filter(filter_params.get_filter()) And helpers.py where ToBePostedParameterConverter is located class ParameterConverter: # Convert url query params to queryset filter params query_patterns = { "campaign": 'to_be_posted__campaign__name', "size": 'reference__size__name', } def __init__(self, query_dict): self._query_dict = query_dict self._filter_params = [] self._convert() def _convert(self): for key in self._query_dict: for search_key in self._query_dict.getlist(key): if query_param := self.query_patterns.get(key): self._filter_params.append(Q(**{query_param: search_key})) def get_filter(self): if self._filter_params: return reduce(operator.or_, self._filter_params) return Q() class ToBePostedParameterConverter(ParameterConverter): query_patterns = { "campaign": 'campaign__name', "size": 'size__name', } def get_filter(self): if self._filter_params: return reduce(operator.or_, self._filter_params) return Q() The question is: when I try to get an object Tobeposted with a size of 666 but only associated with campaigns Acamp and Bcamp I get all objects that have a size of 666 regardless of the specified campaigns in the url EXAMPLE OF REQUEST URL WITH PARAMETERS: http://localhost:8000/api/v2/posters/get_lookups/?campaign=Acamp&campaign=Bcamp&size=666 How I can change the code to get only posters that are related to specified campaigns in the url paramters? I … -
Sort added elements inside Django autocomplete_fields
I have Django application and admin page. Inside admin page, I have one model that has autocomplete_fields. I can sort results but, I can't sort the results. It always sort by pk and not by value that I set. @admin.register(Assortment) class AssortmentAdmin(ImportExportActionModelAdmin): list_display = ['name'] exclude = ['customers'] # inlines = [ProductAssortmentInLine] autocomplete_fields = ['products'] @admin.register(Product) class ProductAdmin(ImportExportActionModelAdmin): exclude = ['associated_products', 'subsidiary_excluded', 'customers'] list_display = ['product_ref', 'name', 'price', 'group', 'retail_unit', 'active'] list_editable = ['price', 'retail_unit', 'active'] list_filter = ['group'] search_fields = ['product_ref', 'name', 'group'] resource_class = ProductResource # inlines = [CustomerInLine] def get_queryset(self, request): qs = super(ProductAdmin, self).get_queryset(request) qs = qs.order_by(Cast(F('product_ref'), IntegerField())) return qs How to solve this? -
Heroku-deployed Django application does not appear in mobile browser
Situation: I've bought a specific domain, let's say 'example.ch' for my Django application which is deployed in Heroku. I also created an automated SSL certificate on Heroku (ACM). This certificate is valid for the WWW-subdomain, i.e. ACM Status says 'OK'. It fails for the non-WWW root domain, so I deleted the root domain entry on Heroku. I use 'swizzonic.ch' as webhostserver. Question: The redirection from 'example.ch' to 'https://www.example.ch' does not work on my mobile device, while everything is fine when I use my Mac and all common browsers. I found an older (unanswered) similar post to this topic (Django app on heroku: content wont appear in mobile browser). I don't know where to start, since seemingly nobody else faces this issue... Many thanks for your help. -
custom view component into based view
how to make a custom component (for example a form) that can then be called from other views? for example class BaseFormView (FormView): template_name = 'pit / contact.html' form_class = ContactForm success_url = '/' def form_valid (self, form): return super (). form_valid (form) class TestView (View): template_name = loader.get_template ('pit / pit.html') title = "test" def get (self, request, * args, ** kwargs): view = BaseFormView () context = {"title": self.title, "view": view} return HttpResponse (self.template_name.render (context, request)) -
Include javascript files in a javascript file in a Django project
I'm using the chart library apexcharts and defined a javascript function for a chart that I'm using multiple times on different parts of the website. The function needs some other scripts to work. So at the moment, everytime I want to use that function (located in util.js), I have to import the scripts like this in my html template: <script type="application/javascript" src="{% static 'shared/js/apexcharts/apexcharts.min.js' %}"></script> <script type="application/javascript" src="{% static "shared/js/apexcharts/dependency2.js" %}"></script> <script type="application/javascript" src="{% static "shared/js/apexcharts/dependency1.js" %}"></script> <script type="application/javascript" src="{% static "shared/js/apexcharts/util.js" %}"></script> How can I include the first 3 in my util.js, so that I just have to import util.js? -
Django ValueError The view HomeFeed.views.AddCommentView didn't return an HttpResponse object. It returned None instead
I received this error from the code: ValueError at /HomeFeed/comments/testuser1-2 The view HomeFeed.views.AddCommentView didn't return an HttpResponse object. It returned None instead. Any idea why this is happening? Like which part is causing this problem too, is it the function or my reverse lazy line? models.py class Comment(models.Model): post = models.ForeignKey(BlogPost, related_name='comments', on_delete=models.CASCADE) name = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='name', on_delete=models.CASCADE) body = models.TextField() date_added = models.DateField(auto_now_add=True) class BlogPost(models.Model): chief_title = models.CharField(max_length=50, null=False, blank=False, unique=True) body = models.TextField(max_length=5000, null=False, blank=False) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['body'] widgets = { 'body' : forms.Textarea(attrs={'class': 'form-control'}), } views.py class AddCommentView(DetailView, FormView): model = BlogPost # change model to post because your are commenting on POSTS not COMMENTS form_class = CommentForm template_name = 'HomeFeed/add_comment.html' success_url =reverse_lazy('HomeFeed:main') def form_valid(self, form): comment = form.save(commit=False) #comment.user = self.request.user comment.name = self.request.user comment.post = self.get_object() comment.save() -
How to create a template in django that can be use any other page and that rander same / editable if needed
i created a base template home.html, there is footer and i pass categories on footer and it work fine in home.html but there is extended pages view.html when i go to this page the footer categories is not showing likewise footer is not showing in other pages how can i solve this problems . to incluse view.html in home.html home.html {% block body %} {%endblock%} <--footer--> <div class="col-xs-6 col-md-3"> <h6>Categories</h6> <ul class="footer-links"> {% for category in procategory %} <li><a href="foodgrains?category={{category.id}}">{{category.name}}</a></li> {% endfor %} </ul> </div> view.html {% extends 'home.html' %} {% load static %} {% block body %} <--my code --> {% endblock body %} problems is when i go to view,html the footer categories value is not showing can any one have any suggestion to solve ,how the footer categories show in different page i sloe use {% include 'footer.html' %} it also doesn't work -
Why are the contents of my static css and js files being replaced by html code?
I have a pure js application from which I have generated the build files using yarn build I have the following files I now need to serve these files using Django. Here is what I have tried I have added a frontend folder in the Django app as follows I have also added the following URL re_path("wazimap/", TemplateView.as_view(template_name="index1.html")) and updated the settings file with the following TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": ["frontend/build/dist"], ....More code STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), os.path.join(BASE_DIR, "frontend/build/dist"), ] now when I access the /wazimap/ URL, the HTML is served but the css/js that is being loaded contains the wrong code. I can see from the console that the files are being requested but index1.html is what is being placed inside all the css/js files i.e The contents of the css/js files are the content of the index1.html file. So a js file has something like <!DOCTYPE HTML>... which isn't a valid js thus causing errors. Any ideas why this is happening? -
How to add email in Django amin Add user Page
I have created a CustomUser(AbstractUser) Model and in this model I want to add email id field in admin Add User Page.Currently By default first we can enter username and Password and after creating username and password we are redirected to another page where email field is available I want this email field on add User page is this possible.? -
Jupyter Installation
i am quite new into the Jupyter community and want to experience what jupyter has to offer. My knowledge about Jupyter is still quite limited While I was downloading jupyter and trying to open the jupyter notebook. Errors below were shown to me instead. Traceback (most recent call last): File "C:\Users\Tan Caken\anaconda\Scripts\jupyter-notebook-script.py", line 6, in from notebook.notebookapp import main File "C:\Users\Tan Caken\anaconda\lib\site-packages\notebook\notebookapp.py", line 51, in from zmq.eventloop import ioloop File "C:\Users\Tan Caken\AppData\Roaming\Python\Python38\site-packages\zmq_init_.py", line 50, in from zmq import backend File "C:\Users\Tan Caken\AppData\Roaming\Python\Python38\site-packages\zmq\backend_init_.py", line 40, in reraise(*exc_info) File "C:\Users\Tan Caken\AppData\Roaming\Python\Python38\site-packages\zmq\utils\sixcerpt.py", line 34, in reraise raise value File "C:\Users\Tan Caken\AppData\Roaming\Python\Python38\site-packages\zmq\backend_init_.py", line 27, in ns = select_backend(first) File "C:\Users\Tan Caken\AppData\Roaming\Python\Python38\site-packages\zmq\backend\select.py", line 28, in select_backend mod = import(name, fromlist=public_api) File "C:\Users\Tan Caken\AppData\Roaming\Python\Python38\site-packages\zmq\backend\cython_init.py", line 6, in from . import (constants, error, message, context, ImportError: cannot import name 'constants' from partially initialized module 'zmq.backend.cython' (most likely due to a circular import) (C:\Users\Tan Caken\AppData\Roaming\Python\Python38\site-packages\zmq\backend\cython_init_.py) And I don't know how to solve this problem. I kinda notice the import error that says there is a python thing install beforehand, but other than that. I have no clue on resolve on this. T -
Operational Error: no such table: background_task - clean way to deploy?
I have an issue with background_tasks and deploying. When running makemigrations I get: no such table: background_task here are my INSTALLED_APPS: INSTALLED_APPS = [ 'appname.apps.AppnameConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'background_task', ] I also tried python manage.py makemigrations background_task before python manage.py makemigrations but this also failed. My workaround for now is to rename the tasks.py to tasks and to comment the part in the urls.py where I call the tasks from the tasks.py and deleting background_task from settings.py. Then I do all the migrating and then undo my renaming/commenting/deleting. This works, but there must be a better way? I already tried the tips from here (but my workaround is based a little bit on OPs own answer) and here. -
In Django, after login I'm able to redirect to the previous page, but if the login page is directly accessed then unable to redirect
I want to secure each webpage of my django app, and what I want is that after login the user should be redirected to the previous page he was trying to access. So in accounts/views.py this is the login function I am using for that: def login(request): if request.method == 'POST': #some code if user is not None: auth.login(request, user) return redirect(request.POST.get('next','dashboard')) else: #some code else: #some code Now, I have used @login_required condition for each view of my webapp in this way: @login_required(login_url='login') def profile(request): return render(request, 'profile.html') my login.html: <form method="POST" action="/accounts/auth"> {% csrf_token %} <input type="hidden" name="next" value="{{ request.GET.next }}" /> {{ login_form }} <input type="submit"> </form> Now if the user visits accounts/profile without login, then he is redirected to accounts/login?next=/accounts/profile, so after login he is successfully redirected to accounts/profile as the value of 'next' is set to /accounts/profile and in login function if the user is authenticated then i have used return redirect(request.POST.get('next','dashboard')) which means redirect to the value of next if it is entered, otherwise /accounts/dashboard. Now coming to my issue, if I try to access the login page directly (i.e. /accounts/login) then as there is no next variable in the URL, so according to … -
Django Field Error (Unknown Fileds) even though field is already included in models.py
I keep getting the error, FieldError at /admin/products/variant/add/ Unknown field(s) (default) specified for Variant. Check fields/fieldsets/exclude attributes of class VariantAdmin. Even though the field default is included in my Variant Model models.py file class Variant(models.Model): COLOR_CHOICES = [ ('black', 'Black'), ('grey', 'Grey'), ('white', 'White'), ('blue', 'Blue'), ('green', 'Green'), ('yellow', 'Yellow'), ('orange', 'Orange'), ('red', 'Red'), ('purple', 'Purple'), ('gold', 'Gold'), ('silver', 'Silver'), ('brown', 'Brown'), ('pink', 'Pink'), ('colorless', 'Colorless'), ] CLOTH_SIZE_CHOICES = [ ('xxs', 'XXS'), ('xs', 'XS'), ('s', 'S'), ('m', 'M'), ('l', 'L'), ('xl', 'XL'), ('xxl', 'XXL'), ('xxxl', 'XXXL')] product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name='variants') default = models.BooleanField(default=False), price = models.FloatField() old_price = models.FloatField(blank=True, null=True) quantity = models.IntegerField() # Dimensions in cm height = models.FloatField(blank=True, null=True) width = models.FloatField(blank=True, null=True) length = models.FloatField(blank=True, null=True) # in kg weight = models.FloatField(blank=True, null=True) # Colors color_family = models.CharField(max_length=20, choices=COLOR_CHOICES) specific_color = models.CharField(max_length=50, blank=True, null=True) # Clothing and Shoes cloth_size = models.CharField( max_length=20, choices=CLOTH_SIZE_CHOICES, blank=True, null=True) shoe_size = models.IntegerField(blank=True, null=True) # Computing ram = models.IntegerField(blank=True, null=True) rom = models.IntegerField(blank=True, null=True) # in cm screen_size = models.FloatField(blank=True, null=True) def __str__(self): return f"{self.product} Variant" def in_stock(self): return self.quantity > 0 def discount(self): if (self.old_price == self.price) or (self.old_price < self.price): return 0 return (100 - ((self.price / self.old_price) … -
Error 500 deploying a DJANGO app on heroku, in everything except the index
The view with the index works perfect even with statics, but the other views show the error 500 The code of my urls.py is next: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',include("home.urls",namespace="home")), path('api/',include("api.urls",namespace = "api")), ] +static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and that one in my urls home folder (app folder) from django.urls import path from django.contrib.auth import views as auth_views from home import views from django.conf import settings from django.conf.urls.static import static app_name="home" urlpatterns=[ path('VerItems/',views.VerItems, name="VerItems"), path('VerAutores/',views.VerAutores, name="VerAutores"), path('AgregarAutor/',views.AgregarAutor, name="AgregarAutor"), path('AgregarItem/',views.AgregarItem, name="AgregarItem"), path('',views.Index.as_view(), name="index"), ] And finally. settings file, I know that BASEDIR is not what every web shows it should be, but if I change it, the index does not work anymore from pathlib import Path import os.path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ke-7l!7r!e$f#8+e=bv9(&wu_1@purto!^#ut948t8)od+@te(' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', … -
Django: How to make it such that I can submit interest to any blogpost, not just 1 blog post?
Django: How to make it such that I can submit interest to any blogpost, not just 1 blog post? Currently, now after I submit interest to a blogpost, I can no longer submit interest to any other blog post. I will receive this message saying that 'You have already submitted your interest to this post.' Even though i haven't. Judging by the nature of my model. Is there a way for me to filter the 'user' field in my interest model such that I am only checking through to see if the particular user in that particular blog post has already submitted the interest? Cause i understand that right now, they are filtering it based on all the blogpost, and as long as I have already submitted 1, it definitely exists. Please let me know if you need my forms.py , urls.py too if it helps. views.py def submit_interest_view(request, slug): form = SubmitInterestForm() user = request.user blog_post = get_object_or_404(BlogPost, slug=slug) num_blogpost = BlogPost.objects.filter(author=user).count() if blog_post.author.email == user.email: return HttpResponse('You cannot submit interest to your own post.') if Interest.objects.filter(user=request.user).exists() and request.method=="POST": return HttpResponse('You have already submitted your interest to this post.') if request.method == 'POST': form = SubmitInterestForm(request.POST, request.FILES) if form.is_valid(): … -
How Mediafire (file Hosting) works or how to develope a Medifire like clone?
Actually, I was learning Django So I want to make a project for my own curiosity and also want to learn more about scalability and load. -
Django: Can't access static files in python script
i have deployed a django project with mod wsgi on an apache server. Everything works so far. In one python script I'd like to open a file in static files. Therefore I have tried something like this: mycode.py import cv2 class Foo(): def __init__(self): ... def openImg(self): self.myimg = cv2.imread('static/myapp/img/picture.jpg',0) return self.myimg .. just for testing However it can't find this file. Whether in path ('static/myapp/img/picture.jpg'), nor path ('myapp/static/myapp/img/picture.jpg') nor in path ('../static/myapp/img/picture.jpg') and some other which I have already forgot. It always returns "None". If I try the same on my "undeployed" local project it works without any problem. I have already collected all staticfiles to /myproject/static and given enough rights to access them. By the way, the access to the static files in the html works in production. What's the problem? Can you give me any advice? Thank you. Some additional information: views.py from django.shortcuts import render from .mycode import Foo def index(request): # New Instance for class Foo bar = Foo() # Return img array to put it in html for whatever imagearray = bar.openImg() context = {'imgarray': imgarray} return render(request, 'electreeksspy/index.html', context) Thats an example of my directory /home/myuser/MyProject /static/myapp/img/picture.jpg (collected) / /myapp /static/myapp/img/picture.jpg /mycode.py /views.py … -
Django: simple_tag not rendering simple string
I am trying to create dynamic menus list under one mega menu.The menus will be fetched from database.I am using Django simeple_tag feature to achieve this but some how does not render the simple test string which I am giving although I want to render HTML tags at the end.Here is my code, my_app/home/templatetags/menus.py from django import template register = template.Library() @register.simple_tag(name='downloadable_menus') def downloadable_menus(a): """ Generate the downloadable menus under the free resources mega menu """ return 'Hello' This is how I am using in template. {% load menus %} <div class="content"> <ul class="menu-col"> {{ downloadable_menus }} </ul> </div> So the above code should display the "Hello" string in the menu but it is not.Any help would be appreciated. -
How to import a value inside another class model in Django?
shope/models.py from django.db import models class Product(models.Model): PN = models.CharField(max_length=100, default = "AAAA") Ship/models.py from shop.models import Product class OrderItem(models.Model): product = models.ForeignKey(Product, related_name='ship_items', on_delete=models.CASCADE) PN = models.ForeignKey(Product.PN, related_name='ship_items', on_delete=models.CASCADE) print(PN) All I want to do is to get PN from shope/models.py into Ship/models.py then print it. -
PLEASE HELP: assert not cls._meta.auto_field, ( AssertionError: Model shop.Product can't have more than one auto-generated field
I GOT MORE THAN ONE AUTO-GENERATED FIELD ERROR product_id = models.AutoField(primary_key=True) product_name = models.CharField(max_length=50) category = models.CharField(max_length=50, default="") subcategory = models.CharField(max_length=50, default="") price = models.IntegerField(default=0) desc = models.CharField(max_length=300) pub_date = models.DateField() image = models.ImageField(upload_to="shop/images", default="") def __str__(self): return self.product_name``` -
How to store file in django session and get that file in another view and store in database
I created form where user upload their photo and other details before they submit the form i want to redirect somewhere because of payment gateway so how can i handle it. this is in my views #this is for order creation def form_submit(request): white_bg_photo = request.FILES['white_bg_photo'] front_page = request.FILES['front_page'] request.session['file1'] = white_bg_photo request.session['file2'] = front_page if order_status == 'created': context['data'] = data #all other stuff i am sending to order confirmation return render(request, 'order_confirmation.html',context) else: return(request,'error.html') #this is for order confirmation def payment_status(request): response = request.POST data = request.POST.get('data') params_dict = { 'razorpay_payment_id' : response['razorpay_payment_id'], 'razorpay_order_id' : response['razorpay_order_id'], 'razorpay_signature' : response['razorpay_signature'] } # VERIFYING SIGNATURE try: status = client.utility.verify_payment_signature(params_dict) booking = Booking() booking.white_bg_photo = request.session['file1'] booking.front_page = request.session['file2'] booking.data = data booking.save() return render(request, 'order_summary.html', {'status': 'Payment Successful'}) except: return render(request, 'order_summary.html', {'status': 'Payment Faliure!!!'}) -
Adding Button in Django Admin Panel
In my main Django Project, I have an app called "Argentina" where I have registered model "PowerPlantMix". The model will have list of PowerPlants in Argentina with their respective capacities. Goal: What I am trying to do is to have an extra button by name of "Button" (as given in image) in which a URL would be embedded that would take me to respective URL(already registered in url.py). Is there a way I can add a button in models. As I have multiple apps I cannnot use the view site button. Thanks -
Django, Next.JS: CORS header ‘Access-Control-Allow-Origin’ missing, CORS request did not succeed even though django-cors-headers is defined
I am stuck with the old and confusing issue of CORS with Django and Next.JS. My setup: OS: Windows 10, Browser: Mozilla: 84.0.2 (64-bit), Django: 3.1, Next.JS: 10. My Django settings: INSTALLED_APPS = [ ... 'corsheaders', 'rest_framework', 'my_app', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], } CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', ] CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True urls.py: from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('my_app.urls')), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] My Next.js page: import { useState } from 'react'; import axios from 'axios'; export default function loginForm() { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const handleSubmit = () => { const headers = { "Content-Type": "application/json", "Accept": "application/json" } return axios({ method: "POST", url: "http://127.0.0.1:8000/api/token/", data: { username: username, password: password }, headers: headers }) .then(function (response) { console.log(response); }) .catch(function (response) { console.log(response); }); }; return ( <div className="loginBox"> <div className="lblBox"> <label className="label" htmlFor="loginbox"> Enter Username and Password <div className="unameInput"> <input type="text" name="username" placeholder='Enter username' onChange={e => setUsername(e.target.value)} /> </div> <div className="passwordInput"> <input type='password' name='password' placeholder='Enter password' onChange={e => … -
Making nested queries using the Django ORM
Assuming I have a model like below: class Region(models.Model): info = JSONField() number = models.IntegerField() I want to write a ORM query which translates into a nested SQL query similar to the below one: SELECT result, COUNT(number) FROM (SELECT jsonb_object_keys("region_table"."info") as result, number from region_table) pp group by number; Is there any way to perform the above nested SQL query? -
Using python-decouple, how do I pass a variable with a carriage return (rsa key)?
I have a rsa key in my .env file like this: MY_KEY=-----BEGIN PRIVATE KEY-----\n********my key**********\n-----END PRIVATE KEY-----\n When using from decoule import config and "private_key": config("MY_KEY"), the following is the result I get. MY_KEY=-----BEGIN PRIVATE KEY-----\\n********my key**********\\n-----END PRIVATE KEY-----\\n The extra slash in \\n is causing a problem in that my google.oauth2 can't recognize the key. Is there a way to import the key so that only one slash is returned and not two?