Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to prevent flushing data in test database after every test case in Django
I am currently writing my first Django application and writing selenium test cases for testing the UI. I am using the Django test case class for testing the app. This is the configuration for running test cases: "configurations": [ { "name": "test", "type": "python", "request": "launch", "program": "${workspaceFolder}\\manage.py", "args": [ "test", "review.tests.test_selenium.ReviewTests.test_app", "--keepdb" ], "django": true } This configuration uses the existing test database and I have to add data in the tables each time I run a new test case. Is there any way to preserve data after running test-cases? Thanks In Advance. -
Django: Send API Key back to the user on successful authentication
I have a requirement to create Django(1.8) API for authenticating end users of an external consuming app. The user along with the username and password would need to provide a valid app identifier as part of the URL.This app identifier would already be mapped to the consuming app in the database.The user would be authenticated only on providing a valid app identifier.My understanding is that this can be achieved using a hidden input form field which would then be appended to the URL My View: class LoginView(View): """On successful authentication return the api key.Authentication only if valid api identifier found in the request""" def post(self, request): try: username = request.POST['username'] password = request.POST['password'] app_id = request.GET['app_identifier'] try: ConsumingAppInfo.objects.get(app_identifier=app_id) except Exception: raise Exception('Invalid app identifier found in the request') user = authenticate(username=username,password=password) if user is None: return HttpResponse('Invalid user credentials provided', status=400) request.session['user_id'] = user.id # Create API Key on first time login for the consuming user and return the same on any other subsequent # requests app_credentials,created = ConsumingAppAuth.objects.get_or_create(consuming_app_id=app_id, defaults={ 'api_key': str(uuid.uuid4())+'_'+str(datetime.now()), 'created_on': datetime.now(), 'consuming_app_id': app_id}) return JsonResponse({'api-key': app_credentials.api_key}) except Exception as e: return HttpResponse("Invalid request.Please verify the request parameters.Error Message: "+str(e), status=400) My Form: <form method="POST" action="/login"> <div class="form-group"> … -
How can I add dynamic background in a <div> tag?
I am a very beginner for coding please kindly let me know how can i load a photos to my template slide show? accoding to my template i have to load pictures as braground pictures. when they are sliding appeared an Image title and discription with a link My template is this . you can see clickin this [enter link description here][1][1]: https://colorlib.com/wp/template/eatery/ if i show you the html code which is behind {% for gallery in galleries %} <div class="slider-item " style=" background-image:url{{gallery.image.url}}"> <div class="container"> <div class="row slider-text align-items-center justify-content-center"> <div class="col-md-8 text-center col-sm-12 element-animate"> <h1>{{gallery.image_title}}</h1> <p class="mb-5"> {{gallery.image_description}} </p> <p> <a href="#" class="btn btn-white btn-outline-white">Get Started</a> </p> </div> </div> </div> </div> {% endfor %} if i loade the image with tag. {% for gallery in galleries %} <div class="slider-item "> <img class="image" src="{{gallery.image.url}}" /> <div class="container"> <div class="row slider-text align-items-center justify-content-center"> <div class="col-md-8 text-center col-sm-12 element-animate"> <h1>{{gallery.image_title}}</h1> <p class="mb-5"> {{gallery.image_description}} </p> <p> <a href="#" class="btn btn-white btn-outline-white">Get Started</a> </p> </div> </div> </div> </div> {% endfor %} then i can see only the image .othe details will desappear.. please help me with a solition. thank you -
Django chat application
I'm trying to make a chat application with Django channels. I've successfully build a one-to-one chat app but I'm not getting the idea for extending it to multiple one-to-one chat. Like, right now there's only two users logged in, but what if multiple users are chatting with one another. I'm stuck on how to prepare the model for that and inserting data in the database. So if anyone can help I'd appreciate that. -
Django Aggregate Query Include Zero Count
In my Django application, I'm trying to get a Count of all Student submitted Papers, including students who have submitted NO papers (represented as count=0). models.py class Student(models.Model): idstudent = models.AutoField(primary_key=True) student_name = models.CharField(max_length=250, null=False, blank=False, verbose_name='Student Name') class Paper(models.Model): idpaper = models.AutoField(primary_key=True) student = models.ForeignKey(Student, on_delete=models.PROTECT, null=False, blank=False) Query Attempt 1: Returns only Students who have submitted Papers papers = Paper.objects.order_by('submission_date') result = papers.values('student', student_name=F('student__student_name')).annotate(count=Count('student')).distinct().order_by('-count') print(result) <QuerySet [{'idstudent': 1, 'student_name': '\nMichael Jordan\n', 'count': 4}, {'idstudent': 2, 'student_name': '\nSteve White\n', 'count': 2}, {'idstudent': 3, 'student_name': '\nHillary Clinton\n', 'count': 1}]> Query Attempt 2: Returns Students who have submitted 0 Papers, but the Count for every other Student is 1 result = Student.objects.values('pk', student_name=F('student_name')) .annotate( count=Count( 'pk', filter=Q(pk__in=Paper.objects.values('student') ) ) ) ).order_by('-count') print(result) <QuerySet [{'idstudent': 1, 'student_name': '\nMichael Jordan\n', 'count': 1}, {'idstudent': 2, 'student_name': '\nSteve White\n', 'count': 1}, {'idstudent': 3, 'student_name': '\nHillary Clinton\n', 'count': 1}, , {'idstudent': 4, 'student_name': '\nDoug Funny\n', 'count': 0}, , {'idstudent': 5, 'student_name': '\nSkeeter Valentine\n', 'count': 0}]> Along the same lines as Attempt 2, I also tried the following using Sum(Case( which yielded the same result, as I recognized that the Attempt 2 raw SQL actually utilizes Case(When, but seems to only count when Student.pk is present in … -
How to design page with collapsing menu using Django
I want to design a web page similar to below page using Django framework. Please help with my project, enter image description here -
Django Template to PDF in Django version 3
Is there any module available to handle Djnago template to PDF conversion without any visual compromise? Note: I have used only Inline and Internal CSS in the template. My website will be hosted on heroku, a OS independent solution will be preferred. Thanks in advance. -
Django application in Docker gives FileNotFoundError: [Errno 2] No such file or directory: '/tmp/
I'm using Docker with python:3.7.6-slim image to dockerize the Django application. I'm using django-import-export plugin to import data in the admin panel which stores the uploaded file in temporary directory to read while importing. But on import it gives an error FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmppk01nf3d' Same is working when not using docker. -
Saleor error with elastic-search : **Found different types with the same name in the schema: JSONString, JSONString**
I am new on GraphQL, I am using saleor for e-Commerce with elastic-search (https://pypi.org/project/graphene-elastic/). import graphene from graphene_elastic import ( ElasticsearchObjectType, ElasticsearchConnectionField, ) from graphene_elastic.filter_backends import ( FilteringFilterBackend, SearchFilterBackend, HighlightFilterBackend, OrderingFilterBackend, DefaultOrderingFilterBackend, ) from graphene_elastic.constants import ( LOOKUP_FILTER_PREFIX, LOOKUP_FILTER_TERM, LOOKUP_FILTER_TERMS, LOOKUP_FILTER_WILDCARD, LOOKUP_QUERY_EXCLUDE, LOOKUP_QUERY_IN, ) # Object type definition class Post(ElasticsearchObjectType): class Meta(object): document = PostDocument interfaces = (Node,) filter_backends = [ FilteringFilterBackend, ] # For `FilteringFilterBackend` backend filter_fields = {. 'title': { 'field': 'title.raw', # Available lookups 'lookups': [ LOOKUP_FILTER_TERM, ], # Default lookup 'default_lookup': LOOKUP_FILTER_TERM, }, 'category': 'category.raw', } # For `OrderingFilterBackend` backend ordering_fields = { 'title': 'title.raw', 'created_at': 'created_at', } # For `DefaultOrderingFilterBackend` backend ordering_defaults = ( '-num_views', # Field name in the Elasticsearch document 'title.raw', # Field name in the Elasticsearch document ) # For `HighlightFilterBackend` backend highlight_fields = { 'title': { 'enabled': True, 'options': { 'pre_tags': ["<b>"], 'post_tags': ["</b>"], } }, 'content': { 'options': { 'fragment_size': 50, 'number_of_fragments': 3 } }, 'category': {}, } # Query definition class ElasticQuery(graphene.ObjectType): all_post_documents = ElasticsearchConnectionField(Post) This is working fine but when I combine the normal Query with ElasticQuery then give me error AssertionError: Found different types with the same name in the schema: JSONString, JSONString.: class Query( AccountQueries, AppQueries, … -
Django can't load javascript but load css (please)
Please your help.. I spent hours to understand it I started a very basic template with Django, and it can't find my js files, while it can find the css file - when both of them in static folder Thanks a lot! [11/Jun/2020 00:21:18] "GET /js/init.js HTTP/1.1" 404 2134 Not Found: /js/materialize.js [11/Jun/2020 00:21:18] "GET /js/materialize.js HTTP/1.1" 404 2155 Not Found: /js/init.js In Setting.py I have these settings: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') STATIC_ROOT = 'staticfiles' My Page index.html: This is my Project Dictionary: 3 folders - (1) home [the app] (2) project_folder (3) static - contain css, js, images -
Password reset not redirecting to template html file in django
I am trying to use a template html file for my password reset form. But it is not redirecting to my template file rather it is redirecting ti Django administration page. I don't want to use django administration page for resetting the password change link. password_reset_form.html: <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet"> <link rel="stylesheet" href="{% static 'employeeregistration/css/master.css' %}"> </head> <body> {% load bootstrap4 %} <div class="container title"> <h2 style="text-align:center; padding-top:100px;">Reset your password</h2> </div> <div class="container"> <form method="POST" action="{% url 'password_reset' %}"> {% csrf_token %} {{ form.as_p }} {% buttons %} <button type="submit" class="btn btn-primary">Send confirmation mail</button> {% endbuttons %} </form> </div> </body> </html> urls.py: from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name = 'registration' urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name="registration/login.html"), name='login'), path('password_reset/', auth_views.PasswordResetView.as_view(template_name="registration/password_reset_form.html"), name='password_reset'), # path('password_reset/password_reset_done/', auth_views.PasswordResetView.as_view(template_name="registration/password_reset_done.html"), name='password_reset_done'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('signup/', views.EmployeeSignUp.as_view(), name='signup'), ] views.py: from django.contrib.auth import login, logout from django.contrib.auth.mixins import(LoginRequiredMixin, PermissionRequiredMixin) from django.views.generic import (TemplateView,ListView, DetailView,CreateView, UpdateView,DeleteView) from django.urls import reverse_lazy from django.views import generic from django.views.generic import CreateView from . import forms class EmployeeSignUp(CreateView): """ Views for employee sign up """ form_class = forms.NewEmployeeRegistrationForm … -
How to test a customized clean method in Django ModelForm
I have the following ModelForm forms.py class MyModelForm(forms.ModelForm): my_file = forms.FileField() class Meta: model = MyModel def clean(self): form_file = self.cleaned_data['my_file'] file_name = form_file.name if MyModel.objects.filter(my_file_name=file_name).exists(): raise forms.ValidationError("This file already exists") Actually works but I need to add some unit tests to the customized clean method. Could you help me with that? Im using Django 2.0. Thanks in advance. -
How to disable auto reload django with deployed by IIS
I deployed a django project on IIS ,like this https://docs.microsoft.com/en-us/visualstudio/python/configure-web-apps-for-iis-windows?view=vs-2019 . But I found that the project start 2 sessions,the frontend request can receive by the 2 sessions,and it will cause something wrong.I think one of the session only for auto reload,and it can also receive request? When I start the project in cmd python manage.py runserver --noreload ,it is ok. How I can add this --noreload parameter in IIS settings? -
How to access html button values in django views
I am working on a django web application. The application has a few buttons inside a form. These buttons act like toggle switches. When a user submits the form, I want to access the values of the button in the django views. Take a look at the image below for better understanding. I designed the form with Bootstrap. this is the code to the HTML form. <form> {% csrf_token %} ... <p class='details-scrape'>Select the items you want to add to the list</p> <button type="button" class="btn btn-outline-primary" data-toggle="button" aria-pressed="false" autocomplete="off"> Tomato </button> <button type="button" class="btn btn-outline-primary" data-toggle="button" aria-pressed="false" autocomplete="off"> Eggs </button> <button type="button" class="btn btn-outline-primary" data-toggle="button" aria-pressed="false" autocomplete="off"> Bread </button> <button type="button" class="btn btn-outline-primary" data-toggle="button" aria-pressed="false" autocomplete="off"> Beans </button> <button type="button" class="btn btn-outline-primary" data-toggle="button" aria-pressed="false" autocomplete="off"> Cheese </button> <button type="submit" class="btn btn-primary btn-block btn-lg mt-5">Submit</button> </form> Here is my views.py code def index(request): if request.method == 'POST': # ------------- New code will come here ----------------- #access the values of the clicked buttons here... return redirect(index) else: return render(request, 'index.html') -
django- password reset link from email doesn't load templates but redirect to homepage
I'm using dj-rest-auth for the password reset I was able to receive an email with the link: mysite.com/password/reset/confirm/NTg/5h7-172d3be6f550a332e590/ Upon clicking the link, it would redirect to my frontend's (reactjs) home page when it should load the templates. This is my urls.py file: from django.urls import include, path, re_path from django.views.generic import TemplateView urlpatterns = [ path("auth/registration/", include("dj_rest_auth.registration.urls")), re_path(r"^password/reset/$", TemplateView.as_view(template_name = "password_reset.html"), name = 'password-reset'), re_path(r"^password/reset/confirm/$", TemplateView.as_view(template_name="password_reset_confirm.html"), name='password-reset-confirm'), re_path(r"^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$", TemplateView.as_view(template_name="password_reset_confirm.html"), name='password_reset_confirm'), path("auth/", include("dj_rest_auth.urls")), # User path("user/", UserDetailView.as_view()), path('accounts/', include('allauth.urls')), re_path(r"", TemplateView.as_view(template_name="index.html")), ] I have placed the templates in this directory: templates/account/password_reset.html templates/account/password_reset_confirm.html I have placed the templates in this manner because I also had a custom template for confirm email with allauth and putting the templates outside /account directory will cause conflict. I also called the templates in settings.py TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [ os.path.join(BASE_DIR, 'templates'), os.path.join(FRONTEND_DIR, "build"), ], # Added for "hybrid" architecture, to find front's index.html "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", ], }, }, ] I noticed that the link has the domain name as base URL mysite.com instead of 127.0.0.1:8000 Any idea what I'm missing here? Thanks -
How to update django database after deploying it on heroku?
I have deployed my Django quiz app on Heroku by connecting with GitHub. The link of the site is . Now I want to add new questions into the quiz? How to do this? (I have tried to change from the admin panel but after 30-40 minutes default questions are shown only.) -
Pickled model instance's Django version 3.0.3 does not match the current version 3.0.7
When upgrading Django version from Django 3.0.3 to 3.0.7. I get this error. RuntimeWarning: Pickled model instance's Django version 3.0.3 does not match the current version 3.0.7. value = pickle.loads(value) Is there any way to solve this issue to continue deployment without downtime -
TypeError: expected string or bytes-like object error for date range in Django
I am trying to filter CartItem objects based on their delivery dates. I define a startfilterdate and an endfilterdate that i format as a string in the same way my delivery_date's are formatted. Not sure what i am doing wrong. models.py class CartItems(models.Model): restaurant = models.ForeignKey(Restaurant, related_name='restaurant', on_delete=models.CASCADE) delivery_date = models.DateField(auto_now_add=False) views.py class RestaurantOrders(generics.ListAPIView): serializer_class = RestaurantOrderSerializer def get_queryset(self): restaurant_id = self.kwargs['pk'] startfilterdate = date.today() startfilterdate = startfilterdate.strftime("%Y-%m-%d") endfilterdate = date.today()+timedelta(days=9) endfilterdate = endfilterdate.strftime("%Y-%m-%d") orders = CartItems.objects.filter(restaurant_id = restaurant_id, delivery_date=[startfilterdate,endfilterdate]) Error: TypeError: expected string or bytes-like object -
Django Google Login setup without django.contrib.admin and django.contrib.auth
I am working as a newbie backend-engineer where the company requires you to follow this guideline where you comment out django.contrib.admin and django.contrib.auth in settings.py. Below is part of my settings.py INSTALLED_APPS = [ # 'django.contrib.admin', # 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'account', 'pin', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', #'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] They asked me to build a google social login function so I have been referring to a blog posting about setting up the google login. This is the blog: https://medium.com/@whizzoe/in-5-mins-set-up-google-login-to-sign-up-users-on-django-e71d5c38f5d5 Thankfully, there is no need for me to do anything about Django templates since I have front-engineers on it. However, all the google social login set-up tutorials I have found on google requires me to use django.contrib.admin or django.contrib.auth, which my boss has stipulated me not to use(again, this is our company rule). Thus, I am not able to proceed to chapter 8 of the above-mentioned blog tutorial. Is there any way to circumvent the usage of Django-admin and still be able to build the Google social login functionality? Thanks a lot in advance! -
Django view with related value in a list of list
I have a Creator and Listing model, in one of html template, I need to display the Listing attributes and the Creator attribute associated with it, I tried to get all unique creators and put that in set but my Listing is a list of lists, I need to get all attributes from both models which matches creator attribute and an element list of listing. I guess Django has a better approach for this, may be I am doing all wrong, here is what I tried so far. Model class Creator: first_name =models.CharField(max_length=200) last_name = models.CharField(max_length=200) photo = models.ImageField(upload_to='photos/%Y/%m/%d/') class Listing: creator = models.ForeignKey(Creator, on_delete=models.PROTECT) View def index(request): creators = set() listings_by_creator = set() for e in Listing.objects.filter(is_published=True).select_related('creator'): creators.add(e.creator) if any(x != e.creator for x in listings_by_creator ): listings_by_creator.add(e) context = {'zipped_app_list': zip(listings_by_creator, creators)} template {% if zipped_app_list %} {% for list_of_listing,creator in zipped_app_list %} ............. Now I need to display creator value and item with creator value in list_of_listing -
How can a programmer help the black lives matter movement?
I’m guessing this will get removed but I figure y’all answer all my other programming questions so why not ask? Anyone know of ways a programmer can help support the mission of Black Lives Matter or other movements seeking equality? -
How to download videos from Telegram API to local storage in Django
I want to download videos from Telegram API to my local storage using Python -
Django-Taggit tables not being created in PostgreSQL
Adding django-taggit to an existing Django app using PostgreSQL for db. I've used the django-taggit library before with no problem (but with a SQLite db). Makemigrations and Migrate commands look like they complete fine, but no taggit tables are created in PostgreSQL (in SQLite, two tables are created -> taggit_tag and taggit_taggeditem). So something is blocking the table creation. Django version = 3.0.7 Django-Taggit version = 1.3.0 Taggit has been included in Django settings: THIRD_PARTY_APPS = [ "crispy_forms", "allauth", "allauth.account", "allauth.socialaccount", "taggit", "django_countries", ] and models.py for the app: from django.db import models from django.urls import reverse from django.conf import settings from autoslug import AutoSlugField from model_utils.models import TimeStampedModel from taggit.managers import TaggableManager class Quote(TimeStampedModel): quote = models.TextField( "Quote", blank=False, help_text='Quote text', ) creator = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL, ) author = models.ForeignKey( 'authors.Author', related_name="author_quotes", on_delete=models.PROTECT, blank=False, null=True, ) tags = TaggableManager() def get_absolute_url(self): return reverse( 'quotes:detail', args=[str(self.id)] ) def __str__(self): return self.quote admin.py for the app includes: from django.contrib import admin from .models import Quote # admin.site.register(Quote) class QuoteAdmin(admin.ModelAdmin): list_display = ( 'quote', 'author', 'creator', 'tag_list', ) fields = [ 'quote', 'author', 'creator', 'tags', ] def get_queryset(self, request): return super().get_queryset(request).prefetch_related('tags') def tag_list(self, obj): return u", ".join(o.name for o in … -
Django Download csv after post request
I want to create an endpoint, in this endpoint its possible to send POST request, if the POST request is validated, then the page download a csv I created the serializer form to make a easy validation of the data received My problem is that the csv its easy downloaded in a HttpResponse, but i need neccesary to make a endpoint and a validation of the data in a post request. This are my files #urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^hello-view/', views.HelloApiView.as_view()), ] Serializers #serializers.py from rest_framework import serializers class HelloSerializer(serializers.Serializer): """Serializes a name field """ name = serializers.CharField(max_length=100) seller_id = serializers.CharField(max_length=100) def validate_name(self, dob): UnitOfMeasureName = ["Each", "Grams", "Ounces", "Pounds", "Kilograms", "Metric Tons"] if dob in UnitOfMeasureName: return dob else: raise serializers.ValidationError('Wrong username') And the views files In this file i created the export function to try to export the csv data, but doesnt works import csv from django.shortcuts import render from django.http import HttpResponse from rest_framework import viewsets from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from . import serializers class HelloApiView(APIView): def export(self, request): response = HttpResponse(content_type='text/csv') writer = csv.writer(response) writer.writerow(['First name', 'Last name', 'ID']) response['Content-Disposition'] … -
Django: violates not-null constraint on .create, However attribute is not part of that model
In Django, when trying to create a new record of my "Cast" model, I get the following error regarding the "image_cover" attribute. The problem is that "image_cover" is not a defined attribute of my "Cast" model. So I'm not sure where it's coming from. Any Help is appreciated! Thanks The Error: django.db.utils.IntegrityError: null value in column "image_cover" violates not-null constraint DETAIL: Failing row contains (33, FAKE CAST, 2020-06-11 00:34:59.421996+00, 2020-02-20 07:00:00+00, 1, 4, url, t, {}, null). ####BELOW IS A NOTE ``` 33 = *pk*, FAKE CAST = *name*, 2020-06-11 00:34:59.421996+00 = *modified_datetime*, 2020-02-20 07:00:00+00 = *created_datetime*, 1 = *book*, 4 = *created_by*, URL = *character_cast_url*, t = *public*, {} = *character_cast*, null = *aliases OR image_cover* ``` Details This error occurs as part of my coded application, but also when trying to create a "cast" via the built-in Django admin. For simplicity, I'll focus this question around the later. Probably Important: While "image_cover" is NOT part of the "Cast" model, The only place it does exist is as a charfield on the "Book" model (a foreign key on the "Cast" model). This seems slightly irrelevant, however, since when I create a cast via the Django Admin, I can simply …