Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to solve origin 'http://127.0.0.1:9000' has been blocked by CORS policy
Access to font at 'https://fra1.digitaloceanspaces.com/ewan-space/ewan/static/admin/fonts/Roboto-Light-webfont.woff' from origin 'http://127.0.0.1:9000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. i see tihis erorr in django admin when i collect my static in digitalochenspace , and it's work fine in when collect static in localhost, this is my code settings #installed apps "corsheaders", MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.middleware.security.SecurityMiddleware",] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL=True django 3.2 python 3.8 how to solve this problem ? -
How to cycle through images on Django website
I have built a photo gallery and I when an image is opened I would like to add to buttons ( Previous & Next) Which will cycle through my images based on their id/pk. Models.py class PostImage(models.Model): image = models.ImageField(null=False, blank=False, upload_to="images", default="default.png") image_title = models.CharField(max_length=100, null=False, blank=False, default="") def __str__(self): return self.image_title class Meta: verbose_name_plural = 'PostImage' Views.py def galleryPage(request): images = PostImage.objects.all() context = {'images':images} return render(request, 'gallery.html', context) def viewImage(request, pk): photo = PostImage.objects.get(id=pk) return render(request, 'viewimage.html', {'photo': photo}) HTML <div class="image-container"> <div class="image-post"> <a href="{% url 'gallery' %}" ><img class="photo-img" src="{{photo.image.url}}" /></a> <h2 class="photo-title">{{photo.image_title}}</h2> <p class="contact"> Interested in purchasing this as a print? Contact me for more information regarding price and sizes. </p> <a href="{% url 'contact' %}" class="btn btn-secondary" type="button" >Contact</a > </div> </div> </body> </html> -
why am i getting the error ManyRelatedManager' object has no attribute 'publications' in django rest framework
i have a many to many relationship between a model called topic and publication , when i'm trying yo serializing data related to the publication model i get the error below enter image description here here is my model : class Publication(models.Model): title = models.CharField(max_length=30) content = models.CharField(max_length=1000) image = models.ImageField(upload_to='blog_images/') class Topic(models.Model) : name = models.CharField(max_length=40) publications = models.ManyToManyField( Publication, related_name='topic' ) def __str__(self) : return self.name here are my serializers : class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username' , 'profile_pic'] class CommentSerializer(serializers.ModelSerializer): sender =UserSerializer(many=False) class Meta : model = Comment fields = ['sender'] class TopicSerializer(serializers.ModelSerializer): class Meta : model = Topic fields = '__all__' class PublicationSerializer(serializers.ModelSerializer): topic = TopicSerializer(many=False) publication_comments = CommentSerializer(many=False) class Meta : model = Publication fields = '__all__' and here are my views : @decorators.api_view(['GET']) def get_publications(request,pk=None): if pk : instance = Publication.objects.get(pk=pk) return response.Response( PublicationSerializer(instance , many=None).data) topic = request.query_params.get('topic') if request.query_params.get('topic') else '' title = request.query_params.get('title') if request.query_params.get('title') else '' qs = Publication.objects.all() data = PublicationSerializer(qs, many =True).data return response.Response(data , status=200) i tried to return a filtered queryset -
Edit blog post on Django but not make it visible until finished
The question is basically in title. I was wondering if there is a way for a user to edit a blog post in Django admin but not make it visible to the public until finalized? -
Converting base64 to video
i posted file by api in js of type string as shown in picture so i need to convert str base64 to video file when converting in python the generated file as shown in screenshot its lieke text the lesson_vid = request.POST.get('lesson_video') print(type(lesson_vid)) output is : <class 'str'> the question is how to save mp4 video from str base64 -
How to load image from Django content field in Next.js?
Hello everyone and Happy New Year! Please tell me, I have data coming from the Django API, there is a TextField field, it uses the markdown editor. Loading the text, I get everything except the image. The reason it won't load is the wrong link because it looks like this: media/uploads/image.jpg Next.js, in turn, tries to add an address to it, did this: localhost:3000/media/uploads/image.jpg, but localhost:8000/media/uploads/image.jpg will be correct, how to make an absolute link? There are no problems with the preview, everything can be configured there. -
Django - create code blocks in html templates
I would like to create a web page that will display data I have in a table inside a code block just the way it is here, even with a copy function. I can already display the data on the page, I just like to have it formatted in a pretty box, maybe even with syntax highlights, I looked at Pygments but I can't get it to work. Below is a sample code block that I would like to re-create in my Django app. Please don't pay attention to the actual code, this is only a sample. I would appreciate if you could please let me know in detail how to implement this. # Python Program to find the area of triangle a = 5 b = 6 c = 7 # Uncomment below to take inputs from the user # a = float(input('Enter first side: ')) # b = float(input('Enter second side: ')) # c = float(input('Enter third side: ')) # calculate the semi-perimeter s = (a + b + c) / 2 # calculate the area area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 print('The area of the triangle is %0.2f' %area) -
DRY: how to get a basic React/Apollo web app and python GraphQL backend API going with minimal duplication?
I'm an experienced SWE but sort of new to modern web development. I'd like to build a demo/prototype website for a startup idea with minimal time. I'd like to have the frontend tied to a backend DB store up front so it's fully functional. I'd like advice on the best stack to use. I'd like a python backend, and I'm planning on React for the frontend, with GraphQL (unless this is a dumb idea for a prototype... I'd like to learn about it though.) I feel like there is a ton of redundancy in terms of data object models. I can make a GraphQL schema (I was thinking of using ariadne + FastAPI) but then I still need to build DB tables, or create an object model e.g. in Django. And then of course there is all the React code to make forms to edit stuff. My app will require a significant amount of data entry on the website to set up users and lots of metadata. I built a ton of forms etc in React, backed by Apollo client. Any suggestions -- am I on the right track or is there a quicker way to a prototype? Are there … -
Django forms - limiting options from fields based on the answer of another field
I have a Django form the receives entries from the users with information on a surgical procedure. Each Procedure will have only one (surgical) Technique and only one Diagnosis. Each Technique may be related to a limited number of Diagnosis, and each Diagnosis may be used on different Techniques. I want to limit which Diagnosis appear of the form based on which Technique the user selected previously on the form. I tried using smart_selects ChainedManyToMany field with relative success, but it enable multiple Diagnosis to be selected, I only want to have one. I`m also using DAL for autocompleting the Technique (over 1,6k options) as the user types. My models: # The "Technique" model class Sigtap(models.Model): codigo = models.CharField(max_length=10) descricao = models.CharField(max_length=175, default='') # The "Diagnosis" model class Cid10(models.Model): codigo = models.CharField(max_length=4) descricao = models.CharField(max_length=270, default='') sigtap_compativel = models.ManyToManyField(Sigtap, blank=True) # The "Surgical Procedure" model class Cirurgia(models.Model): paciente = models.PositiveIntegerField(verbose_name='Número do prontuário') data = models.DateField(verbose_name='Data de realização') procedimento = models.ForeignKey(Sigtap, on_delete=models.CASCADE, verbose_name='Código do procedimento (SIGTAP)') cid = ChainedManyToManyField( Cid10, horizontal=True, chained_field='procedimento', chained_model_field='sigtap_compativel', auto_choose=True, verbose_name='CID-10') My forms: class CirurgiaModelForm(forms.ModelForm): class Meta: model = Cirurgia fields = ['paciente', 'data', 'procedimento', 'cid'] widgets = { 'procedimento': autocomplete.ModelSelect2(url='sigtap-autocomplete'), } Maybe a better approach to … -
Not getting the data on request from ajax on Django API
I've this button, on click i'm calling a function that would disappear once clicked and would send the data to django api. <button type="button" class="btn btn-success" id="Approved" onclick="approveFunction()">Approve</button> <script> var button1 = document.getElementById("Approved"); function approveFunction() { button1.style.display = "none"; console.log('hello') approved = 'Approved' $(document).ready(function () { $.ajax({ url: "/stitch/admin/approvals/detail/status", dataType: "html", data: { 'Approved': approved }, success: function (response) { console.log('hiiiiiiiiiii') } }); }); } </script> This is the url and api i've created(don't worry about stitch in the ajax url, it's supposed to be like that) url(r"^admin/approvals/detail/$", ApprovalDetail.as_view()), class ApprovalDetail(TemplateView): template_name = "admin/approval_detail.html" def get(self, request, *args, **kwargs): id = request.GET.get('id') approval_detail = Approval.objects.filter(id=id) approval_status = request.GET.get('Approved') rejection_status = request.GET.get('Rejected') if approval_status: print('Approved') # Approval.objects.filter().update(status='Approved') if rejection_status: print ('Rejected') # Approval.objects.filter().update(status='Rejected') if approval_status is None and rejection_status is None: print('Unapproved') return render(request, self.template_name,{'approval_detail':approval_detail}) Btw this is the same api i'm using to render the html page in which i'm showing the button and want to send the ajax data to. I'm doubting if even this is possible. Tried to send the data to the api, but not getting it. -
Anyway to join this query and make one query in django filter
post_search_comments= PostInLanguages.objects.filter(comment_data__is_post_comment=True).annotate(c=Count('comment_data', distinct=True)).filter(c__gte=0) post_search_likes = PostInLanguages.objects.annotate(l=Count('like_model', distinct=True)).filter(l__gte = 1) I need to make one query from these above queries. Needed post objects which has minimum likes and minimum comments. For now im using intersection intersection = post_search_comments & post_search_likes print(intersection) paginator = CustomPageNumberPagination() page = paginator.paginate_queryset(post_search_comments, request) serializer = PostInLanguagesSerializer(page, many=True) response = paginator.get_paginated_response(serializer.data) return response -
VsCode can't resolve Django Imports
I just woke up and shockingly VsCode can't resolve imports in all my Django projects. Some were using venv and some pipenv, but they have all stopped resolving imports. I have tried the answers which all seem to say I should select the python.exe from the Script folder of the respective projects virtual environment`. But as you can see below, that ain't working. Any pointers? -
When trying to update an instance of related models I get the Ids on the template instead of the names, using {{form}}
URLS.py urlpatterns = [ path('stock/update/<int:pk>/', views.StockUpdateView, name='stock-update'), VIEWS.py def StockUpdateView(request, pk): stock = Stock.objects.get(id=pk) form = StockForm(instance=stock) if request.method == 'POST': form = StockForm(request.POST, instance=stock) if form.is_valid(): form.save() return redirect('/inventory/stock') context = {"form": form} return render(request, 'inventory/update-stock.html', context) TEMPLATE.html <form action="" method="POST" class="row g-3"> <div class="col-auto"> <h6>Stock update form:</h6> {% csrf_token %} {% for field in form %} <div class="form-control"> {{field}} </div> {% endfor %} I have changed from using the {{ form }} tag to looping over the fields trying to get the name of the related table instead of the IDs. -
Django 3.2 how to add model decimal fields together inside model
I am trying to add all the decimalfields numbers together to form a sum inside the model this is my model class Ataskaita(models.Model): class Meta: verbose_name_plural = 'Ataskaitos' bendrija = models.ForeignKey(Bendrija, on_delete=models.CASCADE, related_name="ataskaita") atlyginimas = models.DecimalField(max_digits=10, decimal_places=2, null=False, default=0) sodra = models.DecimalField(max_digits=10, decimal_places=2, null=False, default=0) vmi = models.DecimalField(max_digits=10, decimal_places=2, null=False, default=0) pvm_saskaitos_kvitas = models.DecimalField(max_digits=10, decimal_places=2, null=False, default=0) bankines_operacijos = models.DecimalField(max_digits=10, decimal_places=2, null=False, default=0) sum = models.DecimalField(max_digits=10, decimal_places=2) and I want to add all the fields (atlyginimas, sodra, vmi, pvm_saskaitos_kvitas, bankines_operacijos) together so I have all of their total I looked around stackoverflow and I think the only way to do it is to create a method, but I already tried it, and it wouldn't work as intended -
Adding a linebreak into a django form
beginner here! i've created a Django form and it works but all the fields are in the same line when i open the page, could someone help please? that's my code, it works but they all stay in the same line class NewListingForm(forms.Form): title = forms.CharField(label="Title", max_length=64) description = forms.CharField(label="Description", max_length=200) -
Django module installed in virtual environment but i get ModuleNotFoundError
I'm trying to use a module called reportlab, which i have installed through pip, i did check with pip list inside my environment and it does appear, but when i try to run my server i'm getting the module not found error. i tried to reinstall the package but same issue occurs, any suggestions? -
Why is django only reading admin url and not other url?
Why django is reading only admin url and not others?Even if I delete the admin url I can still browse it -
why does the child template get overriden by the templates in extends when using the django framework
for login.html this is what I have {% block content %} <h2>Tryin to Log In</h2> {% endblock content %}``` for base.html this is what I have {% block content %} <h2>base template</h2> {% endblock %} My problem is that the base.html overwrites the templates in login.html I have looked into the settings.py and this is what I have TEMPLATES = [ { ... 'DIRS': [BASE_DIR / "templates"], ... }, ] -
Got an error when try to use Social Auth backends fir dj-rest-auth app DRF
I wanted to add social media auth endpoints from dj-rest-auth third-party app. I did everything from the dj-rest-auth documentation. I am getting this strange error, though: File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/views/generic/base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/utils/decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/views/decorators/debug.py", line 92, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/views.py", line 53, in dispatch return super().dispatch(*args, **kwargs) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/views.py", line 130, in post self.serializer.is_valid(raise_exception=True) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/rest_framework/serializers.py", line 227, in is_valid self._validated_data = self.run_validation(self.initial_data) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/rest_framework/serializers.py", line 429, in run_validation value = self.validate(value) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/serializers.py", line 121, in validate user = self.get_auth_user(username, email, password) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/serializers.py", line 96, in get_auth_user return self.get_auth_user_using_allauth(username, email, password) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/serializers.py", line 62, in get_auth_user_using_allauth return self._validate_email(email, password) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/serializers.py", line 30, in _validate_email user = self.authenticate(email=email, password=password) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/serializers.py", line 26, in authenticate return … -
what is the correct way to automatically set a ForeignKey(User, on_delete=models.CASCADE) to the current loging in user
i need to auto set the model field "auther = models.ForeignKey(User, on_delete=models.CASCADE)" to the current authenticated user so that any posts created are automatically assigned to the user that created them... currently with my code the user has to select their own username in a drop down list. i would like to remove this and have that field auto filled out in the back end to prevent users picking the wrong username. here is my models.py class Task(models.Model): SELECT = 'None' GREEN = 'Green' AMBER = 'Amber' RED = 'Red' PRIORITY = [(SELECT, 'Select Priority'),(GREEN, 'Green'), (AMBER, 'Amber'),(RED, 'Red'),] auther = models.ForeignKey(User, on_delete=models.CASCADE,) priority = models.CharField(max_length=5,choices=PRIORITY,default=SELECT,) date = models.DateField(auto_now_add=True) title = models.CharField(max_length=255) description = models.TextField() def __str__(self): return self.title + ' | ' + str(self.auther) def get_absolute_url(self): return reverse('task') def is_upperclass(self): return self.PRIORITY in {self.GREEN, self.AMBER} here is my views.py class TaskView(ListView): model = Task template_name = 'tasks.html' ordering = ['-id'] class AddTaskView(SuccessMessageMixin,CreateView): model = Task template_name = 'add_task.html' fields = ['priority','title','description'] success_message = " Task was created successfully" class UpdateTaskView(SuccessMessageMixin, UpdateView): model = Task template_name = 'update_task.html' fields = ['priority','title','description'] success_message = " Task was updated successfully" class DeleteTaskView(SuccessMessageMixin, DeleteView): model = Task template_name = 'delete_task.html' success_url = '/task/' … -
Auto conplete using js and json data
Hey I have a django website and Im trying to write an autocomplete searchfield using js Im returning a json response in django view in this format: [{'label':"Spider man no way home", 'link':"/movies/spider-man-no-way-home", 'img':"imgae url"},{...},{...},...] Im receiving the name of the movie from input(Search box) and writing query to db using a GET request: /search/movie?="the movie name" in script file ` $(function() { $("#search").autocomplete({ source: //"autocomplete.php", [ {id:"Wikipedia", value:"Wikipedia", label:"Wikipedia", uri: 'https://www.wikipedia.org/', img:"https://upload.wikimedia.org/wikipedia/commons/6/63/Wikipedia-logo.png"}, {id:"Google", value:"Google", label:"Google", uri: 'https://www.google.com', img:"https://www.buro210.nl/wp-content/uploads/2017/05/google-logo-icon-PNG-Transparent-Background-e1495781274381.png"} ], minLength: 1, select: function(event, ui) { //console.log(ui.item); //var url = ui.item.uri; //if(url !== '') { location.href = ui.item.uri; //} }, html: true, open: function(event, ui) { $(".ui-autocomplete").css("z-index", 1000); } }) .autocomplete( "instance" )._renderItem = function( ul, item ) { return $( "<li><div><img src='"+item.img+"'><span>"+item.value+"</span></a></div></li>" ).appendTo( ul ); }; }); ` I found this code in this page It works fine, but I wanna make it dynamic by an event listener that fetchs data from db this is how I fetch data: ` let all_data = []; searchinput.addEventListener("input", (e) => { fetch('/search/?movie=' + e.target.value) .then(response => response.json()) .then(data => { all_data = data }) }) ` if I pass the all_data array to source It's empty because the inpur is empty and … -
: could not translate host name "DB" to address: Temporary failure in name resolution
I was using docker for a project, and tried creating a second container for my postgresql database, when i run the command docker-compose up -d, the command line shows something like this:- - Container postgresql-DB-1 Started 1.4s - Container postgresql-web-1 Running And when I run docker-compose logs for the first time, the command line shows that everything is fine. However, when I run it a second time, it shows the error mentioned in the question title, and after that it keeps showing that error when I try to do anything with the docker commands Here's my Dockerfile:- # Pull base image FROM python:3.11.1 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ Here's my docker-compose.yml file:- version: '3.11.1' services: web: build: . tty: true command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - DB DB: image: postgres:11 Here's my settings.py file:- from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for … -
Django CBV: How to subclass scattered parts of code from the parent class
I'm trying to jump from the world of FBV to CBV, but running into an immediate problem...which i'm sure must be pretty common and solvable and I just don't know how... I'm inheriting the general View class into my parent class, which has all the code from my FBV. I created a sub-class which inherits from the parent, and the page still loads fine. Good initial start! But now, I want to utilize the inheritance feature of CBV. I want to move (or override) multiple unique pieces in the parent to the child. I just want to leave the "common" code in the parent, and then all unique things to the child (and eventually other child classes). For example...I have about 1,000 lines of code in parent. And I will need to move / override probably 1/3 of it into child classes. But that 1/3 is scattered from the beginning to the end of the parent. It's not like the parent will be the complete first 1/2 of the code, and then the child classes will be last 1/2. Which presents 2 problems... A) For example, when I want to override a particular section of code in the child, some … -
django.db.utils.IntegrityError: FOREIGN KEY constraint failed - Django
First, I know there are a lot of answers regarding this error, but I can't understand why this is erroring out in my case. I am learning Django and any help would be highly appreciated. I have a Ticket model with ForeignKey reference to Category, Type & GHDUser as below models.py ` # from accounts/models.py class GHDUser(AbstractBaseUser, PermissionsMixin): emp_id = models.IntegerField(primary_key=True) email = models.EmailField(_('email address'),unique=True) username = models.CharField(max_length=150, unique=True) # from ticket/models.py class Category(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' def __str__(self): return self.name class Type(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=100) class Meta: verbose_name = 'Type' verbose_name_plural = 'Types' def __str__(self): return self.name class Ticket(models.Model): status_options = ( ('open', 'Open'), ('pending', 'Pending'), ('closed', 'Closed') ) priority_options = ( ('high','High'), ('medium','Medium'), ('low','Low') ) ticket_no = models.CharField(max_length=10, blank=True) title = models.CharField(max_length=100) description = models.TextField(max_length=1000) category = models.ForeignKey(Category, on_delete=models.PROTECT, default=1) type = models.ForeignKey(Type, on_delete=models.PROTECT, default=1) file = models.FileField(upload_to=user_directory_path, blank=True, default='files/Default_Avatar.png') raised_by_user = models.ForeignKey(GHDUser, on_delete=models.CASCADE, related_name='raised_ticket') ` Now, I am able to create an instance for Ticket model from Admin Panel, but when I try to do the same via shell / using data from front end, I am getting the below error. django.db.utils.IntegrityError: FOREIGN KEY constraint … -
Django annotate field value from external dictionary
Lets say I have a following dict: schools_dict = { '1': {'points': 10}, '2': {'points': 14}, '3': {'points': 5}, } And how can I put these values into my queryset using annotate? I would like to do smth like this, but its not working schools = SchoolsExam.objects.all() queryset = schools.annotate( total_point = schools_dict[F('school__school_id')]['points'] ) Models: class SchoolsExam(Model): school = ForeignKey('School', on_delete=models.CASCADE), class School(Model): school_id = CharField(), This code gives me an error KeyError: F(school__school_id)