Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django get wrong value from json.loads in POST request
I need to pass a user-input geojson with request to further process the information. The data comes from a textfile and then passed to the views.py in django with a POST request. Before passing to the view I checked the value of the string and that appears to be correct. After passing that to the view, I made a print check and some values inside the JSON are changed in string like: "{"id": "13871", "type":SOH@ "Feature", "properties": {"lanes": 0, "highway": "pedestrian" etc....." or "{"id":"86","type":"FeatureSOHVT","properties":etc......." The bold strings sometimes appear even inside the values of the dictionary. The js file: $.ajax({ type: 'POST', url: $('#confImp').data('url'), dataType: 'json', data: {'streetWeb': JSON.stringify(street_web), 'int_points': JSON.stringify(int_points_loaded), 'csrfmiddlewaretoken': csrftoken,}, success: function(res){blablabla} The django views.py: elif 'streetWeb' in request.POST: print(json.loads(request.POST.get('streetWeb'))) request.session['Working_area_final'] = json.loads(request.POST.get('streetWeb')) print(json.loads(request.POST.get('int_points'))) request.session['int_points'] = json.loads(request.POST.get('int_points')) return JsonResponse({'Risposta': 'Done'}) -
Code works fine without subquery, why to use it?
newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at') posts = Post.objects.annotate(newest_commenter_email=Subquery(newest.values('email')[:1])) And, newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at') posts = Post.objects.annotate(newest_commenter_email=newest.values('email')[:1]) Both, works fine then why use a Subquery, what are its advantages? -
Problem with INSTALLED_APPS in django settings.py file
If I try to add blog.apps.BlogConfig string to INSTALLED_APPS (to define the blog app), local server won't start giving me an error. Photos attached below: I am expecting for the separate section to appear on site. Was doing it by tutorial of the Youtuber Corey Schafer: https://www.youtube.com/watch?v=qDwdMDQ8oX4&list=PL-osiE80TeTtoQCKZ03T -
What is the meaning of this wsgi apache error log message (in django)
My django site seems to be working without any problems. But, looking at the apache2 error log, I frequently see this message (but no traceback or anything like it) [Thu Dec 22 16:37:32.948596 2022] [wsgi:error] [pid 763796:tid 140436065670912] [remote xxx.xxx.xxx.xxx:63167] [<JobsListUser: Jillian>] [Thu Dec 22 16:37:32.948671 2022] [wsgi:error] [pid 763796:tid 140436065670912] [remote xxx.xxx.xxx.xxx:63167] ja I have a model called JobsListUser, and these 2 lines appear repeatedly for all users (for example, [<JobsListUser: Kelly>] etc.) I assume the 'ja' is code of some kind for japanese (the site is viewable in english and japanese, but i've never seen an error) Can someone explain this to me? I want to know what the error is and if I need to fix it. I can't see any information in the log telling me which part of the code is generating the error. -
Bad Request when serializing data
I'm creating an API endpoints for a B2B ecommerce application. I have a company model to store the data about companies that are creating an account. I linked the company model to the default User Model in django, so that a user account will be created along with a company object. I linked the company model and the user model (One-to-One relationship). I keep getting this error, "Bad Request: /accounts/create/" when I submit data through the through the browsable API. This is my model. from django.db import models from django.contrib.auth.models import User # Create your models here. class Company(models.Model): class IndustryType(models.TextChoices): MANUFACTURING = "MAN", "Manufacturing" CONSTRUCTION = "CON", "Construction" IT = "IT", "Information Technology" PROFESSIONAL_SERVICES = "PS", "Professional Services" HEALTHCARE = "HC", "Healthcare" FINANCIAL_SERVICES = "FS", "Financial Services" WHOLESALE_AND_DISTRIBUTION = "WD", "Wholesale and Distribution" RETAIL = "RET", "Retail" EDUCATION = "EDU", "Education" user = models.OneToOneField(User, on_delete=models.CASCADE) company_name = models.CharField(max_length=255) industry_type = models.CharField(max_length=255, choices=IndustryType.choices) tax_identification_number = models.CharField(max_length=15) address = models.CharField(max_length=255) phone = models.CharField(max_length=50) email = models.EmailField() def __str__(self): return self.company_name This is my serializer from rest_framework import serializers from django.contrib.auth.models import User from .models import Company class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = ( "company_name", "industry_type", "tax_identification_number", "address", "phone", … -
How to configure BaseURL in Django4?
I'm new to django and trying to set a baseURL in django4. I came upon How to set base URL in Django of which the solution is: from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^someuri/', include([ url(r'^admin/', include(admin.site.urls) ), url(r'^other/$', views.other) ])), ] but this import statement: from django.conf.urls import urls shows: Cannot find reference 'urls' in '__init__.py' What am I doing wrong? -
"&" and "|" vs "and" and "or" for "AND" and "OR" operators in Django
I have Blog model below. *I use Django 3.2.16 and PostgreSQL: # "store/models.py" from django.db import models class Blog(models.Model): post = models.TextField() def __str__(self): return self.post Then, store_blog table has 2 rows below: store_blog table: id post 1 Python is popular and simple. 2 Java is popular and complex. Then, when running the filter() code using & or and or using Q() and & or Q() and and in test() view as shown below: # "store/views.py" from .models import Blog from django.db.models import Q def test(request): # With "&" # ↓ Here qs = Blog.objects.filter(post__contains="popular") & \ Blog.objects.filter(post__contains="simple") print(qs) # With "Q()" and "&" # ↓ Here # ↓ Here qs = Blog.objects.filter(Q(post__contains="popular") & Q(post__contains="simple")) print(qs) # ↑ Here # With "and" # ↓ Here qs = Blog.objects.filter(post__contains="popular") and \ Blog.objects.filter(post__contains="simple") print(qs) # With "Q()" and "and" # ↓ Here # ↓ Here qs = Blog.objects.filter(Q(post__contains="popular") and Q(post__contains="simple")) print(qs) # ↑ Here return HttpResponse("Test") I got the same result below: <QuerySet [<Blog: Python is popular and simple.>]> # With "&" <QuerySet [<Blog: Python is popular and simple.>]> # With "Q()" and "&" <QuerySet [<Blog: Python is popular and simple.>]> # With "and" <QuerySet [<Blog: Python is popular and simple.>]> # … -
How to create dockerfile & docker compose for django mysql with .env file?
dockerfile FROM python:3.10 WORKDIR /django_app ENV PYTHONUNBUFFERED 1 ADD . /django_app RUN pip install --upgrade pip RUN pip install -r requirements.txt COPY . /django_app docker-compose.yml version: '3.8' services: db: image: mysql:latest hostname: mysql restart: always ports: - '3308:3306' environment: MYSQL_DATABASE: 'test[[enter image description here](https://i.stack.imgur.com/Y6wAp.png)](https://i.stack.imgur.com/1OMAo.png)' MYSQL_USER : 'mysqluser' MYSQL_PASSWORD: 'root123' MYSQL_ROOT_PASSWORD: 'root123' # volumes: # - D:\django_project\db1:/var/run/mysqld # - D:\django_project\db:/var/lib/mysql web: build: . restart: on-failure command: sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" ports: - "8000:8000" depends_on: - db [pl check error in photos.](https://i.stack.imgur.com/ni4t7.png) First time create docker build but agine build docker getting errors. Database not connect docker image mysql. -
ValueError at /category/ The 'image' attribute has no file associated with it
I am building an Ecommerce website in Django for the first time. Some how despite following the YT tutorial, I am not able to render image that are uploaded from my Django Admin Panel. Here are my codes: Models.py class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() image = models.ImageField(null=True, blank=True, upload_to='image/') def __str__(self): return self.name Views.py def category(request): products = Product.objects.all() context = {"products":products} return render(request,'store/category.html', context) category.html {% for product in products %} <div class="col-lg-4 col-md-6"> <div class="product__item"> <div class="product__item__pic set-bg" data-setbg="{{product.image.url}}"> <div class="label new">New</div> <ul class="product__hover"> <li><a href="{{product.imageURL}}" class="image-popup"><span class="arrow_expand"></span></a></li> <li><a href="#"><span class="icon_heart_alt"></span></a></li> <li><a href="#"><span class="icon_bag_alt"></span></a></li> </ul> </div> <div class="product__item__text"> <h6><a href="#">{{product.name}}</a></h6> <div class="rating"> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> </div> <div class="product__price">${{product.price|floatformat:2}}</div> </div> </div> </div> {% endfor %} settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') Error I get: enter image description here Please Help. Thank you. I tried to render images in django by following along a Youtube Tutorial. -
I'm Getting Bad Request Error After Uploading the Video
I'm uing Django and React to make a YouTube clone. I tried to post the video on the frontend side, and got an error in terminal: <QueryDict: {'title': ['Test Video Creation'], 'user': ['1'], 'description': ['Is it working?'], 'image': [<TemporaryUploadedFile: attachment.png (image/png)>], 'video': [<TemporaryUploadedFile: video-for-fatube.mp4 (video/mp4)>]}>Bad Request: /api/admin/create/ And the problem is not in the backend settings, because when I made a post request in the postman, the video was succesfully created. creat.js File on frontend side to create videos. import React, { useState } from 'react'; import axiosInstance from '../../axios'; import { useHistory } from 'react-router-dom'; //MaterialUI import Avatar from '@material-ui/core/Avatar'; import axios from "axios"; import Button from '@material-ui/core/Button'; import CssBaseline from '@material-ui/core/CssBaseline'; import TextField from '@material-ui/core/TextField'; import Grid from '@material-ui/core/Grid'; import Typography from '@material-ui/core/Typography'; import { makeStyles } from '@material-ui/core/styles'; import Container from '@material-ui/core/Container'; import IconButton from '@material-ui/core/IconButton'; import PhotoCamera from '@material-ui/icons/PhotoCamera'; const useStyles = makeStyles((theme) => ({ paper: { marginTop: theme.spacing(8), display: 'flex', flexDirection: 'column', alignItems: 'center', }, avatar: { margin: theme.spacing(1), backgroundColor: theme.palette.secondary.main, }, form: { width: '100%', // Fix IE 11 issue. marginTop: theme.spacing(3), }, submit: { margin: theme.spacing(3, 0, 2), }, })); export default function Create() { const history = useHistory(); const initialFormData = Object.freeze({ … -
Error at /basic_app/ Invalid block tag on line 10: 'endblock', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
I am a beginner in HTML templates and Django. school_list.html {% extends "basic_app/basic_app_base.html" %} <!-- {% load static %} --> {% block body_block %} <h1>Here are the list of all the schools!</h1> <ol> {% for school in schools %} <h2><li><a href="{{school.id}}">{{school.name}}</a></li></h2> {% endfor % } </ol> {% endblock %} **Error:**TemplateSyntaxError at /basic_app/ Invalid block tag on line 10: 'endblock', expected 'empty' or 'endfor'. Did you forget to register or load this tag? Views.py from django.shortcuts import render from django.views.generic import (View,TemplateView, ListView,DetailView) from . import models # from django.http import HttpResponse # Template views with CBV class IndexView(TemplateView): template_name='index.html' # List View class SchoolListView(ListView): context_object_name='schools' model=models.School template_name='basic_app/school_list.html' # Detail View class SchoolDetailView(DetailView): context_object_name='school_detail' model=models.School template_name='basic_app/school_detail.html' models.py from django.db import models from django.urls import reverse # Create your models here. class School(models.Model): name=models.CharField(max_length=256) principal=models.CharField(max_length=256) location=models.CharField(max_length=256) def __str__(self): return self.name class Student(models.Model): name=models.CharField(max_length=256) age=models.PositiveIntegerField() school=models.ForeignKey(School,related_name='students',on_delete=models.CASCADE) def __str__(self): return self.name urls.py from django.urls import include, re_path # from django.conf.urls import url from basic_app import views app_name='basic_app' urlpatterns = [ re_path(r'^$',views.SchoolListView.as_view(),name='list'), re_path(r'^(?P<pk>\d+)/$',views.SchoolListView.as_view(),name='detail') ] I need output like the following image, when clicking on school page : -
How to access Authorization code flow, Implicit Flow and Hybrid flow in Django oauth toolkit
I want to implement OpenID connect in my project. So I started using Django Oauth Toolkit. I was able to make the changes in Dajango Rest framework menu and was able to test the Resource owner password-based flow using the curl command curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/ After that I made all the changes as mentioned in the OpenId Connect menu. I have Generated RSA private key Added the changes as mentioned in the documentation Then I registered applications for each flow as mentioned in the documentation. Then the problem arise. I tried testing these flows the same way I tested Resource owner password-based flow eg: For Authorization code flow curl -X POST -d "grant_type=password&username=user&password=aryan123&scope=openid" -u "rwOah6DU7PXPbpE7CWVokh16YeMIFsPCE4zv1ZUk:5p186YD3Wvf0nMz4bfXd9UJXbQnACMfpVzHwJ6AuneoPqnjJuoPUz4CiEM653gUIhCOMtV96Yymr1kLnAimdyfxWZMP2hOzslEH9kMpfoqyOorwviY8f1rs1BqcTSUtn" http://localhost:8000/o/token/ I'm getting the error: { "error": "invalid_grant", "error_description": "Invalid credentials given." } For Implicit Flow curl -X POST -d "grant_type=password&username=user&password=aryan123&scope=openid&response_type=id_token" -u "qKgH4Bx5QzOdSdRo5h7vUSpSaivHk0SaccMa0coH:DyNdcoS52JuanNhjjqqbRnemGaq27sQrwa43C6ieYahxCdHYXXJt4Y5ZdwXVbNZdZmt89XoAJ7kBuFoDZanZvhCCza3WMLWlCwSy5qv09W1QyJsLmTEGUzRHkytU21s1" http://localhost:8000/o/token/ I'm getting the error: { "error": "invalid_grant", "error_description": "Invalid credentials given." } For Hybrid flow curl -X POST -d "grant_type=password&username=user&password=aryan123" -u "YpKesUZnxyvOysKje4H2NNFhs45roO8z0SBu58Y5:Yf2IAsMRoLCbLrEUHsgPByLLnmFrNYPvqtYXuaZAJV5HbHioFZtbsTzh6Oj1W7jgWOKVU0PLsUwBPO0j5y7fhOLbUFiH2X9ZhdnQ3wJ7KxFOjTHYu2Cd52IxGO7U3iF3" http://localhost:8000/o/token/ I'm getting the error: { "error": "invalid_grant", "error_description": "Invalid credentials given." } For the development purpose I have generated the private key and stored it in a python file itself like this Note: The … -
Django - I want to store the data of 3 models into a single database in phpmyadmin (MySQL)
I have created 3 models (country, state and city) and the inputted data is getting stored in 3 different table. I want to store this data into a single table with following columns: Database Column Schema Models.py class Country(models.Model): id = models.AutoField(primary_key=True) parent_id = models.IntegerField(null=False) name = models.CharField(null=False, max_length=255) status = models.CharField(null= True, choices=Status_Choices, max_length=11, default='--Select Status--') added_by = models.IntegerField() updated_by = models.IntegerField() created_on = models.CharField(default=get_current_datetime_str , max_length=255) updated_on = models.CharField(default=get_current_datetime_str, max_length=255) def __str__(self): return self.name class State(models.Model): parent = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(null=False, max_length=255) def __str__(self): return self.name class City(models.Model): Country = models.ForeignKey(Country, on_delete=models.CASCADE) state = models.ForeignKey(State, on_delete=models.CASCADE) name = models.CharField(null=False, max_length=255) def __str__(self): return self.name admin.py from django.contrib import admin from location.models import Country, State, City from django import forms from django.contrib import admin class CountryAdmin(admin.ModelAdmin): exclude = ('parent_id', 'created_on', 'updated_on', 'added_by', 'updated_by') def save_model(self, request, obj, form, change): user = request.user # Check if the user is authenticated (i.e. logged in) if user.is_authenticated: # If the user is authenticated, set the added_by field to the user's ID obj.added_by = user.id else: # The user is not authenticated, do something else ... if change: obj.updated_by = user.id # Save the model instance super().save_model(request, obj, form, change) admin.site.register(Country, … -
Dockerized python.django app does not run in the browser
I have a python-django app built in ubuntu OS that I am trying to containerize. Docker builds and runs with no error. But when I try to browse the site in a browser, I do not see it. This is my allowed hosts in settings.py ALLOWED_HOSTS = ["localhost", "127.0.0.1","0.0.0.0"] And this is my dockerfile #base image FROM python:3.10 # setup environment variable ENV DockerHOME=/home/app RUN mkdir -p $DockerHOME WORKDIR $DockerHOME ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip3 install --upgrade pip # copy whole project to your docker home directory. COPY . $DockerHOME # run this command to install all dependencies RUN pip3 install -r requirements.txt # port where the Django app runs EXPOSE 8000 # start server CMD python3 manage.py runserver 0.0.0.0:8000 I tried to run it by the following commands with no luck. sudo docker run -p 8000:8000 myapp:v0 #also the following sudo docker run myapp:v0 I am browsing the site with http://0.0.0.0:8000/ I tried with the docker ip http://172.17.0.2:80000 So not sure what am I missing. Any idea would be very much appreciated. -
get size of data responsed to the browser in django?
I want get size of http data responsed to the browser in django. how to do that.? the destination i want is difference between gzip response and non-gzip response. -
How to run "AND" operator with "filter()" without "SyntaxError: keyword argument repeated:" error in Django?
I have Blog model below. *I use Django 3.2.16 and PostgreSQL: # "store/models.py" from django.db import models class Blog(models.Model): post = models.TextField() def __str__(self): return self.post Then, store_blog table has 2 rows below: store_blog table: id post 1 Python is popular and simple. 2 Java is popular and complex. Then, when writing the filter() code with 2 post__contains arguments in test() view to run AND operator as shown below: # "store/views.py" from .models import Person def test(request): print(Blog.objects.filter(post__contains="popular", post__contains="simple")) # Here return HttpResponse("Test") I got the error below: SyntaxError: keyword argument repeated: post__contains So, how to run AND operator with filter() without SyntaxError: keyword argument repeated: error in Django? -
Django logger refuse to show full traceback in file message
Currently, i'm setting up logging in Django following the document https://docs.djangoproject.com/en/2.2/topics/logging/ (I'm using Django 2.2 with python3.7) and Django rest framework. Here is my settings.py: # LOGGING LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '{levelname} {asctime} {message}', 'style': '{', }, }, 'handlers': { 'file': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': '/var/log/django_errors.log', 'formatter': 'simple' }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'ERROR', }, }, } Here is my view using django-rest-framework: import logging logger = logging.getLogger(__name__) class Countries(APIView): permission_classes = () authentication_classes = [] def get(self, request): try: ... some API process except Exception as e: import traceback print(traceback.format_exc()) logger.error(traceback.format_exc()) return JsonResponse({'code': 500, 'message': str(e)}, status=500) From the console I can see the print() show the correct full stack traceback. But in the logging file, it doesn't show any traceback. django_errors.log: ERROR 2022-12-22 11:35:21,051 "GET /api/countries HTTP/1.1" 500 72 ERROR 2022-12-22 11:35:21,065 "GET /api/countries HTTP/1.1" 500 72 I also tried logger.exception() the same thing happens, file doesn't log full stack traceback I tried looking online for solutions and tried them but to no prevail, hope someone can help me figure out why expected log to show correct traceback for example like console print(): File … -
How to show the human readable form of choices in DRF
How to show the human readable form of choices in DRF. I have genders choices. I have used serializermethodField() to solve this but it's read only and cannot write. GENDER = ( ('M', "Male"), ("F", "Female"), ("O", "Other") ) so in response I get { "gender": "M", } response I want { "gender": "Male", } -
Django - How to store existing Data in Variable from Database and Update it with another variable
I am facing an issue for few days but could not get the findings to solve it. Suppose, I want to update a record into database using a form and want to keep the existing data into a variable and update it using form and keep the updated data into another variable. Please be inform that i made a solution using session but want another way to solve it. def client_edit(request, client_id): client = Client.objects.get(id=client_id) previous_client_name = client if request.method == 'POST': form = AddClientForm(request.POST, instance=client) if form.is_valid(): client2 = form.save(commit=False) client2.save() context = { 'user': request.user, 'client': client2, 'previous_client':previous_client_name, } return render(request, 'did_app/client_edit.html', context=context) else: return render(request, 'did_app/client_edit.html', {'form': form}) else: return render(request, 'did_app/client_edit.html', {'client': client}) I tried this way but both client and previous_client return the same data. Please suggest. Thanks in advance -
Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty
I've seen other posts about this such as here but I still can't figure out my issue. File structure of relevant files: ba_django_project | docker-compose.prod.yml | |__app | Dockerfile.prod | manage.py | .env.prod | |__ba_django_project | __init__.py | settings.py | wsgi.py docker-compose.prod.yml: version: '3.8' services: web: build: context: ./app dockerfile: Dockerfile.prod image: 370950449536.dkr.ecr.us-east-2.amazonaws.com/ba_django_project:ba_django_project_web command: gunicorn ba_django_project.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles expose: - 8000 env_file: - ./app/.env.prod depends_on: - db db: image: postgres:13.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./app/.env.prod.db nginx: build: ./nginx image: 370950449536.dkr.ecr.us-east-2.amazonaws.com/ba_django_project:ba_django_project_nginx volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles ports: - 1337:80 depends_on: - web volumes: postgres_data: static_volume: media_volume: settings.py: from pathlib import Path from decouple import config import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent STATIC_DIR = os.path.join(BASE_DIR, "static") # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = int(os.environ.get("DEBUG", default=0)) ALLOWED_HOSTS = [ 'ec2-3-20-22-254.us-east-2.compute.amazonaws.com', '0.0.0.0', 'localhost', '127.0.0.1' ] # Application definition INSTALLED_APPS = [ 'crispy_forms', 'users.apps.UsersConfig', 'resume.apps.ResumeConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
django for-loop only displaying the last iteration
I'm building a book recommendation django application. I'm done integrating my machine learning model but the problem is that it gets the data from the csv file i used, not from my database. I have no problem displaying the titles of the recommended books but I would like to let the users view the details page of the said book. With that being said, I need to get the id of the recommended books from my Book model. I'm relatively new to Django so please excuse if my codes are messy. Thank you in advance! This is the excerpt from my views.py def s_detail(request, book_id): #student paper detail cosine_sim = joblib.load('cosine_sim-v5.pkl') #load the ml model data = pd.read_csv('try.csv', sep=',', encoding='utf-8') try: book = Book.objects.get(pk=book_id) fav = True if book.favorites.filter(id=request.user.id).exists(): fav=False def recommendations(book_id,n, cosine_sim = cosine_sim): recommended_books = [] idx = book_id score_series = pd.Series(cosine_sim[idx]).sort_values(ascending = False) top_n_indexes = list(score_series.iloc[1:n+1].index) for i in top_n_indexes: recommended_books.append(list(data.index)[i]) # data.index for book_id column return recommended_books recommend = recommendations(book_id, 3) for i in recommend: new = Book.objects.filter(id=i) #to get the Book id from the model print(new) #just to check if it's working except Book.DoesNotExist: raise Http404("Title does not exist") return render (request, 'books/s_detail.html', {'book':book, 'fav':fav, … -
Application and request contexts in Flask
I really need your help. I am currently doing a project with Flask and I have used the application and request contexts but to this day I have not been able to understand why it is necessary to use them? I don't understand how they work. Every time a request is made to a web app developed with Flask a new instance of the Flask class is created or really how a Flask app works under the hood. It would be very helpful if you help me solve this doubt that is driving me crazy. Thank you very much in advance. I've read everywhere and I still don't understand. -
Python Virtual Environment Help - Django
Error Message I am struggling to install Django to my new project using pipenv, it keeps telling me to run another virtual environment rather than actually installing Django. Please help :( I tried to do what it says to using the other virtual env but it still won't work. -
Django OAuth Authentication
I built an app (Django backend, React frontend) that whenever a client login it will generate JWT authentication. React will store the access token and client can use it to access Django backend database. Then I want to add in social login feature (Google) so I will get back access token from that as well. However, this access token is different from the JWT access token generated before, so I wonder how can I integrate both ways of logging in a user smoothly on both Django and React? For JWT I use djangorestframework-simplejwt For social login I use django-allauth I can run each individual way perfectly on React, but I don't know how to keep both the installations of JWT and allauth in Django settings. -
Django Template changing html attribute based on slug and current request
When I tried to iterate through a list of post titles to create links in a django template the urls never match the requested path (matching the current web page should alter the formatting on the page for that list item). When I try and change things, Django spits out a 404 error which doesn't let me diagnose the problem or it "works" but not as expected. the relevant url patterns: path('<slug:post>', views.blog_post, name='entries') the relevant views function: def blog_post(request, post): try: return render(request, 'blog/post.html', { 'post_title':post, 'post_content':blog_posts[], 'posts':blog_posts.keys }) except: raise Http404() the template: <ul> {% for post in posts %} {% url "blog:entries" "{{post}}" as blog_entry %} <li><a href="/blog/{{post}}" {% if request.path == blog_entry %} class="active"{% endif %}> <span class="item">{{post}}</span> </a></li> {% endfor %} </ul> I suspect the {% url "blog:entries" "{{post}}" as blog_entry %} in the template is not resolving correctly as when I replace the href with {% blog_entry %} it causes a 404 error. I have tried hard coding it in, I have tried different ways of writing the url, I have tried changing the syntax (in case I am doing it incorrectly. I have checked the page source when I have run tests. I …