Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to set user field in the nested form of a django nested inline formset - fails
I followed this: https://www.yergler.net/2009/09/27/nested-formsets-with-django/ and this: django inline formsets with a complex model for the nested form and overall my code works great. class Account(models.Model): user_username = models.ForeignKey(User, on_delete=models.CASCADE) account_name = models.CharField(max_length=30) class Classification(models.Model): user_username=models.ForeignKey(User, on_delete=models.CASCADE) data_id=models.ForeignKey(ImportData, on_delete=models.CASCADE) class ImportData(models.Model): user_username = models.ForeignKey(User, on_delete=models.CASCADE) data_id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) ClassificationFormset = inlineformset_factory(ImportData, Classification, exclude=('user_username',), extra=1) # below is just what came from the nested formset links above: pasted here for easy reference. class BaseNestedTransactionFormset(BaseInlineFormSet): def add_fields(self, form, index): # allow the super class to create the fields as usual super(BaseNestedTransactionFormset, self).add_fields(form, index) try: instance = self.get_queryset()[index] pk_value = instance.pk except IndexError: instance=None pk_value = hash(form.prefix) transaction_data = None if (self.data): transaction_data = self.data; # store the formset in the .nested property form.nested = [ CategoryFormset(data=transaction_data, instance = instance, prefix = 'CAT_%s' % pk_value)] def is_valid(self): result = super(BaseNestedTransactionFormset, self).is_valid() for form in self.forms: if hasattr(form, 'nested'): for n in form.nested: # make sure each nested formset is valid as well result = result and n.is_valid() return result def save_new(self, form, commit=True): """Saves and returns a new model instance for the given form.""" instance = super(BaseNestedTransactionFormset, self).save_new(form, commit=commit) # update the form’s instance reference form.instance = instance # update the … -
Django importing FileNotFoundError: [Errno 2] No such file or directory:
I tried to import the folder 'covid_data' with files, so that I can use functions from the file 'coviddata'(which reads csv files from its directory), but I've been stuck for a while here. It yields lines of errors with FileNotFoundError: [Errno 2] No such file or directory: 'restrictions.csv'. I tried joining directories, but to no avail. Tried creating a separate 'static' folder with csv files and moving coviddata.py to plots (the same directory as views.py) with then restrictions=pd.read_csv('static/restrictions.csv'), which also didn't work. screenshot -
Django 3rd party login duplicate email
I set up my django application to be able to sign in with google and facebook 3rd party applications. However, whenever I already have an account that signs up with a gmail account that already exists, I get a weird signup page that looks like this: Menu: Sign In Sign Up Sign Up You are about to use your Google account to login to example.com. As a final step, please complete the following form: Username: testuser An account already exists with this e-mail address. Please sign in to that account first, then connect your Google account. E-mail (optional): email@test.com Sign Up » Is there a way to fix this so it can ask the user for a different email instead of breaking like this? When the user hasn't been registered before through the application, this problem does not occur. -
How to filter a ManyToMany field from django template?
I have a model named Universities in which there is a ManyToMany field named bookmarks associated with User model. In template file, I have looped through all the universities {% for university in universities %} and I am trying to show a bookmark icon based on the logged in user has bookmarked that specific university or not. However, it seems like I can not filter the query in template directly. How do I do that? -
When I set CSRF_COOKIE_HTTPONLY = True then 403 (Forbidden) error occurred
In my settings.py: ... CSRF_COOKIE_HTTPONLY = True SESSION_COOKIE_HTTPONLY = True CSRF_COOKIE_SECURE = False CORS_ALLOW_CREDENTIALS = True authenticate.py: from rest_framework_simplejwt.authentication import JWTAuthentication from django.conf import settings from rest_framework import exceptions from rest_framework.authentication import CSRFCheck def enforce_csrf(request): """ Enforce CSRF validation. """ check = CSRFCheck() # populates request.META['CSRF_COOKIE'], which is used in process_view() check.process_request(request) reason = check.process_view(request, None, (), {}) print(reason) if reason: # CSRF failed, bail with explicit error message raise exceptions.PermissionDenied('CSRF Failed: %s' % reason) class CustomAuthentication(JWTAuthentication): def authenticate(self, request): ..... validated_token = self.get_validated_token(raw_token) enforce_csrf(request) return self.get_user(validated_token),validated_token Error: CSRF token missing or incorrect. Forbidden: /photos/photo_support/ when I set CSRF_COOKIE_HTTPONLY = False then all work very well. What's the reason when I set CSRF_COOKIE_HTTPONLY = True then they me throw 403 Forbidden error. My Frontend is ReactJS. TestMe.js: Axios.defaults.withCredentials = true Axios.defaults.xsrfCookieName = 'csrftoken'; Axios.defaults.xsrfHeaderName = 'X-CSRFToken'; const TestMe = () => { .... const payHandle = () => { Axios.post('http://localhost:8000/photos/photo_support/', { data:data }) .then(res => { console.log(res.data) }) .catch(error => alert(error.message)) } ... -
Generate Refer Code From Username in Django?
I have unique username in User model. I want to generate refer code based on username. My Member model is as. I want refer code to be success if correct username is set but the refer code is set to be in char field. how can I do that? class User(AbstractBaseUser) username = model.CharField(unique = True, max_length = 70) class Member(BaseModel): user = models.ForeignKey(User, on_delete=models.CASCADE) refer_code = models.CharField(max_length=20) class Meta: default_permissions = () def clean(self): if not self.user.is_member: raise DjangoValidationError({'user': _('User must member')}) if not self.refer_code not in self.user.username: # dummy code ' -
How to get field from django model by name from list
I got model like: class mymodel(models.Model): val1 = models.FloatField(default=0) val2 = models.FloatField(default=0) ...and more var with other names name = models.CharField(max_length=200) url = models.CharField(max_length=200) I need change values in many models but not all fields (only from list) list= ['val1', 'val2' .... 'val15'] for entry in list: mymodel.entry = data[entry] How can i do it? i tried {entry}, entry, [entry] -
Django allauth: Custom SignUp form doesn't save all of the fields
I have made a custom signup form but it seems that my app doesn't try to save all the data from a post request. SQL query that is executed is clearly missing few fields. Do you have any idea what's happening? Should I make a custom view for signup also? Error django.db.utils.IntegrityError: (1048, "Column 'birth_date' cannot be null") Post request body csrfmiddlewaretoken 'S6s1kocaG5nKQyeKfJd4cTD6do3Dv2VjrElQ4DYESybICDQtueQG5TkqQf5HgP7W' username 'User123' email 'mrjst1995@gmail.com' first_name 'John' last_name 'Doe' city '2' address 'blahblahblah' phone '005006007' birth_date '2006-06-09' password1 'somerandpass' password2 'somerandpass' Executed query db <_mysql.connection open to 'localhost' at 02154B30> q (b'INSERT INTO `users_user` (`email`, `username`, `password`, `date_joined`, `l' b'ast_login`, `is_admin`, `is_active`, `is_staff`, `is_superuser`, `first_name' b"`, `last_name`, `phone`, `city_id`, `address`, `birth_date`) VALUES ('mrjst1" b"995@gmail.com', 'User123', 'pbkdf2_sha256$216000$6H02ElhAxQ3y$y56l29/sTf0Oyy" b"+sa39MX2cgLlgvPzsA+K5HWOb/NjU=', '2021-03-21 18:05:49.199287', '2021-03-21 1" b"8:05:49.199287', 0, 1, 0, 0, 'John', 'Doe', '', NULL, '', NULL)") self <MySQLdb.cursors.Cursor object at 0x05194BB0> models.py from django.db import models from django.contrib.auth import get_user_model from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.contrib.auth.hashers import make_password class City(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=20,null=False) def __str__(self): return self.name class UserManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, city, address,phone, birth_date, password=None): if not email: raise ValueError('Korisnik mora imati email adresu') if not username: raise ValueError('Korisnik mora imati korisničko ime') if … -
Django INNER JOIN and WHERE
Let me introduce you with the structure. Let's say I have 3 models defined as: class User(AbastractUser): some fields... class UserProfile(Model): gender = models.CharField(max_length=10, choices=GENDER_CHOICES, default='unknown', verbose_name=_('Gender')) ... user = models.OneToOneField(User, related_name='userprofile', on_delete=CASCADE) preferences = models.OneToOneField( Preferences, related_name='user_profile', null=True, on_delete=CASCADE ) class Preferences(TimestampedModel): some fields... method = models.CharField( max_length=10, null=True, blank=True, default=None, choices=[(x, x) for x in methods] ) I would like to write this query with django models, what would be the way? Query: SELECT * from users as u INNER JOIN users_profile as up ON u.id as up.user_id INNER JOIN preferences as p ON p.id as up.preference_id WHERE p.method = 'TEST' Any suggestions, what would be the cleanest way, also most optimised? -
How use Json variable in Django Template Tags?
How use json variable in Django template tags in srcipts? I cannot use variables in javascript strings when I use django template tags and my own custom tags like: {% if ${comment}|comment_like_ip:ip %} $(document).ready(function(){ const comments = document.getElementById('comments') const loadBtn = document.getElementById('load-btn') const loadBox = document.getElementById('loadBox') let visible = 3 vis = { num : visible, } let handleGetData = () => { $.ajax({ type: 'GET', data: vis, url: "{% url 'load-comments' video.slug %}", success: function(response) { max_size = response.max const data = response.data console.log(data) data.map(comment=>{ console.log(comment.id) if(comment.is_child) { comments.innerHTML += `<div class="comment"> ${comment.nickname} | ${comment.timestamp} <div style="background-color: black; width: 300px;"> <p>Ответ: ${comment.parent_name}</p> <p>Комментарий: "${comment.parent_text}"</p> </div> <p>${comment.text}</p> <p><a href="#" class="like-comment" data-id="${comment.id}"> {% if ${comment}|comment_like_ip:ip %} <i class="fas fa-heart" style="color: #BE0E61;"></i> {% else %} <i class="far fa-heart"></i> {% endif %} <span>${comment.likes}</span></a></p> <button style="background-color: black;" class="reply" data-id="${comment.id}" data-parent=${comment.get_parent}>Ответить</button> <form action="" method="POST" class="comment-form" id="form-${comment.id}" style="display:none;"> <textarea type="text" name="comment-text"> </textarea> <br> <input type="submit" class="btn submit-reply" data-id="${comment.id}" data-submit-reply="${comment.get_parent}" value="Отправить"/> </form> </div>` } else { comments.innerHTML += `<div class="comment"> ${comment.nickname} | ${comment.timestamp} <p>${comment.text}</p> <p><a href="#" class="like-comment" data-id="${comment.id}"> {% if True %} <i class="fas fa-heart" style="color: #BE0E61;"></i> {% else %} <i class="far fa-heart"></i> {% endif %} <span>${comment.likes}</span></a></p> <button style="background-color: black;" class="reply" data-id="${comment.id}" data-parent=${comment.get_parent}>Ответить</button> <form action="" method="POST" class="comment-form" … -
Django/Docker/Postgresql - psycopg2 error
hope you can help me with my following issues. This is my first time using docker and docker-compose. I'm trying to "dockerize" my Django project running on Postgresql database and I'm having an issues with psycopg2 module. I'm using psycopg2-binary, as it's normaly the only one that works with my configuration. I've tried the standard psycopg2 package but it still doesn't work. So I will begin by showing you some of my files: relevant part of settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES_DIRS = os.path.join(BASE_DIR, "templates") # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY', 'changeme') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] ALLOWED_HOSTS_ENV = os.environ.get('ALLOWED_HOSTS') if ALLOWED_HOSTS_ENV: ALLOWED_HOSTS.extend(ALLOWED_HOSTS_ENV.split(',')) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'core.apps.CoreConfig', 'django.contrib.staticfiles', 'jquery', 'ckeditor', 'ckeditor_uploader', 'crispy_forms', ] 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', ] ROOT_URLCONF = 'littledreamgardens.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'core/templates/core/')], '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', 'core.views.category_list', ], }, }, … -
Django templates: Calling super in case of multi-level extends
This is my current template structure: example_template_1.html example_template_2.html extends example_template_1.html example_template_3.html extends example_template_2.html How would I get content of a specific block from example_template_1.html in example_template_3.html? Basically, I need something that does {{ block.super.super }} in example_template_3.html to override the contents of a specific block in example_template_1.html. Is that possible? -
301 redirect router for Django project
I have a website building tool created in Django and I'd like to add easy user defined 301 redirects to it. Webflow has a very easy to understand tool for 301 redirects. You add a path (not just a slug) and then define where that path should lead the user. I'd like to do the same for the Django project I'm working on. I currently allow users to set a slug that redirects (/<slug:redirect_slug>/) and they can set to go to any URL. But I'd like them to be able to add, for example, the path for an old blog post ('/2018/04/12/my-favorite-thing/') What's the best URL conf to use in Django to safely accept any path the user wants? -
No module named error If I create and use batch file in Django project
I am trying to create batch file that will use for "Task Scheduler". It will update my database from csv file daily. Even py manage.py runscript delete_data is running in Django shell command, I faced following error after run batch file. File "*****\Desktop\argeportal\scripts\delete_data.py", line 4, in <module> from core.models import News ModuleNotFoundError: No module named 'core' What I am missing? How can I create it? My script py from core.models import News import csv def run(): with open(r"csvdata.csv") as f: reader = csv.reader(f, delimiter=';', quotechar='"') next(reader) # Advance past the header News.objects.all().delete() print(reader) for row in reader: print(row) c = News(id=row[0], title=row[1], body=row[2], content=row[3], addedDate=row[4], updateDate=row[5], newsImg=row[6]) c.save() My batch file @echo off "C:\Users\bense\AppData\Local\Programs\Python\Python38-32\python.exe" "C:\Users\bense\Desktop\argeportal\scripts\delete_data.py" cmd /k -
Birthdays employee Django Model
I have a model with employees data, name, photo, date of birth and etc. I'm trying to create a url that shows the birthdays of the employees where I can filter, if i click at one button, filter the birthdays of the day, another button, birthdays of the week and so on. I'm don't know where I can work with the date of birth to generate theses "category". I'm looking for ideas to implement these Thanks in advance -
How to pass on value to particular title in django
I have fetched the value from my table MarketingMaestro whose structure is given below Structure of MarketingMaestro class MarketingMaestro (models.Model): product_title = models.CharField(max_length=250) total_value = models.IntegerField() total_votes = models.IntegerField() I am able to fetch the value perfectly using for loop which gives the below output in the html So when you click on Invest button from one of the card, you will be able to invest some amount into that particular project. Popup looks like this So I am facing two issues here, I am not able to display the particular project name whos invest button is clicked, and after adding the amount and submitting it I am not getting any error but it is not getting saved in the database. I am not getting the idea how should I pass the project name to the ajax code. AJAX code $(document).on('submit', '#post-form',function(e){ // console.log("Amount="+$('input[name="amount"]').val()); e.preventDefault(); // getting the value entered amount = $('input[name="amount"]').val(); console.log("Amount entered by user="+amount); $.ajax({ type:'POST', url:'{% url "brand" %}', data:{ name: name, emailID: emailID, product_title: product_title, total_investment : total_investment, amount: amount, csrfmiddlewaretoken: '{{ csrf_token }}', action: 'post' }, error : function(xhr,errmsg,err) { $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+ " <a href='#' … -
How to Validate Against Current User in Django?
I have following model class User(AbstractBaseUser, PermissionsMixin): #: First and last name do not cover name patterns around the globe username = CharField(max_length=100,unique=True) email = models.EmailField(_('email address'), unique=True) full_name = TitleCharField(max_length=100) phone_number = PhoneNumberField() referred_by = models.ForeignKey('self', on_delete=models.CASCADE) is_member = models.BooleanField(default=False) is_active = models.BooleanField(default=False) Scenario is same user cannot be a user and referred by user. what I have done so far is def clean(self): if self == self.referred_by: raise DjangoValidationError({'referred_by': _('Same user cannot be referred by user')}) I don't feel I am doing right what shall I do? -
Return querysets
here is the code : def some_brand_mobiles(*brand_names): if not brand_names: return (Mobile.objects.all()) else: for brand in brand_names: return Mobile.objects.filter(brand__name=brand) the expected output for some_brand_mobiles('Apple', 'Huawei', 'Samsung') : <QuerySet [<Mobile: Apple iphone 8>, <Mobile: Apple iphone 10>, <Mobile: Apple iphone XIII>]> <QuerySet [<Mobile: Huawei P40>, <Mobile: Huawei P10 Pro>, <Mobile: Huawei P90 Pro>]> <QuerySet [<Mobile: Samsung A80>, <Mobile: Samsung A70>]> instead, it returns this only: <QuerySet [<Mobile: Apple iphone 8>, <Mobile: Apple iphone 10>, <Mobile: Apple iphone XIII>]> I know using a return inside of a loop will break the loop and exit the function even if the iteration is not over and I have two options either yielding or appending data to a list and then return the list but none of them work for me and I do not know how to do that and any help would be appreciated -
Serializing list of object in Django to nested json
I am new to Django/Python and was trying to work on project. I have to create an API with nested values like below { "rule": "ruleA" "criticality" : "High" "user": [ { "email" : "xyz@gmail.com" "username" : "xyz" }, { "email" : "abc@gmail.com" "username" : "abc" } ] } { "rule": "ruleB" "criticality" : "low" "user": [ { "email" : "pqr@gmail.com" "username" : "pqr" } ] } Below is my serializer.py class userSerializer(serializers.Serializer): email = serializers.CharField() username= serializers.CharField() class cloudScoreAnalysisSerializer(serializers.Serializer): rules = serializers.CharField() criticality = serializers.CharField() user = userSerializer(many=True,source='*') While running this code I'm getting attribute error: Got AttributeError when attempting to get a value for field `email` on serializer `userSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. It seems like the code is unable to find the email filed as it's inside the json array ([ { } ]) . Kindly help. -
How to split fields of model class between different views and templates to take inputs in different forms?
I have a class in my models.py with name 'Client', and it has different fields like (name, dob.. etc). I have a view for that called 'ClientCreateView' in views.py in which I am taking input in some fields of Client class (NOT all fields). And the template for this is called 'client_form.html'. Related files are given below: models.py: class Client(models.Model): name = models.CharField(max_length = 100) dob = models.SlugField(max_length = 100) CNIC = models.SlugField(max_length = 100) property_type = models.CharField(max_length = 100) down_payment = models.IntegerField() date_posted = models.DateTimeField(default=timezone.now) installment_month = models.CharField(max_length = 100) installment_amount = models.IntegerField(default = 0) views.py: class ClientCreateView(CreateView): model = Client fields = ['name', 'dob', 'CNIC', 'property_type', 'down_payment'] class AddInstallmentView(CreateView): model = Client fields = ['installment_month', 'installment_amount'] client_form.html {% extends "property_details/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content_section"> <form method="post"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"> Add New Client</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Add Client</button> </div> </form> </div> {% endblock %} Now As you can see that I took the inputs in my views.py in the first five fields (name, dob, CNIC, property_type, down_payment), because these are the only fields required to add new client to my database. … -
After deleting python 3.7 and installing 3.9 my python project is showing following error
when i am trying to use virtualenv from terminal by following command workon api "eroor occurs is 'workon' is not recognized as an internal or external command, operable program or batch file. enter image description here -
How to show two tables inline in django admin?
I have created two models in models.py, Product and ProductImage. Product is needed to show a certain product. ProductImage is needed to show multiple images of one Product. Here is the code in models.py : class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.DecimalField(max_digits=7, decimal_places=2) digital = models.BooleanField(default=False, null=True, blank=False) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url class ProductImage(models.Model): product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE) image = models.ImageField(null=True, blank=True) def __str__(self): return self.product.name @property def imageURL(self): try: url = self.image.url except: url = '' return url And here is the code in admin.py : from django.contrib import admin from .models import * # Register your models here. class ProductImageAdmin(admin.TabularInline): model = ProductImage extra = 2 # how many rows to show class ProductAdmin(admin.ModelAdmin): inlines = (ProductImageAdmin,) admin.site.register(ProductAdmin, ProductImageAdmin) I keep getting this error: TypeError: 'MediaDefiningClass' object is not iterable I searched this error but I still did not manage to fix this. I also looked in the documentation (https://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-many-to-many-intermediary-models) What is the cause of this error? Thank you! -
JWT Logout "detail": "Authentication credentials were not provided."
I am trying to create a Logout endpoint for a jwt token in djangorestframework. When I access this endpoint via postman, I get "detail": "Authentication credentials were not provided." What am I missing here? Am I supposed to create a serializer that has a field for the refresh token and add it to the view? Am I parsing the data corretly in postman? views.py from rest_framework.permissions import IsAuthenticated from rest_framework_simplejwt.tokens import RefreshToken class LogoutView(APIView): permission_classes = (IsAuthenticated,) def post(self, request): try: refresh_token = request.data["refresh_token"] token = RefreshToken(refresh_token) token.blacklist() return Response(status=status.HTTP_205_RESET_CONTENT) except Exception as e: return Response(status=status.HTTP_400_BAD_REQUEST) urls.py from accounts.views.user_api_views import ( LogoutView, LogoutAllView, ) urlpatterns = [ path("auth/", include("djoser.urls")), path("auth/", include("djoser.urls.jwt")), path("auth/token/", ObtainCustomizedTokenView.as_view(), name="token_obtain_pair"), path( "auth/token/refresh/", jwt_views.TokenRefreshView.as_view(), name="token_refresh", ), path("logout/", LogoutView.as_view(), name="logout"), path("logout_all/", LogoutAllView.as_view(), name="logout_all"), ] settings.py INSTALLED_APPS = [ ... # local apps # 3rd party "storages", "rest_framework", "rest_framework_gis", "rest_framework.authtoken", "djoser", "django_celery_beat", "raven.contrib.django.raven_compat", "rest_framework_simplejwt.token_blacklist", ] ...... SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(weeks=521), # 10 years "REFRESH_TOKEN_LIFETIME": timedelta(weeks=521), "ROTATE_REFRESH_TOKENS": True, "BLACKLIST_AFTER_ROTATION": True, "ALGORITHM": "HS256", "SIGNING_KEY": SECRET_KEY, "VERIFYING_KEY": None, "AUTH_HEADER_TYPES": ("JWT",), "USER_ID_FIELD": "id", "USER_ID_CLAIM": "user_id", "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",), "TOKEN_TYPE_CLAIM": "token_type", } ...... REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", ), "DEFAULT_PARSER_CLASSES": [ "rest_framework.parsers.JSONParser", "rest_framework.parsers.FormParser", "rest_framework.parsers.MultiPartParser", ], "DEFAULT_PERMISSIONS_CLASSES": ("rest_framework.permissions.IsAuthenticated"), } Image from Postman -
Django python variable not printing in html
this is my code in my views.py: import requests import os import json from django.http import JsonResponse, HttpResponse from django.shortcuts import render def btc(request): query_url = [ 'https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=4&interval=daily', ] headers = { } result = list(requests.get(u, headers=headers) for u in query_url) json_data1 = result[0].json() btcprices = [] btcprices.append(int(json_data5['prices'][0][1])) print(btcprices) context = { "btcprices": btcprices, } return render(request, "index.html", context) when i do {{ btcprices }} in my html file nothing apperas on the web page when i "python manage.py runserver" it works with other variables that i removed from the code but i'm struggling with this one. Any idea why ? by the way the print(btcprices) gives me : [59014, 57922, 58243, 58376] it's type is a list of integers -
How to find dictionary by date in dictionary of dictionaries
I have a dictionary of dictionaries, each is a boxscore of a game in a season. If I wanted to pull one specific game by date, how would I pull that one dictionary out? Something like... for game in schedule: boxscore = game.boxscore if date = '2021-03-21' Thanks! def management(request): """ View to return site management page """ schedule = Schedule('CHI') for game in schedule: boxscore = game.boxscore date = game.date date_time_date = datetime.datetime.strptime(date, '%a, %b %d, %Y') game_date = date_time_date.strftime('%Y-%m-%d') context = { 'game_date': game_date, 'boxscore': boxscore, } return render(request, 'management/management.html', context)