Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Beginner Problem about the path to take after learning the basics
I recently graduated but my degree is not in computer science. I want to switch career path and I have started learning Python. I have learnt all the syntax and the basic stuff. But now I am a little bit confused about which way I should go in terms of what I should now learn . Which projects I should create and where to find them. I need suggestions on how to carry on this path from where I am now to being at least Job Ready. -
Easiest way to geoblock users from website?
What is the easiest way to geoblock users from e.g. China / Iran from accessing my website? FYI its Django + NGINX on Linode. I've read about MaxMind tables but seems complex and only seems works with NGINX Plus which is like $2500 / year. Also Cloudflare, probably easy but potentially only for enterprise subscriptions. Is using built in Django (https://docs.djangoproject.com/en/3.2/ref/contrib/gis/geoip2/) the best option? Do I move to AWS and see if they have something? If anyone has been in this situation it would be great to hear what worked for you, thanks. PS; it's more distribution compliance than stopping DDoS etc, so blocking the majority of average users is enough. -
Issues with Django in virtual enviroment
I have a python application that I installed in WSL ubuntu and I an trying to link my VSCode ( from windows to it). I am having some trouble accomplishing that thou and I hope I can be assisted. SITUATION In running a script I need ( in VSCode terminal) I get the following error. ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? (Please note I am in a virtual enviroment). So then I return to Ubuntu and I run python3 -m django --version which returns 3.2.8. I go back to VSCode virtual environment and run the same script that shows me /mnt/h/Documents/Projects/React/Myplace/venv/bin/python: No module named django So I think ok maybe I can install it and I run sudo pip install Django==3.2.8 which returns Requirement already satisfied: Django==3.2.8 in /usr/local/lib/python3.8/dist-packages (3.2.8) Requirement already satisfied: sqlparse>=0.2.2 in /usr/local/lib/python3.8/dist-packages (from Django==3.2.8) (0.4.2) Requirement already satisfied: asgiref<4,>=3.3.2 in /usr/local/lib/python3.8/dist-packages (from Django==3.2.8) (3.4.1) Requirement already satisfied: pytz in /usr/local/lib/python3.8/dist-packages (from Django==3.2.8) (2021.3) Given this, I am currently unsure how to proceed. I think I should also mentioned I created my virtual enviroment using sudo pip3 install virtualenv … -
Thought I overrode the User model but actually not? Django
I've been trying to create my custom user model, but I can see in the admin console that there's still the original user model. I want to remove permanently Users from it. This is my models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, first_name, last_name, name, email, password=None): if not email: raise ValueError("need email address") user = self.model( email = self.normalize_email(email), first_name = first_name, last_name = last_name, name = name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, first_name, last_name, name, email, password=None): user = self.create_user( email = self.normalize_email(email), password = password, first_name = first_name, last_name = last_name, name = name, ) user.is_admin = True user.is_staff = True user.is_active = True user.is_superadmin = True user.save(using=self._db) return user class Account(AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=100, unique=True) phone_number = models.CharField(max_length=50) name = models.CharField(max_length=50) joined_date = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_superadmin = models.BooleanField(default=False) objects = MyAccountManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "name", "last_name"] There's a It looks like your post is mostly code; please add some more details. error in my post, so please ignore this text: asldifhaosdfhoahsdofhaosdhfoahsdifkas;dfoasbdfoabsodfhoashdfoiasdofbaosdfoabsdofbaosdbfoausbdfuabsdofbasdf -
how to count each occurrence in each django aggregate
I have the query below that I am using to fetch certain relationships between N1 and N2 (has foreign key rel to N1). The ArrAgg groups all annotated ch which works fine as it is, but I'm wondering if it is possible to rewrite the query to count each occurrence of elements in ch edits = N2.objects.all().prefetch_related('n1').values("n1_id", "n1__url").annotate(ch=ArrayAgg("w_c"), v_t=Count('w_c')) Current queryset: <QuerySet [ {'n1_id': 31, 'n1__url': 'https://google.com', 'ch': ['t1', 't1', 't1', 't2', 't3', 't3', 't2', 't2'], 'v_t': 8}]> Desired QuerySet (or something similar) <QuerySet [ {'n1_id': 31, 'n1__url': 'https://google.com', 'ch': ('t1', 3), ('t2', 3), ('t3', 2)}]> I could write a template tag that uses Counter from collections then use that in the template, but wondering if this is possible in plain ORM. -
Get django models according to its dependencies
I want to add attribute to django model meta class. this attribute is depends on related_models for example: App one class Main(Models.Models): class Meta: abstract = True class A(Main): #model_fields_here class B(Main): a= models.ForeignKey(A,on_delete = Models.CASCAD) #models_fields_here class C(Main): b = models.ForeignKey(b,on_delete = Models.CASCAD) App two class A1(Main): #model_fields_here class B1(Main): a= models.ForeignKey(A,on_delete = Models.CASCAD) #models_fields_here class C1(Main): b1 = models.ForeignKey(B1,on_delete = Models.CASCAD) I want to get models like this: models = [A,A1,B,C,B1,C1] means I want to get the list of whole django models sorting by its dependencies. I try with this but it ignore django models dependencies: import django.apps django.apps.apps.get_models() -
ERROR: PyAudio-0.2.11-cp38-cp38-win_amd64.whl is not a supported wheel on this platform. on heroku
ERROR: PyAudio-0.2.11-cp38-cp38-win_amd64.whl is not a supported wheel on this platform. while deploying to heroku.I also install this error file in my system. -
How to insert images from render( , , context) in Django?
guys! New in Django so maybe it's a silly question. I have a .json file that keeps information about shop's clothes including "img". The goal is to otput all the information about products in a single "for loop". So I've written such lines {% for product in products %} <div class="col-lg-4 col-md-6 mb-4"> <div class="card h-100"> <a href="#"> <img class="card-img-top" src="{% static '{{ product.img }}' %}" !!! problem is here alt=""> </a> <div class="card-body"> <h4 class="card-title"> <a href="#"> {{ product.name }} </a> </h4> <h5>{{ product.price }}</h5> <p class="card-text"> {{ product.description }}</p> </div> <div class="card-footer text-center"> <button type="button" class="btn btn-outline-success">Отправить в корзину</button> </div> </div> </div> {% endfor %} Everything works fine except the line concerns an image. In devtools I get the next path "/static/%7B%7B%20product.img%20%7D%7D". But in the .json file it looks like "img": "vendor/img/products/Brown-sports-oversized-top-ASOS-DESIGN.png". I am totally confused about that situation and definitely in a bind. I appreciate any help -
Upload an image from html template file to a django python class without using model
I am a beginner in coding. I am building an application in Django which requires an image captured through the html and then it should be used in a python class where i want to pass the image to opencv. i am using the following code: store.html:- {% csrf_token %} Image: <input type="file" name="camCapture" accept="image/*" id="image" required> <input type="submit" name="submit" value="submit" required> filter.py: class Pic2Filter(django_filters.FilterSet): img = cv2.imread('CV/static/images/IMG_1159.jpg') img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) hImg,wImg,_ = img.shape boxes = pytesseract.image_to_data(img) lst = [] for x,b in enumerate(boxes.splitlines()): if x!=0: b = b.split() if len(b)==12: x,y,w,h = int(b[6]),int(b[7]),int(b[8]),int(b[9]) detected_text = b[11] lst.append(detected_text) #Product identification products = Product.objects.values_list('name', flat=True) d = [x.lower() for x in lst] # make dict of list with less elements search_result = [] for m in products: if m.lower() in d: searched_name = Product.objects.filter(name__iexact=m) search_result += searched_name i want to use the captured image instead of CV/static/images/IMG_1159.jpg. Is there a way to do it without using a model or saving? -
The field 'email' clashes with the field 'email' from model 'account.account'. Django3.2
Newbie in django here. I've been trying to create a simple site with django and i just finished creating the models. However, when I try to makemigrations, i get this: SystemCheckError: System check identified some issues: ERRORS: account.Account.email: (models.E006) The field 'email' clashes with the field 'email' from model 'account.account'. I checked my code, but i couldn't find anything bad. Maybe my eyes are broken. Here's my models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class AccountManager(BaseUserManager): def create_user(self, first_name, last_name, name, email, password=None): if not email: raise ValueError("User must have an email address") user = self.model( email = self.normalize_email(email), first_name = first_name, last_name = last_name, name = name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, first_name, last_name, name, email, password=None): user = self.create_user( email = self.normalize_email(email), password = password, first_name = first_name, last_name = last_name, name = name, ) user.is_admin = True user.is_staff = True user.is_active = True user.is_superadmin = True user.save(using=self._db) return user class Account(AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=100, unique=True) phone_number = models.CharField(max_length=50) name = models.CharField(max_length=50) reputation = models.BigIntegerField(default=1) downvote_count = models.IntegerField(default=0) # mandatory fields created_date = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_superadmin … -
Django event stream deployment with daphne
I'm trying to redeploy my Django project on my local ubuntu server to document all the steps, I managed to get it up and running but the problem is my real time notifications are not working, I'm using Django event stream for the notifications. I have setup the Daphne and Nginx accordingly and the event stream connection is opened too but I'm not receiving the real time notifications. There is no code related issue as the same code is on production server and notifications are working there. The problem is I'm not getting any error message so I don't know where to look to debug the issue. I'm sharing the configurations which I did I think I'm missing something in the setup. I have followed Django channels official deployment here. My Nginx and Daphne configurations are in the below images. . Channels=2.3.1 Daphne=2.5.0 Django Event Stream==2.6.0 I'm using http server sent events -
jinja2.exceptions.TemplateNotFound: login.html :FastAPI
I'm a newbie to fastapi , I'm trying to render a html page using a router app/routers/login.py: from fastapi.templating import Jinja2Templates import os # some of codes here.... # BASE_PATH = Path(__file__).parent.resolve() # # lets say your template directory is under the root directory # templates = Jinja2Templates(directory=f'{BASE_PATH}/templates') router = APIRouter( tags=['login'], prefix="/login", ) operating_directory = os.path.dirname(os.path.abspath(__file__)) #templates = Jinja2Templates(directory="templates") templates = Jinja2Templates(directory=os.path.join(operating_directory, 'templates')) @router.get("/", response_class=HTMLResponse) async def login(request: Request): return templates.TemplateResponse("login.html",{"request": request}) my html file is in this location: app/templates/login.html <!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>Login</title> <link rel="stylesheet" href="css/main.css"> <!-- <link href="{{ url_for('static', path='css/main.css') }}" rel="stylesheet"> --> </head> <body> <div class="container"> <form action=""> <div class="form-group"> <label for="email">Email</label> <input type="text" class="form-control" required> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" class="form-control" required> </div> <input type="submit" class="btn" value="login"> </form> </div> </body> </html> when i try http://localhost:8000/login/ render the template , its shows not able to fin template -
Docker SQL - SQL connection timeout
I have been trying to resolve this issue for many days still I couldn't able to resolve it.I have created the docker image for mssql and django app.when I tried to docker-compose up I can see it still resulting in the same error but when i run in the local its working fine. my system config: microsoft.com/fwlink/?linkid=2099216. sql-server-db | 2021-10-09 13:44:28.18 Server The licensing PID was successfully processed. The new edition is [Express Edition]. 2021-10-09 13:44:28.89 Server Microsoft SQL Server 2017 (RTM-CU26) (KB5005226) - 14.0.3411.3 (X64) Aug 24 2021 09:59:15 Copyright (C) 2017 Microsoft Corporation Express Edition (64-bit) on Linux (Ubuntu 16.04.7 LTS) errorlogs: Exception in thread django-main-thread: web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection web_1 | self.connect() web_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner web_1 | return func(*args, **kwargs) web_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 197, in connect web_1 | self.connection = self.get_new_connection(conn_params) web_1 | File "/usr/local/lib/python3.8/site-packages/sql_server/pyodbc/base.py", line 312, in get_new_connection web_1 | conn = Database.connect(connstr, web_1 | pyodbc.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)') these are my requirements.txt is anything that i left out to install requirements.txt asgiref==3.4.1 click==8.0.1 colorama==0.4.4 Django==2.1.15 django-mssql-backend==2.8.1 # django-pyodbc-azure==2.1.0.0 … -
Why we use action attribute in html form? What is the difference between action and redirect?
Yes! you must be thinking it is a basic question or stupid etc, but i didn't get the answer of this question on the entire google.. I got the answer of this question is that the action always sends data to the url which was given to the action attribute and just redirect the on that url.. My questions are: Why we use action whenever we can use redirect in django or other backends?: if we send data to the url why we send? Where we use this data? -
Django SECRET_KEY protection VS ability to run project locally
I have read many topics here about django SECRET_KEY, but most of them are about how to store it in environment variable instead of settings.py, at this stage everything is clear. Currently i keep it in .env locally and in config var on heroku. Im confused about 2 conflicting points that i can't combine together. On the one hand, it considers as a good practice to keep SECRET_KEY in secret. From the docs: Instead of hardcoding the secret key in your settings module, consider loading it from an environment variable Besides that github warms in email if you have SECRET_KEY explicit in your code: GitGuardian has detected the following Django Secret Key exposed within your GitHub account. On the other hand, i want to allow anyone to run my project locally. I have it on github and deployed version on heroku, but it's still a demo project which is used as part of portfolio, not a serious one. What is the solution here? To break the protection convention and put it explicitly in settings.py? -
Turn django rest framework url completely off
Hey i was wondering if it is possible to completely turn off the drf own rendering url. I know that u can switch from the browsable api renderer to the JSON renderer. As i have it on my own settings shown below REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', ] } When I go to my localhost:8000/products I want to see simply a 404 page and not the JSON rendered products. I am currently using a simple router. -
make djangoAdmin a reall dashboard?
for my project i needed to add some features to the DjangoAdmin using ModelAdmin,used DA's builtins like https://docs.djangoproject.com/en/3.2/ref/contrib/admin and so on ,further i got more things like customizig DJ template link above. at the time, i just wondered that it would be really good for me if i could do more with templates, here is what i need ,almost like full customization . think about a User model that has img, username, and other things almost like a User , including all of these we reach inTime dashboards , can i customize my DjangoAdmin template using my User model and it's objects (img, ...)?? searched a lot and got some builted like django-admin-plus https://github.com/jsocol/django-adminplus any reference, snippet, or any related will help. thanks for your time,ErfanVahedi -
How to Create New User from User_Profile in DRF?
I am creating a cross-platform application in which the users are - Admin, Instructor, and Student. And for registering a new user privilege is only for admin users, so an admin user can add another admin, instructor, and student. I am trying to make nested serializers by which a UserProfile (AdminProfile, InstructorProfile, or StudentProfile) when created also creates User. I am new to django and drf. How can this be done ? serializers.py from rest_framework import serializers from .models import User, ProfileAdmin # # This will have GET method for seeing the users according to the userType. class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'password', 'user_type'] extra_kwargs = {'password': {'write_only': True}} class UserProfileSerializer(serializers.ModelSerializer): user_account = UserSerializer(many=False) class Meta: model = ProfileAdmin fields = ['email', 'first_name', 'last_name', 'address', 'telNum', 'aliasMailID', 'MSteamsID', 'user_account'] def create(self, validated_data): account_data = validated_data.pop('user_account') user = ProfileAdmin.objects.create(**validated_data) User.objects.create(**account_data) return user def update(self, instance, validated_data): account_data = validated_data.pop('user_account') user_account = instance.user_account instance.email = validated_data.get('email', instance.email) instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.address = validated_data.get('address', instance.address) instance.telNum = validated_data.get('telNum', instance.telNum) instance.aliasMailID = validated_data.get('aliasMailID', instance.aliasMailID) instance.MSteamsID = validated_data.get('MSteamsID', instance.MSteamsID) instance.save() user_account.username = account_data.get('username', user_account.username) user_account.user_type = account_data.get('user_type', user_account.user_type) return instance models.py from django.db import models … -
Python Django function got multiple values for argument
I am trying to call a function to print a receipt using Django in an html file. The function has 1 variable print_order_receipt(number) where the number is the order number fetched from Shopify API. This is the HTML code I did: path('print/<int:number>/', views.print_order_receipt, name="print") And this is the function: def print_order_receipt(number): order = Order.objects.get(number=number) printer = Network("192.168.1.100") printer.text('**********************************************\n') printer.text('LNKO vous remercie!\n') printer.text('**********************************************\n') printer.text('\n') printer.text('\n') printer.text('Commande Numero: ') printer.text(order.number) printer.text('\n') printer.text('\n') printer.text('Montant total a payer: ') printer.text(order.totalprice + " MAD") printer.text('\n') printer.text('Dont taxes: ') printer.text(order.tax + " MAD") printer.text('\n') printer.text('Client: ') printer.text(order.clientfname + ' ' + order.clientlname) printer.text('\n') printer.text('Une facture detaillee a ete envoyee a:\n') printer.text(order.clientemail) printer.barcode(order, 'EAN13', 64, 2, '', '') printer.qr("You can readme from your smartphone") printer.cut() And these are the 2 HTML versions I tried, both are not working: <td><a href="/print/{{ number }}">Imprimer</a></td> <td><a href="{% url 'print' {{ number }} %}">Imprimer</a></td> I don't know what I'm doing wrong here! Here is the Traceback error: Environment: Request Method: GET Request URL: http://localhost:8000/print/12500/ Django Version: 2.2.5 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', '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'] Traceback: File "D:\Dropbox\Dropbox\My Laptop\lnko\printer_receipt\venv\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "D:\Dropbox\Dropbox\My Laptop\lnko\printer_receipt\venv\lib\site-packages\django\core\handlers\base.py" … -
How can I store the value of one IntegerField model in another model?
** Hi beginner in Django here, I want to have a model that'll allow the user to modify the balance model, a model for deposit and withdrawal, in a way that the value for the user's balance model can be updated. The user can modify it using the class based view "updateview" ** from django.db import models from django.contrib.auth.models import User # Create your models here. class Task(models.Model): # DEPOSITOR user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, blank=True, max_length=30) # ACCTNO title = models.CharField(max_length=7) # To check number of accounts accountComplete = models.BooleanField(default=False) # BALANCE balance = models.IntegerField(null=True, blank=True) #WITHDRAWAL model #DEPOSIT model def __str__(self): return self.title class Meta: order_with_respect_to = 'user' -
What is wrong with this inkscape extension?
I am not a programmer. I used to use an inkscape extension that was designed to change the path in inkscape to Gcode. Recently this extension stopped working giving the following error massage. The extension has 5 python files (unicorn.py, init.py, context.py, entities.py, svg_parser.py). The error massage I keep getting is: Traceback (most recent call last): File "unicorn.py", line 23, in from unicorn.svg_parser import SvgParser File "C:\Program Files\Inkscape\share\inkscape\extensions\unicorn\svg_parser.py", line 4, in import entities ModuleNotFoundError: No module named 'entities' **Based on the error massage I think the problem is with python.py or svg_parder.py I post the unicorn.py and svg_parser.py here. Can anybody help me with this? unicorn.py text #!/usr/bin/env python ''' '' import sys,os import inkex from math import * import getopt from unicorn.context import GCodeContext from unicorn.svg_parser import SvgParser class MyEffect(inkex.Effect): def __init__(self): inkex.Effect.__init__(self) self.OptionParser.add_option("--extrude_multiple", action="store", type="float", dest="extrude_multiple", default="1.0", help="Extrude_multiple") self.OptionParser.add_option("--e_r_pattern", action="store", type="float", dest="e_r_pattern", default="1.0", help="E_r_pattern") self.OptionParser.add_option("--e_r_speed", action="store", type="float", dest="e_r_speed", default="900.0", help="E_r_speed") self.OptionParser.add_option("--z_hop_enabled", action="store", type="inkbool", dest="z_hop_enabled", default="true", help="Z_hop_enabled") self.OptionParser.add_option("--z_hop_height", action="store", type="float", dest="z_hop_height", default="10.0", help="Z_hop_height") self.OptionParser.add_option("--z_hop_speed", action="store", type="float", dest="z_hop_speed", default="900.0", help="Z_hop_speed") self.OptionParser.add_option("--x_move", action="store", type="float", dest="x_move", default="0.1", help="X move") self.OptionParser.add_option("--y_move", action="store", type="float", dest="y_move", default="0.1", help="Y move") self.OptionParser.add_option("--layer_delay", action="store", type="int", dest="layer_delay", default="10000", help="Layer_delay") self.OptionParser.add_option("--retraction", action="store", type="float", dest="retraction", default="0.1", help="Retraction") self.OptionParser.add_option("--z_up", action="store", type="float", dest="z_up", … -
Fetch API Django
I'm attempting to implement API from rapidapi.com def home(request): headers = { 'x-rapidapi-host': "...", 'x-rapidapi-key': "..." } url = "..." response = requests.request("GET", url, headers=headers).json() my print statement shows the following: {'data': [{'iso': 'CHN', 'name': 'China'}, {'iso': 'TWN', 'name': 'Taipei and environs'}, {'iso': 'USA', 'name': 'US'}, {'iso': 'JPN', 'name': 'Japan'}, {'iso': 'THA', 'name': 'Thailand'}, {'iso': 'KOR', 'name': 'Korea, South'}, {'iso': 'SGP', 'name': 'Singapore'}, {'iso': 'PHL', 'name': 'Philippines'}, {'iso': 'MYS', 'name': 'Malaysia'}, {'iso': 'VNM', 'name': 'Vietnam'}, {'iso': 'AUS', 'name': 'Australia'}, {'iso': 'MEX', 'name': 'Mexico'}, {'iso': 'BRA', 'name': 'Brazil'}, {'iso': 'COL', 'name': 'Colombia'}, {'iso': 'FRA', 'name': 'France'} How do I insert the data in my template ??? I do understand it's a list ... I did attempted in my views.py : d ={ "iso":response ['data']['iso'], "name":response ['data']['name'] } my template looks like so: <h1> {{data.iso}}</h1> <h2>{{data.name}}</h2> It does not work ... -
Django // Daphne 500 error on all requests after version update "TypeError: object HttpResponse can't be used in 'await' expression"
I have a problem where I'm getting 500 responses after updating Django from version 3.1.13 to 3.2.8. The issue wasn't occurring on the previous version of Django, and it only occurs if both the Django Channels app and OpenCensus middleware are enabled in settings.py. I would really appreciate if someone can help verify that my asgi.py and settings.py are configured correctly, or identify the dependency causing the issue so that I can follow through and raise a bug. Repo that reproduces the issue https://github.com/oscarhermoso/bug-opentelemetry-django-asgi Daphne error as it appears in the browser 500 Internal Server Error Exception inside application. Daphne ASGI entrypoint # testproject/asgi.py import os from django.core.asgi import get_asgi_application # os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'testproject.settings') from channels.auth import AuthMiddlewareStack # noqa from channels.routing import ProtocolTypeRouter, URLRouter # noqa import testproject.routing # noqa application = ProtocolTypeRouter({ # Django's ASGI application to handle traditional HTTP requests "http": get_asgi_application(), # WebSocket chat handler "websocket": AuthMiddlewareStack( URLRouter( testproject.routing.websocket_urlpatterns ) ), }) Installed apps and middleware # settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'opencensus.ext.django.middleware.OpencensusMiddleware' ] Error Dump System check identified no issues (0 silenced). October 09, 2021 - 10:59:03 Django version … -
I get some undefiend behavior in django settings
I changed a drf settings to REST_FRAMEWORK = {'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',)} It's disabled BrowsableAPI. And if I import BrowsableAPI in settings of my proj then this enabled again. Why is it work so? -
Is there any way to send mails regulary using Sendgrid?
I want to send monthly notifications to users that log on to my website. I've thought of using Sendgrid's Marketing campaigns to send monthly mails but it doesn't fit perfectly to my needs. I'll have to keep adding emails to the automation at a month's duration and that doesn't seem the right way to do it.