Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Running drowsiness detection python file by clicking a button using django
I am doing a capstone project related to a drowsiness detection system, I have written a python file that pops up the web camera and detects drowsiness from the face. I have made a Django website to run this detection system. I want that this python file that just pops up the web camera and detects drowsiness of a person run by clicking an HTML button but I'm unable to find that, how can I make this possible -
How Can I Use This MongoDB Object In Django Field ( Djongo, MongoDB, PyMongo ]
What Is Name Of This MongoDb Object On Django Or Djongo Fields? -
Why does .save() still take up time when using transaction.atomic()?
In Django, I read that transaction.atomic() should leave all the queries to be executed until the end of the code segment in a single transaction. However, it doesn't seem to be working as expected: import time from django.db import transaction my_objs=Obj.objects.all()[:100] count=avg1=0 with transaction.atomic(): for obj in my_objs: start = time.time() obj.save() end = time.time() avg1+= end - start count+= 1 print("total:",avg1,"average:",avg1/count) Why when wrapping the .save() method around a start/end time to check how long it takes, it is not instantaneous? The result of the code above was: total: 3.5636022090911865 average: 0.035636022090911865 When logging the SQL queries with the debugger, it also displays an UPDATE statement for each time .save() is called. Any ideas why its not working as expected? PS. I am using Postgres. -
Django Query Joining and Grouping
I'm having trouble figuring out the most efficient way to query the following scenarios and appreciate any assistance class Company(models.Model): name = models.CharField(max_length=100) class DatapointModel(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) name = models.CharField(max_length=255) value = models.FloatField() Now I essentially need all company that have two valid DatapointModel rules such as companies with both datapoint name='country' with value='USA' and datapoint name='building_color' with value='blue' Results should be each company name where both datapoint rules are satisfied -
Deleting Tablib Dataset Column Headers skipping unexpectedly in Django Import Export
I have a csv file with this sample data: in which I am trying to modify django-import-export's before_import function and overwrite the dataset, and in order to do so I need to empty the current dataset and replace it with a new one. Here is how I do it: def before_import(self, dataset, using_transactions, dry_run, **kwargs): """ code to create a new_dataset """ print(dataset.headers) # delete data rows in dataset del dataset[0:len(dataset)] # delete headers for header in dataset.headers: del dataset[header] print(dataset) """ code to replace dataset with the new_dataset """ what the shown code does is delete the dataset's data and its headers. But the print shows not all headers are deleted. It skips headers being deleted, or more accurately, it alternates in deleting them. Is there something I'm missing in here? -
Django model filter objects having a field as self object(please read body of question)
I have two models Quiz and ABCD ABCD is connected to Quiz using oneToOneField Quiz model will be used to store a quiz and ABCD is a model used to store result for a user one Quiz will be connected to Multiple ABCD(one quiz will have multiple results) inside Quiz model i want a method which will return all results for that quiz(ABCD objects having That quiz as its quiz field) what should i write to filter the ABCD with that Quiz class Quiz(models.Model): name=models.CharField(max_length=250) def show_results(self): return ABCD.objects.filter(quiz=what to write here) class ABCD(models.Model): quiz=models.OneToOneField(Quiz,on_delete=models.CASCADE) points=models.IntegerField() -
Reverse for 'topic' with arguments '('',)' not found. 1 pattern(s) tried: ['topics/(?P<topic_id>[0-9]+)/\\Z']
I am getting this error: Reverse for 'topic' with arguments '('',)' not found. 1 pattern(s) tried: ['topics/(?P<topic_id>[0-9]+)/\\Z'] which I believe is stemming from my urls.py: from django.urls import path from . import views urlpatterns=[ #your paths go here path('', views.index, name='index'), # home page path('topics/', views.topics, name='topics'), path('topics/<int:topic_id>/', views.topic, name='topic') # add id arguemnt since each entry is linked to topic by id ] here is the topics.html which links to topic.html: {% extends "learning_logs/base.html" %} {% block content %} <p>Topics</p> <ul> {% for topic in topics %} <!--passed through context i guess?--> <li> <a href = "{% url 'topic' topics.id %}">{{ topic }}</a> </li> {% empty %} <li>No topics have been added yet.</li> {% endfor %} </ul> {% endblock content %} and here is the views.py code for topic: def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') # minus sign indicates reverse order context = {'topic':topic, 'entries':entries} return render(request, 'learning_logs/topic.html', context) Thanks for any help! -
Data is not getting stored in a database through a customer form
I made a customer feedback form with rating stars. But problem is, not getting stored data in database. Where the actual problem occured? What is the relevent solution? I tried many time. forms.py: class FeedBackForm(forms.Form): feedBACK = forms.CharField(widget=forms.Textarea, required=True) rating = forms.CharField(widget=forms.NumberInput) models.py: class ProductREVIEWS(models.Model): rating = models.IntegerField(blank=True, null=True) feedBACK = models.TextField(blank=True, null=True) views.py: def quick_view(request, quick_view_id): form = FeedBackForm() if request.method == "POST" and request.user.is_authenticated: form = FeedBackForm(request.POST) if form.is_valid(): ProductREVIEWS.objects.create( feedBACK=form.cleaned_data.get('feedBACK'), rating=form.cleaned_data.get('product_rating'), ) template: <form action="#!" method="POST" class="needs-validation mt-3" style="font-size: 13px;" novalidate="" autocomplete="off"> {% csrf_token %} <div class="radio-toolbar d-flex"> <input type="radio" id="one_star" name="product_rating" value="1" checked> <label for="one_star" class="mx-1">1 <i class="fas fa-star"></i></label> <input type="radio" id="two_star" name="product_rating" value="2"> <label for="two_star" class="mx-1">2 <i class="fas fa-star"></i></label> <input type="radio" id="three_star" name="product_rating" value="3"> <label for="three_star" class="mx-1">3 <i class="fas fa-star"></i></label> <input type="radio" id="four_star" name="product_rating" value="4"> <label for="four_star" class="mx-1">4 <i class="fas fa-star"></i></label> <input type="radio" id="five_star" name="product_rating" value="5"> <label for="five_star" class="mx-1">5 <i class="fas fa-star"></i></label> </div> <div class="mb-3 mt-2"> <textarea id="email" placeholder="Share your experiencs..." rows="10" style="font-size: 13px; text-transform: lowercase;" type="email" class="form-control" name="feedBACK" value="" required></textarea> </div> -
Cannot close bootstrap accordion after modal dismissing
I use boostrap 5.1.3 and django-bootstrap-modal-forms 2.2.0 in my django project. The problem is when I open modal driven by django-bootstrap-modal-forms it changes css and behavoir of bootstrap elements on the page. I illustrate that with accordion element. <div class="accordion" id="filters"> <h2 class="accordion-header" id="headingOne"> <button class="accordion-button collapsed" id="filtersButton" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="false" aria-controls="collapseOne"> Filters </button> </h2> <div class="accordion-body" id="accordion-body-filters"> <div id="collapseOne" class="accordion-collapse collapse" aria-labelledby="headingOne" data-bs-parent="#accordionExample"> <form action="" method="get" class="form form-inline" id="django-filter-form"> Some form here </form> </div> </div> </div> Modal <div class="modal fade" tabindex="-1" role="dialog" id="modal"> <div class="modal-dialog" role="document"> <div class="modal-content"></div> </div> </div> the modal is triggered by the button <button type='button' id='new-payment' class="btn btn-secondary"> </button> JS <script type="text/javascript"> $(document).ready(function() { $("#new-payment").modalForm({ formURL: "{% url 'Payment_register:add_payment' %}" }); }); </script> When I open and then dismiss modal I cannot close accordion. Aria-expanded of #filtersButton is always "true" and #filtersButton's ".show" class remains despite of clicking on collapse button. To be more presise, #collapseOne gets "collapsing" class for a moment, but then it becomes "show" again. The only way to get accordion's normal behavoir back is to refresh the page. I also have found that cdn links to bootstrap css and js somehow add to modal html. They are the same I … -
Django framework CORS error on Heroku while working fine on localhost,
I have a Django rest API deployed on Heroku, and the interface is deployed on Cloudflare, now when I hit the endpoint on Heroku it gives me a CORS error, but when I hit the endpoint on localhost, it works fine, so why does the CORS error appear only on Heroku? and how to pass this issue? Tell me please if have to change anything in my code!! Settings.py """ Django settings for API project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os import django_heroku import dj_database_url from decouple import config # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # 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 = 'django-insecure-@es2kt*gq&6zs^+a4wtidi)^!-o-%ft4+17n==kdanf-b&nuzq' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True CSRF_COOKIE_SAMESITE = 'Strict' SESSION_COOKIE_SAMESITE = 'Strict' CSRF_COOKIE_HTTPONLY = True SESSION_COOKIE_HTTPONLY = True CORS_ALLOW_ALL_ORIGINS = True # # PROD ONLY # CSRF_COOKIE_SECURE = True # SESSION_COOKIE_SECURE = True ALLOWED_HOSTS = [] # … -
Django rules overwrite not getting applied
We use an abstract model class to lay some ground rules that should get overwritten by the actual models in Django (more detail in previous question). In this case most classes have a typical use case, so they inherit the same permissions from the base class, but in case of the exemplary Ticket the is_public predicate should be added. class BaseModel(RulesModel): ... class Meta: abstract = True @classmethod def preprocess_rules_permissions(cls, perms): perms.update({ "can_create": can_create_in_company | is_superuser, "can_view": can_view_in_company | is_author | is_superuser, }) class Ticket(BaseModel): ... @classmethod def preprocess_rules_permissions(cls, perms): perms.update({ "can_view": can_view_in_company | is_author | is_superuser | is_public, }) Implementing it this way results in the predicate not being applied when trying to access a public ticket. Are all the rules overwritten by the update method, or can we specifically update one predicate? Even when adding a print statement in the Tickets preprocess it doesn't get executed, so the overwrite apparently doesn't work. The documentation doesn't mention anything here. -
Python Django Regional Data Storage
I have a Django application which is hosted on Heroku at present, with databases MySQL in AWS RDS. When my users sign up I want them to select which region of RDS to store their data, in a specific RDS instance. I was going to use one global database for user authentication and regional preferences and then app routing at DB level to connect to that instance for fetching data. I am concerned about latency and overhead with number of connections required, is there a better way to achieve this? Its based on user preference rather than geo location, so I can't auto load balance based on IP Thanks all -
Unable to deploy Django app to Heroku with waitress
I tried a few weeks ago to host a Django app to Heroku, but when I try opening my app, I get an Application Error. I tried many alternatives as well but nothing seems to work for me, as it's the same error again. Any help would be greatly appreciated! Please do let me know if I need to include any other files. Procfile: web: waitress-serve --listen=*:5000 Cakewala_Attendance.wsgi:application --log-file - --log-level debug heroku ps:scale web=1 python manage.py migrate .gitignore: # Created by https://www.toptal.com/developers/gitignore/api/visualstudiocode,django # Edit at https://www.toptal.com/developers/gitignore?templates=visualstudiocode,django ### Django ### *.log *.pot *.pyc __pycache__/ local_settings.py db.sqlite3 db.sqlite3-journal media # If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/ # in your Git repository. Update and uncomment the following line accordingly. # <django-project-name>/staticfiles/ ### Django.Python Stack ### # Byte-compiled / optimized / DLL files *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec … -
como puedo hacer para sumar dos modelos dentro de una clase? Django models
from django.db import models from django.forms import CharField, IntegerField from django import forms proceso_status=(('hc','Hc'),('af','Af')) lente_status=[('argon','Argon'),('ecoline','Ecoline'),('mig','Mig'),('fall dual','Fall dual'),('argon elite','Argon Elite'),('neon','Neon'),('new classic','New classic'),('aviator','Aviator')] lente_tipo=[('argon','Argon'),('ecoline','Ecoline'),('mig','Mig'),('neon','Neon')] class tiempo_de_carro(models.Model): tipo_proceso = models.CharField( null=False, blank=False, choices=proceso_status, default='Hc', max_length=2, verbose_name='Tipo de proceso') tipo_lente= models.CharField( max_length=12, null=False,blank=False, choices=lente_status, default='argon', verbose_name= 'Tipo de lente') tiempo_ciclo=models.IntegerField( verbose_name='Tiempo de ciclo' ) tiempo_carro=models.IntegerField( ) class Meta: db_table = 'tiempo_de_carro' -
how to create a SimpleListFilter in django
I have the following models : Patient, Prescription and User doing the relationship between the both first ones. class Patient(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) address = models.TextField(blank=True, null=True) city = models.CharField(max_length=85, null=True, blank=True) country = CountryField(null=True, blank=True) postal_code = models.CharField(max_length=32, null=True, blank=True) [and other stuff] class Prescription(models.Model): user = models.ForeignKey( User, null=True, blank=False, on_delete=models.DO_NOTHING ) uploaded_by_user = models.IntegerField( 'upload user from request.user', null=True, ) prescription_date = models.DateTimeField( null=True, blank=True, ) image_file = models.BinaryField( 'prescription file', blank=True, null=True, ) file_extention = models.CharField( 'file extention', max_length=8, null=True, blank=True, ) In the PatientAdmin, i want to use a filter by prescription file (for example pdf or jpg) I created a SimpleListFilter but i have still the same issue. Prescription' object is not subscriptable Here the code of my SimpleListFilter class PrescriptionFileExtensionFilter(SimpleListFilter): """ This filter is being used in django admin panel in patient model. """ title = 'Prescription File Ext' parameter_name = 'file_extention' def lookups(self, request, model_admin): return ( ('pdf', 'PDF'), ('jpg', 'JPG'), ) def queryset(self, request, queryset): print(queryset) for user in queryset: mydict = user.user.prescription_set.all().first() print(mydict['file_extention']) if self.value() == 'pdf': return queryset.filter( user=user.user).filter(prescription__file_extention="pdf") if self.value() == 'jpg': return queryset.filter( user=user.user).filter(prescription__file_extention="jpg") -
How to get list phone number (12 phones) with most Vote type bad (django)
i'm using django and i want a query to get a list phone number (12 phones number) with condition Vote has type bad and list phone is most type vote is bad. Please help me how to query to get list phone with conditions that. Eg: phone 1 has 10 vote bad, phone 2 has 1 vote bad, phone 3 has 5 vote bad, phone 4 has 2 vote bad. list_phone_i_want_3_item = [phone 1, phone3, phone4] with [10 vote bad, 5 vote bad, 2 vote bad] bellow is my models class Phone(models.Model): phone_number = models.TextField(max_length=15, verbose_name="phone", default="") view = models.IntegerField(default=1, verbose_name="view") create = models.DateTimeField(auto_now_add=True, verbose_name="create") status = models.BooleanField(default=True, verbose_name="status") def __str__(self) -> str: return self.phone_number class Vote(models.Model): # type vote : 1 is Normal # 2 is Spam # 3 is Bad type_vote = models.IntegerField(default=1, verbose_name="type vote") phone = models.ForeignKey(Phone,on_delete=models.CASCADE, related_name="phone") comment = models.TextField(verbose_name="comment") create = models.DateTimeField(auto_now_add=True, verbose_name="creat") status = models.BooleanField(default=True, verbose_name="status") def __str__(self) -> str: return self.comment -
I need to link comments to single post in django , i have no idea what to do , i'm self taught
i need crucial help, i need to link comments to single post in django , i have no idea what to do my models i think this is the only part that i know what is goin on from tkinter import CASCADE, Widget from django.db import models from django.contrib.auth.models import User class Post (models.Model): id = models.AutoField(primary_key=True) name = models.ForeignKey(User, on_delete=models.CASCADE, default='User') text = models.TextField (max_length=200) posted = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text class Comment(models.Model):#comment for the requests request = models.ForeignKey('sunu_app.Post', on_delete =models.CASCADE , related_name='comments', null=True , blank=True) # name = models.ForeignKey(User, on_delete=models.CASCADE , null=True , blank=True) text = models.TextField () posted = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text my views i honestly had no idea what was going on there # from typing_extensions import Self from urllib.request import Request from django.http import HttpResponse from django.shortcuts import get_object_or_404, render from django.shortcuts import render,redirect from .forms import * from .models import * def home(request): requests = Post.objects.all().order_by('-posted') count = Post.objects.all().count() #diplay the comments here and let it save in commentform.view comments = Post.comment_set.all() context = {'requests':requests , 'count':count , 'comments':comments} return render(request,'sunu_app/home.html', context) # context = {'cases':rooms} the second value is the data # you want to pass the first value is … -
What is the difference between Django's ScopedRateThrottles and Throttles Per View (Custom Throttle Classes)?
I'm working on adding a mechanism to prevent Brute force login attacks into my Django-based app. I'm aware of Django-Axes but do not want to use an external app when I can implement it using Django's default features. I came across this article which did a good job giving me an overview of how to achieve this, but I'm confused about the difference between Django's ScopedRateThrottles and Throttles Per View (Custom Throttle Classes) mentioned in the article. Is the difference just that you can have a custom error message, etc. in custom classes but can't do the same in Scoped? What's the best way for me to achieve what I need? I even referred to these two StackOverflow question/answers: How to prevent brute force attack in Django Rest + Using Django Rest Throttling Django rest framework - how can i limit requests to an API endpoint? -
Why django site is not working on cloud hosting platform?
I built my website in the Django framework and used PostgreSQL as a database. I used aws ec2 instance of 1GB ram, Digital Ocean 2GB & 4GB ram droplet for hosting one by one. There was no error after the runserver command. But the website is not showing on the browser. I can't find the reason why it's happening. -
I am using htmx javascript API how do I get the response from server
My code block looks like this, basically when a modal is triggered I send a GET request and retrieve the response, it does send the request alright, but I am unable to see (or to put it better) to get the response from the server via .then() from htmx. I am using the example from there documentation. htmx.ajax('GET', '/user-related-comment/', { swap: 'none', values: { userId: userId } } ).then(data => { console.log(data) }) data is undefined when logged to browser console. -
How to split Django Queryset on two parts of HTML code?
I'm trying to do my Django web-app and can't to overcome a problem. I need to split my model objects on two divs for correct display, but my dish objects just dublicate each other. I've tried to find info how to split my dishes objects on two parts and give them to html code, but it didn't works. Also there is can be a jinja solution, but I don't know how to resolve it, because the pure html code of project is something I never seen before (there is left-list and right-list classes for dishes columns, therefore we need to split our dishes dict somehow). views.py: def reserve(request): chefs = ChefsModel.objects.all() dishes = DishesModel.objects.all() error = '' if request.method == 'POST': form = ReserveForm(request.POST) if form.is_valid(): form.save() return redirect('index') else: error = 'Invalid form' else: form = ReserveForm() return render(request, 'main/index.html', {'form':form, 'error':error, 'chefs':chefs, 'dishes':dishes, }) def index(request): return reserve(request) My Django template + HTML: <article id='tabs-1'> <div class="row"> {% for i in n %} <div class="col-lg-6"> <div class="row"> <div class="{% cycle 'left' 'right' %}-list"> {% for dish in dishes %} {% if dish.tabs == 'Breakfast' %} <div class="col-lg-12"> <div class="tab-item"> <img src="{{ dish.image.url }}" alt=""> <h4>{{ dish.name }}</h4> <p>{{ … -
Reverse for 'topic' not found. 'topic' is not a valid view function or pattern name (another one)
I'm aware that there are quite a few similar posts like this one, but I still can't figure it out 😭. This is the code in the 'topics' template that links each individual 'topic' to it (also the code causing the error): <a href = "{% url 'topic' topic.id %}">{{ topic }}</a> Error being: django.urls.exceptions.NoReverseMatch: Reverse for 'topic' not found. 'topic' is not a valid view function or pattern name. Here is urls.py: urlpatterns=[ #your paths go here path('', views.index, name='index'), # home page path('topics/', views.topics, name='topics'), path('topics/<int:topic_id>/', views.topics, name='topics') # add id arguemnt since each entry is linked to topic by id ] Here is the topic function in views.py: def topic(request): topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') # minus sign indicates reverse order context = {'topic':topic, 'entries':entries} return render(request, 'learning_logs/topic.html', context) Thanks for any help! Let me know if there's any other code I should include. -
Redirect don't see url patterns
Redirect don't work with patterns urlpatterns = [ path('', views.index, name="home"), path("rights/", views.rights, name="rights"), path("add_card", views.add_card, name="add-card"), path("show_card/<card_id>", views.show_card, name="show-card"), path('search', views.search, name="search"), path('edit/<card_id>', views.edit, name="edit"), ] views.py def edit(request, card_id): card = Card.objects.get(pk=card_id) form = CardForm(request.POST or None, instance=card) if form.is_valid(): form.save() return redirect('home') return render(request, 'main/edit.html', {'card':card, 'title':'Редактирование карточки', 'form':form,}) Error: Reverse for 'home' not found. 'edit' is not a valid view function or pattern name. I have tried to chance return redirect to reverse. Also I haev tried to chance path. When I replaced home to main/home Error looks like Page not found 404 path: ../edit/main/home. i.e. in my case redirect add the path home to edit, not updating. If I replace redirect('home') to return render(request, 'main/home', {}) Error look like TemplateDoesNotExist at /edit/14 How to fix this problem? -
Error while providing arguments in django project while testing
I am new to django need a bit of help in testing a particular section of the user model. Heres the error showing while running the test These are my codes models.py from pyexpat import model from django.utils.translation import ugettext_lazy as _ from django.db import models from django.utils.crypto import get_random_string from django.db import models from django.contrib.auth.models import( BaseUserManager, AbstractBaseUser, PermissionsMixin, ) def generate_vid(): """Generates a vid for the users""" not_unique = True while not_unique: vid = get_random_string(10, 'abcdefg0123456789') if not User.objects.filter(v_id = vid).exists(): not_unique=False return vid class UserManager(BaseUserManager): """Model for user manager""" def create_user(self, username, password=None, **params): """Create and return a user""" user = self.model(username=username, **params) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, password, **params): """Create and return a user""" params.setdefault('is_staff',True) params.setdefault('is_superuser',True) params.setdefault('is_active',True) if params.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if params.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(username, password, **params) class User(AbstractBaseUser, PermissionsMixin): """Models for user""" v_id = models.CharField( max_length=10, default=generate_vid, primary_key = True, ) username = models.CharField(max_length=20, unique=True) email = models.EmailField(blank=True, unique = True) # parent_id = models.ForeignKey('User', on_delete=models.SET_DEFAULT, default=0) usertype = models.CharField(max_length=1, choices=[('f', 'family'), ('v', 'veteran')]) REQUIRED_FIELDS = [] is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) USERNAME_FIELD = 'username' objects = UserManager() … -
FOREIGN KEY constraint failed djnago
I get the error FOREIGN KEY constraint failed. I'm trying to return the average of comments and ratings in a model Class Movie, but I get the error FOREIGN KEY constraint failed. How can I fix it? class Movie(models.Model): def get_comments(self): return Comment.objects.filter(movie_id=self.id) def average_stars(self): comments = self.get_comments() n_comments = comments.count() if n_comments == 0: return 0 else: return sum([comment.stars for comment in comments]) / n_comments class Comment(models.Model): comment = models.TextField(max_length=1000) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) user = models.OneToOneField(CustomUser, on_delete=models.CASCADE,) movie = models.ForeignKey(Movie, on_delete=models.CASCADE) created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(auto_now=True) def view_movie_detail(request, movie_id): if request.method == "POST": user = request.user comment = request.POST.get("comment") stars = request.POST.get("stars") if not request.user.is_authenticated: user = User.objects.get(id=1) Comment(comment=comment, stars = stars, user=user,movie_id=movie_id).save() return redirect(f"/movie/{movie_id}/") else: data = requests.get(f"https://api.themoviedb.org/3/movie/{movie_id}?api_key={TMDB_API_KEY}&language=en-US") recommendations = requests.get(f"https://api.themoviedb.org/3/movie/{movie_id}/recommendations?api_key={TMDB_API_KEY}&language=en-US") comments = reversed(Movie().get_comments()) average = Movie().average_stars() return render(request, "Movie/movie_detail.html", { "data": data.json(), "recommendations": recommendations.json(), "type": "movie", "comments": comments, "average" : average, }) I get the error FOREIGN KEY constraint failed. I'm trying to return the average of comments and ratings in a model Class Movie, but I get the error FOREIGN KEY constraint failed. How can I fix it?