Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to find out why Heroku cannot find Django templates?
I have tried everything that I've found before and nothing helped me. I deployed my project on Heroku and I get this error. My templates in other apps begin with {% extends 'base/base.html' %} This template is located in a base templates folder(you can see it below) But I got this error: settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], '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', ], }, }, ] import dj_database_url DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media') import django_heroku django_heroku.settings(locals()) I don't know why Heroku cannot find my base template. If I remove extends, it'll render an app template, but without styles. But it'll render and it's the most important. -
У меня есть файл JSON, который я хочу прочитать и сделать с помощью python [closed]
У меня есть файл JSON, который я хочу прочитать и сделать с помощью python. Это все в Django. У меня возникли проблемы с получением данных из timetable.json файла в функции python. Файл json - "timetable.json". def timetable(request): def writer(): group_num = [921732] for n in range(0, len(group_num)): url = f'https://journal.bsuir.by/api/v1/studentGroup/schedule?studentGroup={group_num[n]}' print(url) response = requests.get(url) with open('timetable.json', 'w') as file: for piece in response.iter_content(chunk_size=500000): file.write(piece.decode('utf-8')) def reader(filename): with open(filename, 'r', encoding='utf-8') as file: return json.load(file) return render(request, 'studentapp/index.html') -
Django How to pass variable from a view to a form view
I have two models. One is project and another is todo. The todo model has a foreign key that is the related project's id. I have a template that displays the individual project and generates a link to a form to add a todo list. How do I pass the project id to the todo form? I guess I could simply pass the project id in the URL but is that the best way? My current views.py class CompanyProjectsDetailView(DetailView): model = Project id = Project.objects.only('id') template_name = 'company_accounts/project_detail.html' class TodoCreateView(CreateView): model = ProjectTodo template_name = 'company_accounts/add_todo.html' fields = ['title', 'notes', 'status'] -
raise self.model.DoesNotExist( users.models.Profile.DoesNotExist: Profile matching query does not exist
views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm, Profile def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success( request, "Your account has been created! Your ar now able to login.") return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) # p_form = ProfileUpdateForm( # request.POST, request.FILES, instance=request.user.profile) profile = Profile.objects.get(user = request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance = profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, "Your account has been updated!") return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) profile = Profile.objects.get(user = request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance = profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) signals.py from django.db.models.signals import post_save from django.dispatch import receiver from .models import CustomUser @receiver(post_save, sender=CustomUser) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(email=instance) @receiver(post_save, sender=CustomUser) def save_profile(sender, instance, **kwargs): instance.profile.save() models.py from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.db import models from django.contrib.auth.models import User from PIL import Image from .managers import CustomUserManager from … -
how to pass value from django to payment gateway
i'm trying to pass the email gotten the email field in django in other to pass it to the payment gateway. when i click pay, it redirects me to the modal payment gateway for with an error saying An invalid email passed then when i used inspect, to check the issue, this is what it says flwpbf-inline.js:232 Uncaught TypeError: Cannot set properties of undefined (setting 'opacity') at Object.message_handlers.modalready (flwpbf-inline.js:232) at flwpbf-inline.js:253 message_handlers.modalready @ flwpbf-inline.js:232 (anonymous) @ flwpbf-inline.js:253 the js <script> function makePayment() { const email = document.getElementById('email').value; FlutterwaveCheckout({ public_key: "xxxxxxxxxxxxxxxxxxX", tx_ref: "RX1", amount: '{{cart.get_total_price}}', currency: "USD", country: "NG", payment_options: "", redirect_url: // specified redirect URL "https://callbacks.piedpiper.com/flutterwave.aspx?ismobile=34", meta: { consumer_id: 23, consumer_mac: "92a3-912ba-1192a", }, customer: { email: "{{address.email}}", name: "Flutterwave Developers", }, callback: function (data) { console.log(data); }, onclose: function() { // close modal }, }); } </script> -
Is it possible to filter django Many-To-Many QuerySet fields by checking if they're intersection is not empty?
Doing an exercise about creating a Django service that given a certain job returns the best candidates. Sure it's a Machine Learning problem, and the scoring algorithm here is very simple. Frankly, this is the first time I'm using Django and I'm having some issues to filter out objects from one of the models. This is my model class: from django.db import models class Skill(models.Model): name = models.CharField(max_length=100) def __str__(self) -> str: return f'Skill name: {self.name}' class Candidate(models.Model): title = models.CharField(max_length=100) name = models.CharField(max_length=100, default='') skills = models.ManyToManyField(Skill) def __str__(self) -> str: return f'Name: {self.name}, title: {self.title}' class Job(models.Model): title = models.CharField(max_length=100) skills = models.ManyToManyField(Skill) def __str__(self) -> str: return f'title: {self.title}' Given a job name, I would first like to filter by the skills i.e., go over the given Candidates and filter out the ones that don't have a mutual skill with the given job. In a more mathematical approach - the job_skills_set and the candidate_skills_set intersection is not empty. Something likes this: (I mixed Python syntax) Candidate.objects.filter(len(set.intersection(set(skills), set(job.skills))) > 0) Is there a way I can do that in Django? Tried multiple ways and did not succeed. Thanks in advance! -
TINYMCE doesn't show codes with commands template
I have installed TINYMCE on Django but when I have add (for example) C++ codes in to the code box in out put of the post everything of text OK like(bold H tags etc..) but commands with C++ language shows like the simple text!!! (Without any template or color Separator and ..) help me plz :( -
failed to create LLB definition: docker.io/nginxinc/nginx-unprivileged:1-alphine: not found
Hello I am following this tutorial and i am facing this issue failed to solve with frontend dockerfile.v0: failed to create LLB definition: docker.io/nginxinc/nginx-unprivileged:1-alphine: not found This is my Dockerfile FROM nginxinc/nginx-unprivileged:1-alphine COPY ./default.conf /etc/nginx/conf.d/default.conf COPY ./uwsgi_params /etc/nginx/uwsgi_params USER root RUN mkdir -p /vol/static RUN chmod 755 /vol/static USER nginx -
Catch-22 when trying to create two-way Django relationship
I want to allow my users to be able to have a selection of avatars and (crucially) force every user to have one which will be used as the main one. With that in mind, I've got the following (slightly cut down) models:- class Avatar(models.Model): user = models.ForeignKey(User, related_name="avatars", on_delete=models.CASCADE) image = models.ImageField() class User(AbstractUser): avatar = models.OneToOneField(Avatar, related_name="+", on_delete=models.CASCADE) The problem is, I now can't create a User without first creating an Avatar for that User. But I can't create an Avatar without a User. Having spent ages looking at it, I can't see how I can do this without allowing one of these relationships to be null, which seems wrong somehow. Is there another way to do it? -
OperationalError, Error 111 connecting to 127.0.0.1:6379. Connection refused. After deploying in heroku
I am getting the below error after I deployed my website on heroku. Error 111 connecting to 127.0.0.1:6379. Connection refused. Request Method: POST Request URL: https://website.herokuapp.com/account/register Django Version: 3.2.8 Exception Type: OperationalError Exception Value: Error 111 connecting to 127.0.0.1:6379. Connection refused. Exception Location: /app/.heroku/python/lib/python3.8/site-packages/kombu/connection.py, line 451, in _reraise_as_library_errors Python Executable: /app/.heroku/python/bin/python Python Version: 3.8.12 Python Path: ['/app', '/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python38.zip', '/app/.heroku/python/lib/python3.8', '/app/.heroku/python/lib/python3.8/lib-dynload', '/app/.heroku/python/lib/python3.8/site-packages'] Server time: Sat, 11 Dec 2021 21:17:12 +0530 So basically my website has to send email regarding otp, after registration and also some contract related emails. These email are neccessary to be sent hence can't be avoided. I posted a question earlier here regardig how to minimize the time that sending emails takes so that the user doesn't have to wait the entire time. I was suggested to use asynchronous code for this. So i decided to use celery for this. I followed the youtube video that taught how to use it. Now after I pushed the code in the website I am getting this error. I am beginner andd have no idea how to rectify it. Please suggest me what shoul I do. Below are the details and configurations. settings.py CELERY_BROKER_URL = 'redis://127.0.0.1:6379' CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379' … -
django view creates new object instead of replacing it
I wrote a function like this which takes care of user payment information: def PaymentView(request): template = loader.get_template('reg/payment.html') payment = PaymentInfo.objects.get(user=request.user) if request.method == 'GET': if payment and payment.isPaid: return redirect('/dashboard') return HttpResponse(template.render(request=request)) if request.POST.get('proceed'): return redirect('/dashboard') else: payment = PaymentInfo(user=request.user) price = 252000 order_id = jdatetime.datetime.now().isoformat().replace(":", "").replace(".", "").replace("-", "") hyperlink = proceed_to_payment(payment, order_id, price) return redirect(hyperlink) and this is the object that it creates for users every time its called: class PaymentInfo(models.Model): id = models.AutoField(primary_key=True) user = ForeignKey(User, on_delete=models.CASCADE) isPaid = BooleanField(default=False) payment_number = CharField(max_length=32, null=True, default=None) order_id = CharField(max_length=32, null=True, default=None) track_id = CharField(max_length=50, null=True, default=None) card_no = CharField(max_length=16, null=True, default=None) hash_card_no = CharField(max_length=64, null=True, default=None) payment_date = DateField(auto_now_add=True, null=True) payment_verification_date = DateField(auto_now_add=True, null=True) it works just fine but imagine if a user clicks a certain button to get redirected to the payment page and cancel that payment and repeat this one more time. now the user has two seperate paymentInfo object. I want the first one to be updated with new info. what statement should I add to the views functiona? something like if payment.exists(), delete it or replace it some how!? -
Trying to return DB Array object in Django to a View
I have something sort of working. I am very new to Django and Python. I have the following view in my api folder from re import S from django.shortcuts import render from rest_framework import generics, status from .serializers import CourseSerializer, CreateCourseSerializer from .models import Course from rest_framework.views import APIView from rest_framework.response import Response import logging from django.core import serializers logging.basicConfig(level=logging.WARNING) logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # Create your views here. class CourseView(generics.ListAPIView): queryset = Course.objects.all() serializer_class = CourseSerializer SomeModel_json = serializers.serialize("json", Course.objects.all()) logger.debug(SomeModel_json) def get(self, request, format=None): return Response(self.SomeModel_json, status=status.HTTP_201_CREATED) class CreateCourseView(APIView): serializer_class = CreateCourseSerializer def post(self, request, format=None): if not self.request.session.exists(self.request.session.session_key): self.request.session.create() serializer = self.serializer_class(data=request.data) if serializer.is_valid(): course_title = serializer.data.get('course_title') course_topic = serializer.data.get('course_topic') course_topic_about = serializer.data.get('course_topic_about') course_question = serializer.data.get('course_question') course_answer = serializer.data.get('course_answer') course = Course(course_title=course_title, course_topic=course_topic, course_topic_about=course_topic_about, course_question=course_question, course_answer=course_answer) course.save() return Response(CourseSerializer(course).data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and have the following serializers.py in my api folder from rest_framework import serializers from .models import Course class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = ( 'id', 'course_title', 'course_topic', 'course_topic_about', 'course_question', 'course_answer', 'created_at', 'updated_at') class CreateCourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = ( 'course_title', 'course_topic', 'course_topic_about', 'course_question', 'course_answer') Have the follow models.py in api folder from django.db import models # Create your … -
Does transaction.atomic roll back increments to a pk sequence
I'm using Django 2.2 and my question is does transaction atomic roll back increments to a pk sequence? Below is the background bug I wrote up that led me to this issue I'm facing a really weird issue that I can't figure out and I'm hoping someone has faced a similar issue. An insert using the django ORM .create() function is returning django.db.utils.IntegrityError: duplicate key value violates unique constraint "my_table_pkey" DETAIL: Key (id)=(5795) already exists. Fine. But then I look at the table and no record with id=5795 exists! SELECT * from my_table where id=5795; shows (0 rows) A look at the sequence my_table_id_seq shows that it has nonetheless incremented to show last_value = 5795 as if the above record was inserted. Moreover the issue does not always occur. A successful insert with different data is inserted at id=5796. (I tried reset the pk sequence but that didn't do anything, since it doesnt seem to be the problem anyway) I'm quite stumped by this and it has caused us a lot of issues on one specific table. Finally I realize the call is wrapped in transaction.atomic and that a particular scenario may be causing a double insert with the same … -
error mutation grapiql django many-to-many set is prohibited. Use films.set() instead
Tengo los siguientes modelos: ###################################################### class People(TimeStampedModel, SimpleNameModel): """ Personajes del universo de Star Wars """ MALE = 'male' FEMALE = 'female' HERMAPHRODITE = 'hermaphrodite' NA = 'n/a' GENDER = ( (MALE, 'Male'), (FEMALE, 'Female'), (HERMAPHRODITE, 'Hermaphrodite'), (NA, 'N/A'), ) HAIR_COLOR_CHOICES = ( ('BLACK', 'black'), ('BROWN', 'brown'), ('BLONDE', 'blonde'), ('RED', 'red'), ('WHITE', 'white'), ('BALD', 'bald'), ) EYE_COLOR_CHOICES = ( ('BLACK', 'black'), ('BROWN', 'brown'), ('YELLOW', 'yellow'), ('RED', 'red'), ('GREEN', 'green'), ('PURPLE', 'purple'), ('UNKNOWN', 'unknown'), ) height = models.CharField(max_length=16, blank=True) mass = models.CharField(max_length=16, blank=True) # hair_color = models.CharField(max_length=32, blank=True) hair_color = models.CharField(max_length=32, choices=HAIR_COLOR_CHOICES, blank=True) skin_color = models.CharField(max_length=32, blank=True) # eye_color = models.CharField(max_length=32, blank=True) eye_color = models.CharField(max_length=32, choices=EYE_COLOR_CHOICES, blank=True) birth_year = models.CharField(max_length=16, blank=True) gender = models.CharField(max_length=64, choices=GENDER) home_world = models.ForeignKey(Planet, on_delete=models.CASCADE, related_name='inhabitants') class Meta: db_table = 'people' verbose_name_plural = 'people' ###################################################### class Film(TimeStampedModel): title = models.CharField(max_length=100) episode_id = models.PositiveSmallIntegerField() # TODO: Agregar choices opening_crawl = models.TextField(max_length=1000) release_date = models.DateField() director = models.ForeignKey(Director, on_delete=models.CASCADE, related_name='films') producer = models.ManyToManyField(Producer, related_name='films') characters = models.ManyToManyField(People, related_name='films', blank=True) planets = models.ManyToManyField(Planet, related_name='films', blank=True) class Meta: db_table = 'film' def __str__(self): return self.title ###################### class People_film(People): films = models.ManyToManyField(Film, related_name='film', blank=True) Estoy haciendo una mutacion en graphiql de creación que al agregar people tambien pueda agregar films en las … -
Django is crashing again and again
My django server is crashing sometimes on the production, it was also crashing in the test environment but it was not an issue, crash on prod is making business loss. The crash I am getting is quite difficult to trace and difficult to understand(atleast for me) I am attaching few screenshots for your reference. What could be the issue? -
Django search returning all objects not the specified ones
I'm currently trying to achieve a search that shows only the ads that contain the text in title, description or tags. It seems like everything should work properly, but the search returns all of the objects.(site has the /?search=foo ending after the button click) my List View class AdListView(ListView): model = Ad def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) favorites = list() if self.request.user.is_authenticated: # rows = [{'id': 2}, {'id': 4} ... ] (A list of rows) rows = self.request.user.favorite_ads.values('id') # favorites = [2, 4, ...] using list comprehension favorites = [ row['id'] for row in rows ] context['favorites'] = favorites strval = self.request.GET.get("search", False) if strval: # Simple title-only search # __icontains for case-insensitive search query = Q(title__icontains=strval) query.add(Q(text__icontains=strval), Q.OR) query.add(Q(tags__name__in=[strval]), Q.OR) objects = Ad.objects.filter(query).select_related().distinct().order_by('-updated_at')[:10] else : objects = Ad.objects.all().order_by('-updated_at')[:10] # Augment the post_list for obj in objects: obj.natural_updated = naturaltime(obj.updated_at) context['search'] = strval return context part of my template: <div style="float:right"> <!-- https://www.w3schools.com/howto/howto_css_search_button.asp --> <form> <input type="text" placeholder="Search.." name="search" {% if search %} value="{{ search }}" {% endif %} > <button type="submit"><i class="fa fa-search"></i></button> <a href="{% url 'ads:all' %}"><i class="fa fa-undo"></i></a> </form> </div> {% if ad_list %} <ul> {% for ad in ad_list %} <li> <a href="{% url 'ads:ad_detail' … -
Could not import 'djangorestframework_camel_case.render.CamelCaseJSONRenderer' for API setting 'DEFAULT_RENDERER_CLASSES'
I am working on django (DRF) application. And i am using djangorestframework-camel-case==1.2.0 # https://pypi.org/project/djangorestframework-camel-case/ I have the following error: ImportError: Could not import 'djangorestframework_camel_case.render.CamelCaseJSONRenderer' for API setting 'DEFAULT_RENDERER_CLASSES'. ImportError: cannot import name 'force_text' from 'django.utils.encoding' (/usr/local/lib/python3.9/site-packages/django/utils/encoding.py). Full error text https://pastebin.com/DKDSv8Q2 Also all my libs version: https://pastebin.com/ucGte32B How can I fix this error? settings.py -- full code (https://pastebin.com/2VbKqPwM) REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'djangorestframework_camel_case.render.CamelCaseJSONRenderer', 'djangorestframework_camel_case.render.CamelCaseBrowsableAPIRenderer', # Any other renders ), 'DEFAULT_PARSER_CLASSES': ( # If you use MultiPartFormParser or FormParser, we also have a camel case version 'djangorestframework_camel_case.parser.CamelCaseFormParser', 'djangorestframework_camel_case.parser.CamelCaseMultiPartParser', 'djangorestframework_camel_case.parser.CamelCaseJSONParser', # Any other parsers ), } -
how to install postgres extension with docker on django project
I want to add full text search to my django project and I used postgresql and docker,so want to add extension pg_trgm to postgresql for trigram similarity search. how shuld I install this extension with dockerfile? In shared my repository link. FROM python:3.8.10-alpine WORKDIR /Blog/ ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./entrypoint.sh . RUN sed -i 's/\r$//g' ./entrypoint.sh RUN chmod +x ./entrypoint.sh COPY . . ENTRYPOINT ["./entrypoint.sh"] docker-compose services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/Blog ports: - 8000:8000 env_file: - ./.env.dev depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=helo - POSTGRES_PASSWORD=helo - POSTGRES_DB=helo volumes:`enter code here` postgres_data: -
WSGI application Error caused by SocialAuthExceptionMiddleware
I was trying python-social-auth and when I added the middleware MIDDLEWARE = [ 'social_django.middleware.SocialAuthExceptionMiddleware' ... ] I get this error raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: WSGI application 'djangoauthtest.wsgi.application' could not be loaded; Error importing module. and I was looking over at other question to look for an answer and so far I've tried to install whitenoise and add whitenoise middleware reinstall python-social-app use python-social-app 4.0.0 change WSGI_APPLICATION = 'myapp.wsgi.application' to WSGI_APPLICATION = 'wsgi.application' and nothing worked so far. I'll be thankfull for any kind of advice regarding this! -
Unable to run Django with Postgress in Docker
I wanted to set up a Django app with PostgresDb inside docker containers so that's why I wanted to setup docker-compose but when I execute my code docker, django and db all are working fine and I also developed some API's and they were also working fine as expected but unfortunately, suddenly I'm blocked with these errors: pgdb_1 | pgdb_1 | 2021-12-11 15:05:38.674 UTC [1] LOG: starting PostgreSQL 14.1 (Debian 14.1-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit pgdb_1 | 2021-12-11 15:05:38.674 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 pgdb_1 | 2021-12-11 15:05:38.674 UTC [1] LOG: listening on IPv6 address "::", port 5432 pgdb_1 | 2021-12-11 15:05:38.697 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" pgdb_1 | 2021-12-11 15:05:38.729 UTC [27] LOG: database system was shut down at 2021-12-11 15:03:09 UTC pgdb_1 | 2021-12-11 15:05:38.761 UTC [1] LOG: database system is ready to accept connections django_1 | Watching for file changes with StatReloader django_1 | Performing system checks... django_1 | django_1 | System check identified no issues (0 silenced). pgdb_1 | 2021-12-11 15:05:41.390 UTC [34] FATAL: password authentication failed for user "postgres" pgdb_1 | 2021-12-11 15:05:41.390 UTC [34] DETAIL: Role "postgres" does not exist. … -
How can use slug for all urls in django without anything before or after?
I want all djaango urls use slug field without any parameter before or after, by default just one url can use this metod ex: path('<slug:slug>', Article.as_View(), name="articledetail"), path('<slug:slug>', Category.as_View(), name="category"), path('<slug:slug>', Product.as_View(), name="productdetail"), mysite .com/articleslug mysite .com/categoryslug mysite .com/productslug How can I do it? Thank you -
connection error while using requests module in my django project
I was trying to create a django project. Everything was fine until I did a get request using requests.get() in python in my views.py Following is what my views.py have from django.shortcuts import render import re, requests def codify_data(data_raw): data = data_raw.json()['data'] if language == 'web': html_cd = data['sourceCode'] css_cd = data['cssCode'] js_cd = data['jsCode'] def home_page(request): return render(request,'home/index.html') def code(request): link = request.GET.get('link', 'https://code.sololearn.com/c5I5H9T7viyb/?ref=app') result = re.search(r'https://code.sololearn.com/(.*)/?ref=app',link).group(1)[0:-2] data_raw = requests.get('https://api2.sololearn.com/v2/codeplayground/usercodes/'+result) codify_data(data_raw)``` [Error shown in image][1] [1]: https://i.stack.imgur.com/2Uao9.jpg -
get False Booleans one by one from the list
I am building a blog app in which, I have created about 10+ Booleans and I am trying to track Booleans according to the list. I mean, Suppose, there are 5 Booleans and all are in the sequence, like `[boolean_1, boolean_2, boolean_3, boolean_4, boolean_5] and they are all false. then I am trying to get first Boolean on a page until (turning True a Boolean can take days) it is True and then boolean_2 will be seen on page boolean_1 will be removed after True. then I am trying to get the Booleans which are False one by one But I have no idea how can I filter Booleans which are False one by one. models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) boolean_1 = models.BooleanField(default=False) boolean_2 = models.BooleanField(default=False) boolean_3 = models.BooleanField(default=False) boolean_4 = models.BooleanField(default=False) boolean_5 = models.BooleanField(default=False) boolean_6 = models.BooleanField(default=False) views.py def page(request): listOfBooleans = [request.user.profile.boolean_1, request.user.profile.boolean_2, request.user.profile.boolean_3] get_first_boolean = listOfBooleans(0) context = {'listOfBooleans':listOfBooleans} return render(request, 'page.html', context) I have tried by using compress :- from itertools import compress list_num = [1, 2, 3, 4] profile_booleans = [request.user.profile.boolean_1, request.user.profile.boolean_2, request.user.profile.boolean_3] list(compress(list_num, profile_booleans)) But this :- It is returning True instead of False I cannot access first from it, if I … -
Accessing query parameter in serializer in Django
I just wanted to access a query parameter in serializer like class MySerializer(serializers.ModelSerializer): isHighlight = serializers.SerializerMethodField() def get_isHighlight(self, obj): return self.context['request'].query_params['page'] But its showing Django Version: 3.2.7 Exception Type: KeyError Exception Value: 'request' Thanks in advance. -
Getting value from View to Serializer in Django
I am not sure what I am doing wrong, I tried to follow a few solution. class MyViewSet(viewsets.ModelViewSet): filterset_class = IngredientFilter def get_serializer_context(self): context = super().get_serializer_context() context['test'] = "something" return context In my Serializer, class MySerializer(BaseSerializer): isHighlight = serializers.SerializerMethodField() def get_isHighlight(self, obj): return self.context['test'] I am getting this error, Django Version: 3.2.7 Exception Type: KeyError Exception Value: 'test' Any suggestions?