Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make PDF viewer in Python/Django?
I'm trying to make an pdf viewer which will be so much user friendly and people will fill that they are reading books in real life. I can't find any updated module in github. I want to make it from scratch without any paid api. -
how to pass image to Base Template/All Templates Django
from this tutorial I want to put some images in the navbar of my Django project. I defined the context_processors.py like this: from .models import Main_page def get_labels_to_context(request): labels = Main_page.objects.all() return { 'labels': labels, } in the Main_page model I have 4 images that should be displayed in the navbar: models.py: class Main_page(models.Model): title = models.CharField(max_length=50, unique=True) label_services = models.ImageField(upload_to='photos/pages/main_page/', blank=True) label_products = models.ImageField(upload_to='photos/pages/main_page/', blank=True) label_support = models.ImageField(upload_to='photos/pages/main_page/', blank=True) label_company = models.ImageField(upload_to='photos/pages/main_page/', blank=True) I added the context processor in the settings.py file. In the template I try to show the images in this way: <a href="#!" class="view overlay z-depth-1 p-0 mb-2"> <img src="{{ labels.label_services.url }}" class="img-fluid" alt="Services label"> </a> but the images are not being loaded! any ideas? -
TypeError: __str__ returned non-string (type NoneType). Not sure how to solve this
models.py from django.db import models # Create your models here. #Work Related aka Department and Work Shift class Department(models.Model): name = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return self.name class WorkShift(models.Model): name = models.CharField(max_length=200, null=True, blank=True) start_datetime = models.DateTimeField(null=True, blank=True) end_datetime = models.DateTimeField(null=True, blank=True) def __str__(self): return self.name #Personel Related aka Employees and Patients class Doctor(models.Model): name = models.CharField(max_length=200, null=True, blank=True) email = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) department = models.ForeignKey(Department, default="", null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.name class Nurse(models.Model): name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) department = models.ForeignKey(Department, default="", null=True, blank=True, on_delete=models.CASCADE) reports_to = models.OneToOneField(Doctor, default="", blank=True, null=True, on_delete=models.CASCADE) work_shift = models.OneToOneField(WorkShift, default="", blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return str(Nurse.name) class Patient(models.Model): STATUS = ( ('Sick', 'Sick'), ('Healing', 'Healing'), ('Cured', 'Cured'), ('Deceased', 'Deceased'), ) name = models.CharField(max_length=200, null=True, blank=True) description = models.TextField(blank=True, null=True) status = models.CharField(max_length=200, null=True, blank=True, choices=STATUS) department = models.ForeignKey(Department, default="", null=True, blank=True, on_delete=models.CASCADE) care = models.ForeignKey(Nurse, default="", blank=True, null=True, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True) def __str__(self): return self.name views.py [from django.shortcuts import render # Create your views here. from django.shortcuts import render from .models import Doctor, Nurse, Patient from django.http import HttpResponse # Create your views here. def … -
Django: Using variable taken from model as default value in input in bootstrap form
I'm new in Django and now I'm working on my first project. I created a form in bootstrap in django. Data from inputs are used to update previous set of data in model nom and to processing in view home. How can I use previous data from nom database as default values in input. Is there any easy way? Thanks bootstrap form <div class="container my-container"> <form action="{% url 'home' %}" method="Post"> {% csrf_token %} <div class= "row my-row"> <div class="col-4 my-col"> Specyfikacja z dni: </div> <div class="col-4 my-col"> <input type="date" placeholder="0" name="datebeg" size="1" /> </div> <div class="col-4 my-col"> <input type="date" placeholder="0" name="dateend" size="1" /> </div> </div> <div class= "row my-row"> <div class="col-3 my-col"> <input type="text" placeholder="0" name="li200" size="1" /> </div> <div class="col my-col"> <h3><span class="badge badge-secondary"> {% if liczba %} {{ liczba }} {% endif %} </span></h3> </div> <div class="col my-col"> <h3><span class="badge badge-secondary"> {% if ls %} {{ ls }} {% endif %} </span></h3> </div> </div> <div class= "row my-row"> <div class="col-3 my-col"> <input type="text" placeholder="0" name="li100" size="1" /> </div> <div class="col my-col"> <h3><span class="badge badge-secondary"> {% if liczba1 %} {{ liczba1 }} {% endif %} </span></h3> </div> <div class="col my-col"> <h3><span class="badge badge-secondary"> {% if ls1 %} {{ … -
Python Asynchronized django rest endpoint
I have a problem with building a django rest endpoint. Endpoint's task is to return Counter object of all articles in database. Since there can be a lot of articles in database I would like to create asynchronized functions to save CPU. I checked plenty of tutorials on how to work with async but I am still not sure how to cope with this issue. So far my endpoint looks like this: @api_view(["GET"]) async def stats(request): result = await count_words() return JsonResponse({"result": result}) Count_words function looks like this: async def count_words(): articles = db.query(Article).all() article_counters_list = map(lambda x: Counter(x.article_content.split()), articles) result = sum(article_counters_list, Counter()) return result This is not working as assertion error apears "Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'coroutine'>" Can you please advice? Also I assume it should be somehow done with generetors instead of lists so please give any advice on how to make these list more efficient. articles = db.query(Article).all() article_counters_list = map(lambda x: Counter(x.article_content.split()), articles) Thank You -
django password reset confirmation
I'm using the django built-in function to reset the password in case the user forgot his password. I also created my own Html pages to make the appearance look good. password_reset_form.html, password_reset_done.html, password_reset_confirm.html, password_reset_complete.html, and password_reset_email.html for the email. the name of password_reset_form.html in my URL is "reset_password"\ the name of password_reset_done.html in my URL is "password_reset_done"\ the name of password_reset_confirm.html in my URL is "password_reset_done"\ the name of password_reset_complete.html in my URL is "password_reset_complete" reset_password and password_reset_done django inbuilt templates work well with my html page created. The problem apprears When I clicked on the link sent to my e-mail, I should see back to my browser my custom url page (password_reset_confirm.html) but instead i'm seeing the django built in template ("password reset confirmation"). I don't know where is the mistake. I have been trying to set that for 2 days now, but it's difficult to figure it out. Can you please help me out? here is my setting: """ Django settings for grouppublishingindia project. Generated by 'django-admin startproject' using Django 3.1.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # … -
how to change error messege in crispy form django
i want to change that error messeges to different sentence, how? -
Django Migration: Undefined Column becuse circular Forign key reference
I have the next model structure in Django: base.py class BaseModel(models.Model): creator = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='%(class)s_creator' ...) ... accounts.py class Company(BaseModel): ... class User(AbstractUser): company = models.ForeignKey(Company, on_delete=models.CASCADE) ... I have created a BaseModel which has a field called creator to the pupose to track who created that record. It has a reference to the User model. That means the Company model, has a reference to the the User model thorugh the BaseModel. But in the account.py I have to put the Company model before User model, because the User model has a reference to the Company model, so it has to come first in the file (see mock code below) I have read this circular issue and the suggeted solution was to use string representation of the User model which I did (setting.AUTH_USER_MODEL), but when I try to run the migration for the first time I am getteing the next error: psycopg2.errors.UndefinedColumn: column accounts_company.creator_id does not exist I think the issue is that the User model was not created at the point when the Company model was created. It looks to me kind of chicken and egg problem. How could be solved this problem and keep the BaseModel creator field? -
Django REST framework - filtering against query param with date Outside Views.py file
I created my "API" using REST framework, now trying to do filtering for it. That's how my models.py look for BookingStatement model. class BookingStatement(BaseModel): ticket_number = models.PositiveIntegerField(unique=True) booking = models.OneToOneField(Booking, on_delete=models.PROTECT) user_rate = AmountField() agent_rate = AmountField() total_amount = AmountField() class Meta: default_permissions = () def __str__(self): return str(self.id) Booking is One to One Key so the booking model has following Attributes. class Booking(BaseModel): bus_seat = models.ManyToManyField(Seat) schedule = models.ForeignKey(Schedule, on_delete=models.PROTECT) boarding_point = models.ForeignKey( BoardingPoint, on_delete=models.PROTECT, null=True ) remarks = models.JSONField(null=True, blank=True) contact = PhoneNumberField(null=True) booking_date_time = models.DateTimeField(auto_now_add=True) class Meta: default_permissions = () verbose_name = 'Booking' verbose_name_plural = 'Bookings' def __str__(self): return '{}-{}'.format(self.user, self.customer_name) I used generic ListAPIView in my views.py as following. class BusCompanyTicketDetailView(generics.ListAPIView, BusCompanyMixin): serializer_class = serializers.TicketDetailResponseSerializer def get_queryset(self): travel_date = (int(self.request.query_params.get('booking_date'))) print(booking_date) return usecases.ListBusCompanyTicketUseCase(date=#'what should i pass?'#).execute() I use usecases.py to filter booking_date_time with url as following. http://127.0.0.1:8000/api/v1/ticket/list?booking_date=2021-1-29 So my usecase file to filter the Booking time is as following. class ListBusCompanyTicketUseCase(BaseUseCase): def __init__(self, date:datetime): self._date = datetime def execute(self): self._factory() return self._booking_statements def _factory(self): self._booking_statements = BookingStatement.objects.filter(booking__booking_date_time=?? need to get date from views.) Problem is I don't know to how to get query params from url in my usecases to filter with booking date any help … -
How to bite-size a form in Django, with no data persistance: What's the most Djangonic mothod?
Firstly, the scenario in my question: I want to deliver a form in bitesize stages, with the valid completion of one stage leading to the next until all stages are complete. On completion, I'd like to use all data once, and then forget it completely so I'm not holding on to any user data. My options as I see it are: Multiple views each with a unique form all bound to a single model. The final submit button in the chain triggers data in the model to be accessed, used and then that particular row removed. Multiple views each with unbound forms, each adding data to a cookie, which is then read on the final submit, data used and the cookie deleted (either using sessions or plain old js hard coded into each template). A single view and template containing a single unbound form, which progressively un-hides divs containing each stage until all stages are completed and final 'submit' posts data from the form, allows a view to process it and forgets it. I can actualise all three of the above, but which is the most 'Djangonic' method? Is there a more conventional way of 'bite-sizing' my single form? -
Post sensor values to a django app deployed on Heroku
Is it possible to post readings from sensors connected to arduino to postgress database of a django app deployed to heroku...am new to heroku need assistance. -
What is the standart value of category filter in fields? Django-filter
I am using django-filter and I have one question. I am using dictionary value for fields in meta tag of filter class. But on the documentation I didnt found stantart value. class Meta: model = Product fileds = { 'category': <here what?>, } -
getting strict-origin-when-cross-origin although i provided CORS_ORIGIN_ALLOW_ALL = True in settings.py file
I have build my frontend using Angular and backend using django-restframwork. In my settings.py I provided CORS_ORIGIN_ALLOW_ALL = True I run it using python3.8 manage.py runserver 5000 but when my frontend tried to send request to it it generates error. my angular sends request like this. my environment file where I saved my urls export const environment = { production: true, api_url: "https://localhost:5000/op-api", user_login_url: "https://localhost:5000/auth/login/", // all_users :"https://ots.ahg.af:5000/rest-auth/login", user_logout_url: "https://localhost:5000/auth/logout/", user_register_user:"https://localhost:5000/auth/register/" }; and by submitting register form I send my request like this. onCreateAccount(){ this.httpService.register_user(this.registerForm.value).subscribe(resp=>{ ....... }, error=>{ ...... } else{ ........ }); } these are in my http service where I call using the above code. user_register_user = environment.user_register_user; public register_user(data){ if (data != null){ return this.http.post(this.user_register_user ,{ 'username': data.username, 'email' : data.email, 'password' : data.password, }); } } can anyone tell me why I am getting cross-origin error and what is the problem. I tried: export const environment = { production: true, api_url: "https://ots.ahg.af:5000/op-api", user_login_url: "https://ots.ahg.af:5000/auth/login/", // all_users :"https://ots.ahg.af:5000/rest-auth/login", user_logout_url: "https://ots.ahg.af:5000/auth/logout/", user_register_user:"https://ots.ahg.af:5000/auth/register/" }; ots.ahg.af is my domain name export const environment = { production: true, api_url: "http://127.0.0.1:5000/op-api", user_login_url: "http://127.0.0.1:5000/auth/login/", // all_users :"http://127.0.0.1:8000/rest-auth/login", user_logout_url: "http://127.0.0.1:5000/auth/logout/", user_register_user:"http://127.0.0.1:5000/auth/register/" }; none of the above worked for me. -
VScode redis extension show gebberish
VScode redis extension show gibberish of key string, is this an encoding problem? how to fix this in vscode? I am using windows -
Django data from context not showing in template
Im stuck with a template context in Django. In my template I display information about a team and I also want to display players from this team. In context I pass players from team but then in template when I want to display this data it doesn't work. I tried to add also some example data like "test":123 and display it in template like {{test}} but it also doesn't work. views.py* def team_profile(request, name): team = Team.objects.get(name=name) player_list_filtered = [] player_list = User.objects.all() for player in player_list: if player.profile.team.name == team.name: player_list.append(player) context = { 'team': team, 'players': player_list_filtered, 'test': 123 } return render(request, 'blog/team_profile.html', context) team_profile.html* {% block content %} <div class="d-flex align-items-start flex-column content-section"> <img class="rounded-circle account-img" src="{{ team.image.url }}"> <h1>{{team.name}}</h1> <h3>Mecze: {{team.matches}}</h3> <h3>League: {{team.league}}</h3> {% for player in players %} <h3>{{player.first_name}}</h3> {% endfor %} <p>Test: {{test}}</p> </div> {% endblock content %} Here is my result -
Django forms are not reflecting on html tempelate page
Am trying to create forms in django template but the fields are not showing.I have no idea why the fields are not showing, Kindly help out. Below are the codes forms.py from django import forms class ContactForm(forms.Form): from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) views.py from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from .models import Contacts from django.core.mail import send_mail, BadHeaderError from django.conf import settings from .forms import ContactForm # Create your views here. def Contacts(request): # contact = Contacts.objects return render(request,'Contacts/index.html') def Home(request): return render(request,'Home/index.html') def contact(request): if request.method =='GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['henryochieng8@gmail.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return render('success') return render(request, "Contacts/index.html", {'form':form}) def successView(request): return HttpResponse('Success! Thank You for messaging us.') part of html file <h1>Contact Me</h1> <form action="" method="post" role="form"> {% csrf_token %} {{form.as_p}} <div class="form-actions"> <button type="submit">Send</button> </div> </form> -
django-allauth signals user_signed_in signal isn't working
I am relatively new to django, and trying to trigger a function on login. I have tested the function itself, and it works fine. The django-allauth login is also correctly configured. However, i cannot seem to trigger the signal below on login. See code below... Any help would be appreciated... pages/apps.py from django.apps import AppConfig class PagesConfig(AppConfig): name = 'pages' def ready(self): import apps.pages.signals pages/signals.py from allauth.account.signals import user_logged_in from django.dispatch.dispatcher import receiver from django.utils import timezone from datetime import timedelta from .models import Token @receiver(user_logged_in) def user_logged_in_(request, user, **kwargs): is_valid = Token.objects.filter(valid_until__gte=timezone.now() + timezone.timedelta(seconds=10800)).values() if not is_valid: new = Token(token='valid', valid_until=timezone.now()) else: new = Token(token='not valid', valid_until=timezone.now()) new.save() -
Which cloud store should i use for storing documents?
I have developed a Django web app which store user uploaded pdfs, Docx. Site is hosted on pythonanywhere.com. The problem is pythonanywhere provide only 500 MB for a free account. Storage provided by them on the paid account is I feel costly which is 5GB disk space for 12 USD/ Month. I really do not need a lot of space but 500 MB is too low for me. Should I use Google drive/ One drive which provides 15 GB for free and paid service is also quite low than pythonanywhere? Will it affect on drastically on the website? -
Is it possible to reuse annotations from one model in another one in Django?
I'm using Django 2.2.16 and I was trying to get rid of replicated logic across querysets. I didn't manage to find a way (without impacting performance, like subquery in select clause) to reuse annotations from one model in annotations of another one. Here is my current implementation: # models.py from django.contrib.gis.db import models from querysets import PostManager, TagManager class Tag(models.Model): objects = TagManager() name = CICharField(db_index=True, max_length=100) class Post(models.Model): objects = PostManager() STATUS_ACCEPTED = "ACCEPTED" STATUS_DECLINED = "DECLINED" STATUS_CHOICES = ( (STATUS_ACCEPTED, "Accepted"), (STATUS_DECLINED, "Declined"), ) status = models.CharField( default=STATUS_DECLINED, choices=STATUS_CHOICES, max_length=63, verbose_name="Źródło ogłoszenia", ) expiration_date = models.DateField(blank=True, null=True) tags = models.ManyToManyField(Tag, blank=True, db_index=True) # querysets.py from django.db.models import Case, Count, Q, QuerySet, When, Manager class PostQuerySet(QuerySet): def annotate_statuses(self): today = date.today() return self.annotate( live=Case( When( Q(status="ACCEPTED") & (Q(expiration_date__isnull=True) | Q(expiration_date__gte=today)), then=True, ), default=False, output_field=models.BooleanField(), ), expired=Case( When( Q(status="ACCEPTED") & (Q(expiration_date__isnull=False) & Q(expiration_date__lt=today)), then=True, ), default=False, output_field=models.BooleanField(), ), ) PostManager = Manager.from_queryset(PostQuerySet) class TagQuerySet(QuerySet): def annotate_live_listings(): today = date.today() return queryset.annotate( posts_count=Count("post"), listings_count=Sum( Case( When( Q(post__status="ACCEPTED") & (Q(post__expiration_date__isnull=True) | Q(post__expiration_date__gte=today)), then=1, ), output_field=IntegerField(), default=0, ) ), ) TagManager = Manager.from_queryset(TagQuerySet) My question is if it's possible to reimplement method annotate_live_listings in TagQuerySet to reuse somehow already implemented annotate_statuses from PostQuerySet. … -
Receiving data from ESP8266 to Django
I am trying to send data from sensor connected to ESP8266 to Django server using this Arduino code void loop(void){ if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status HTTPClient http; data = analogRead(A0); const int capacity = JSON_OBJECT_SIZE(2); StaticJsonDocument<capacity> doc; doc["sensor"] = data; serializeJsonPretty(doc, postMessage); serializeJsonPretty(doc, Serial); http.addHeader("Content-Type", "application/json"); http.begin("http://192.168.1.21:8000/sensor"); //Specify destination for HTTP request int httpCode = http.POST(postMessage); String payload = http.getString(); if (httpCode > 0) { Serial.println(); Serial.println(httpCode); if (httpCode == 200) { Serial.println("Hooray!"); } } Serial.println(payload); delay(5000); } } but I cant get the postMessage value to django iam using this code and getting None @csrf_exempt def index(request): data = request.POST.get("postMessage", None) print(data) return HttpResponse("Hello there") -
Retrieve a value from JWT Token in Python
I have passed a boolean field, 'is_valid' in the JWT token payload. Now I need to retrieve the value of 'is_valid' for condition checking. How can I do it in python django? Check this image -
iterating over two tables simultaneously in Django Template For Selection - Python Django
Here, I want to iterate over two tables data and make them available in SELECT tag for selection, and this is a mapping table so I want to iterate two tables simultaneously. This mappings I want to store in Mapping table. Let me show my code so that you can better understand it. models.py class Product(models.Model): prod_ID = models.AutoField("Product ID", primary_key=True) prod_Name = models.CharField("Product Name", max_length=30, null=False) prod_Desc = models.CharField("Product Description", max_length=2000, null=False) prod_Price = models.IntegerField("Product Price/Piece", default=0.00) prod_img = models.ImageField("Product Image", null=True) def __str__(self): return "{}-->{}".format(self.prod_ID, self.prod_Name) class Size(models.Model): size_id = models.AutoField("Size ID", primary_key=True, auto_created=True) prod_size = models.CharField("Product Size", max_length=20, null=False) def __str__(self): return "{size_id}-->{prod_size}".format(size_id=self.size_id, prod_size=self.prod_size) class SizeProductMapping(models.Model): size_p_map_id = models.AutoField("Size & Product Map ID", primary_key=True, auto_created=True) size_id = models.ForeignKey(Size, null=False, on_delete=models.CASCADE, verbose_name="Size ID") prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id") def __str__(self): return ".`. {}_____{}".format(self.size_id, self.prod_id) Here in above models i want to store size and product mapping in SizeProductMap table. views.py def sizeProductMap(request): # Here I am fetching products and size ID to give option while add new records productSize_show = Size.objects.all() print(productSize_show) product_show = Product.objects.all() print(product_show) attribute_values = zip(productSize_show, product_show) print(attribute_values) if request.method == 'POST': size_id = request.POST['size_id'] product_id = request.POST['prod_id'] sizeProductMap_update = SizeProductMapping(size_id=size_id, prod_id=product_id) # … -
Uploaded an image got [Error 111] using Cloudinary on Pythonanywhere
Hi, Somebody, please help me, I'm using Pythonanywhere to store my Django code and everything run properly except when I'm trying to upload an image. I got this error: cloudinary.exceptions.Error: Unexpected error - MaxRetryError("HTTPSConnectionPool(host='api.cloudinary.com', port=443): Max retries exceeded with url: /v1_1/MY-CLOUD-NAME/image/upload (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f5de5f6e6d0>: Failed to establish a new connection: [Errno 111] Connection refused'))") This is my code in model.py: from cloudinary.models import CloudinaryField some class project_image = CloudinaryField("project_img", proxy="http://proxy.server:3128") This is my code in setting.py: CLOUDINARY = { 'cloud_name': 'CLOUD-NAME', 'api_key': 'xx', 'api_secret': 'xx, } CLOUDINARY_URL='cloudinary://xxx@CLOUD-NAME?api_proxy=proxy.server:3128' I also tried to change the proxy.server part to: - https://api.cloudinary.com/v1_1/MY-CLOUD-NAME and add the api_proxy in CLOUDINARY parameter but It didn't work also P.S. I'm using a free Pythonanywhere account and I do some research and the owner said that I have to set the proxy to proxy.server:3128 but I don't know how to do that P.S.2 What I've tried to do so far upgrade urllib but didn't work out try to add a proxy in many different ways on setting.py as you saw above Please help me or at least give me any advice, I'm really new to the Pythonanywhere site -
In Django, how can we stop losing the details filled in the form, if it fails validation?
I am using the UserCreationForm for user registration in my Django web app. When the user fills in the detail (username, password, confirm_password) and submits, then if the form fails validation (maybe because username already exists or password don't match or password is too short) then the user is redirected back to the register page (see the below code, to redirect I've used return HttpResponseRedirect(reverse("register")). Now my problem is that when he is redirected back to the register page, the form is blank again, i.e. he has to start all over again, which is not a good user experience because his form might fail one or more times. I want that if the form fails validation and when he is redirected to the registration form, he should see his previously filled in details so that he can just correct the field which is causing the error and move on. Is there any way the data can be retained? Here is my code of the register function in views.py: def register(request): if request.method == 'POST': form = UserCreationForm(request.POST or None) if form.is_valid(): # some code return redirect('login') else: messages.error(request, form.errors) return HttpResponseRedirect(reverse("register")) If it's not possible to retain details in the … -
Django ERROR: there is no unique constraint matching given keys for referenced table
There are many similar questions on Stackoverflow, but none of the answers has helped me. So, when running migrations, Django throws this error: django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "catalogues_movieslist" I have this BlackWhiteCartoon model I am trying to create with the migration: class BlackWhiteCartoon(BaseMovie, BaseList): authors = JSONField(default=list, blank=True, null=True) publisher = CharField(max_length=250, blank=True) year = PositiveSmallIntegerField(blank=True, null=True) This model inherits from the BaseList model that has only one field, a foreign key: class BaseList(Model): belongs_to_movies_list = ForeignKey(MoviesList, on_delete=CASCADE, null=True) The referenced MoviesList model is the following: class MoviesList(Model): creation_date = DateTimeField(auto_now_add=True) id = AutoField(primary_key=True) uid = UUIDField(default=uuid.uuid4, editable=False) user = ForeignKey(User, on_delete=CASCADE, null=True, blank=True) Also, the BaseMovie model is the following: class BaseMovie(BaseObject): language = CharField(max_length=2, blank=True) note = CharField(max_length=700, blank=True) And the BaseObject model: class BaseObject(Model): id = BigAutoField(primary_key=True) uid = UUIDField(default=uuid.uuid4, editable=False, db_index=True) date_added = DateTimeField(null=True) So, what I have tried: Migrating everything together: this throws the above error. Migrating BlackWhiteCartoon without inheriting BaseList first. This migration applies, but as soon as I add BaseList, it crashes with the same error. Adding unique=True to the id field of MoviesList (both together with all other migrations and before adding BaseList to …