Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'QuerySet' object has no attribute 'view_count'
Meanwhile using "view count" in my ecommerce project showing this error ('QuerySet' object has no attribute 'view_count') views.py class ProductDetailView(TemplateView): template_name = 'product-detail-view.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) slug_url = self.kwargs['slug'] product = Product.objects.filter(slug=slug_url) product.view_count += 1 product.save() context["products"] = product return context models.py class Product(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) image = models.ImageField(upload_to='products_img') wholesale_rate = models.PositiveIntegerField() amazon_rate = models.PositiveIntegerField() description = models.TextField() warranty = models.CharField(max_length=200, null=True, blank=True) return_policy = models.CharField(max_length=200, null=True, blank=True) view_count = models.PositiveIntegerField(default=0) -
Django ModelAdmin get_form 'NoneType' object is not callable
I am trying to add a new field to ModelAdmin, but get an error: @admin.register(FilmWork) class FilmworkAdmin(admin.ModelAdmin): fields = ('title', 'plot', 'ratings', 'film_creation_date', 'age_limit', 'link') def get_form(self, request, obj=None, **kwargs): form_factory = super(FilmworkAdmin, self).get_form(request, obj, **kwargs) form_factory.base_fields['Actors'] = forms.CharField(widget=forms.Textarea(), required=False) The error says: form = ModelForm(initial=initial) TypeError: 'NoneType' object is not callable I do not initialise any modelform anywhere. What am I doing wrong? -
django drf testing social oauth2 with google
I'm trying to test drf-social-oauth2's integration with Google via python manage.py test with the following test class: class DRFSocialOAuthIntegrationTest(TestCase): def setUp(self): self.test_user = UserModel.objects.create_user("test_user", "test@user.com", TEST_USER_PASSWORD) self.application = Application( name="Test Application", redirect_uris="", user=self.test_user, client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_PASSWORD, # https://github.com/jazzband/django-oauth-toolkit/blob/master/oauth2_provider/models.py ) self.application.save() # Every test needs a client. self.client = Client() def tearDown(self): self.application.delete() self.test_user.delete() def test_drf_social_oauth2_integration(self): '''Following testing steps found at curl -X POST -d "grant_type=convert_token&client_id=<django-oauth-generated-client_id>&client_secret=<django-oauth-generated-client_secret>&backend=google-oauth2&token=<google_token>" http://localhost:8000/auth/convert-token''' def convert_google_token(self): ''' Convert Google token to our access token curl -X POST -d "grant_type=convert_token&client_id=<client_id>&client_secret=<client_secret>&backend=google-oauth2&token=<google_token>" http://localhost:8000/auth/convert-token ''' return self.client.post( '/auth/convert-token', { 'grant_type': 'convert_token', 'client_id': self.application.client_id, 'client_secret': self.application.client_secret, 'backend': 'google-oauth2', 'token': <google_token> } ) That seems to work fine, but I have to keep feeding it the google_token by manually navigating to https://developers.google.com/oauthplayground/?code=<my_code>&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+openid&authuser=0&prompt=consent#: Once there, I click on the 'Exchange authorization code for tokens' button, get the access token, and paste that access token into the tokenparameter of the request inside convert_google_token(). This doesn't feel very automated. I'm not sure if I should just click the checkbox so that the access token is refreshed automatically and therefore never have to edit it in convert_google_token(). Or maybe I'm supposed to get that access token programmatically. But I believe that would entail getting the authorization code first, which … -
How to use async function based views in DRF?
Since Django now supports async views, I'm trying to change my code base which contains a lot of function based views to be async but for some reason its not working. @api_view(["GET"]) async def test_async_view(request): ... data = await get_data() return Response(data) When I send a request to this endpoint, I get an error saying: AssertionError: Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'coroutine'> Does DRF not support async views yet? Is there an alternative I can do to get this working? -
How to solve this error of django project?
Using the URLconf defined in personal_portfolio.urls, Django tried these URL patterns, in this order: admin/ ^media/(?P.*)$ The empty path didn't match any of these. from django.contrib import admin from django.urls import path from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += static(settings.MEDIA_URL , document_root=settings.MEDIA_ROOT) -
'core' is not a registered namespace Django
It is the first time i get this error while trying to create a slug. Can't seem to find out why and there's no other answer in here. Here is the models.py: from django.db import models from django.conf import settings from django.shortcuts import reverse class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() category = models.CharField(choices=CATEGORY_CHOICES, max_length=2, default="Sport") slug = models.SlugField(default="") def __str__(self): return self.title def get_absolute_url(self): return reverse("core:productpage", kwargs={ 'slug': self.slug }) Here is the views.py: from django.shortcuts import render from django.contrib import admin from .models import * from django.views.generic import ListView, DetailView def index(request): context = {'items': Item.objects.all()} return render(request, 'ecommerceapp/index.html', context) #returns the index.html template def shop(request): context = {'items': Item.objects.all()} return render(request, 'ecommerceapp/shop.html', context) def about(request): return render(request, 'ecommerceapp/about.html') def blog(request): return render(request, 'ecommerceapp/blog.html') def contact(request): return render(request, 'ecommerceapp/contact.html') def productpage(request): return render(request, 'ecommerceapp/product-single.html') -
Django ability to build management systems
Good day! I would like to ask if Django is suitable to build full systems like "Library management systems", "Booking systems", "client management system", etc. is it going to be sufficient to build such systems with Django or PHP would be a more suitable choice? and what would be the differences between the two choices with regard to such systems? -
How to link page from one app to another app
I'm new to django and I'm building a project "myblog" which has "blog" app in which I have created a base.html file which contain nav bar list of About and contact.I also created a "sendemail" app in same "myblog" project and I placed "email.html" contact file in templates directory of "sendemail" app, then what should be the href link in base.html file of "blog" app to access email.html file in "sendemail" app. This is base.html file in blog app of templates directory. {% load static %} <!DOCTYPE html> <html> <head> <title>Stand For Christ</title> <link rel="stylesheet" href="{% static 'css/base.css' %}"> <link href="https://fonts.googleapis.com/css?family=Roboto:400,700" rel="stylesheet"> <meta name="google" content="notranslate" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> </head> <body> <style> body { font-family: "Roboto", sans-serif; font-size: 17px; background-color: #fdfdfd; } .shadow{ box-shadow: 0 4px 2px -2px rgba(0,0,0,0.1); } .btn-danger { color: #fff; background-color: #1d2671; border-color: #1d2671; } .masthead { background: #1d2671; height: auto; padding-bottom: 15px; box-shadow: 0 16px 48px #E3E7EB; padding-top: 10px; } </style> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-light bg-light shadow" id="mainNav"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'home' %}" style="color:#1d2671;font-size:25px" >Stand For Christ Ministries</a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation" > <span class="navbar-toggler-icon"></span> … -
change_view() missing 1 required positional argument: 'object_id'
I am new in Django Framework and currently working on first project. I made a simple contact form it takes data from users and save it into database. Everything is working right. But when I login into my admin panel and go into the Contacts and click on the data that I received. I am getting error "change_view() missing 1 required positional argument: 'object_id'". my admin.py from home.views import contact from django.contrib import admin from home.models import Contact # Register your models here. admin.site.register(Contact) my models.py from django.db import models # Create your models here. class Contact(models.Model): name = models.CharField(max_length=30) email = models.EmailField() phone = models.CharField(max_length=10) desc = models.TextField() my views.py from home.models import Contact from django.shortcuts import render, HttpResponse from home.models import models # Create your views here. def home(request): # return HttpResponse("This is My Homepage") context = {"Name": "Harry", "Course" : "Django"} return render(request, 'home.html') def about(request): # return HttpResponse("This is My About page") return render(request, 'about.html') def projects(request): # return HttpResponse("This is My Projects") return render(request, 'projects.html') def contact(request): if request.method=='POST': print('This is POST') name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] desc = request.POST['desc'] # print(name, email, phone, desc) contact = Contact(name=name, email=email, phone=phone, desc=desc) … -
Django: redirect is still available even after deleting it
django newbie here. I applied redirect locally from /aboutt page to an /about page as a test example. I did it via /admin interface after adding all the required things into settings.py as listed here. Redirect worked, but after deleting it from /admin interface it's still available. I've also deleted the redirect using Python API via shell, but for some reason it's still redirecting. What could be the cause? Any ideas? -
Django - Reverse for 'saleitems' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<pk>[0-9]+)/$']
I know this question asked already many time but really i cant get any answer for this. Project is about saving invoice application where try to save SellInvoice and reverse SellItems path for adding items to invoice but not success: view.py class SellView(generic.View): template_name = "webapp/sellinovice.html" def post(self, request): try: data ={ 'type': "fa", 'totalprice':0, 'date': request.POST.get("factor_date"), } except: pass else: sellinovice = Sellinvoice(**data) sellinovice.save() return HttpResponseRedirect( reverse('webapp:sellitems' , args=(sellinovice.id ,)) ) models.py class Sellinvoice(models.Model): id = models.BigAutoField(db_column='Id', primary_key=True) # Field name made lowercase. type = models.TextField(db_column='Type', blank=True, null=True) # Field name made lowercase. totalprice = models.DecimalField(db_column='TotalPrice', max_digits=18, decimal_places=2) # Field name made lowercase. date = models.DateTimeField(db_column='Date') # Field name made lowercase. class Meta: managed = False db_table = 'SellInvoice' urls.py path('sellinvoice', views.SellView.as_view(), name='sellinvoice'), path('<int:pk>/', views.SellItemsView.as_view(), name='sellitems'), in html When i pass argument sellinovice.id like: <a class="nav-link active" href="{% url 'webapp:sellitems' sellinovice.id %}"> foo </a> faced this erorr: Reverse for 'sellitems' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[0-9]+)/$'] and if use sellinvoice primary key (for example 1967) as argument like : <a class="nav-link active" href="{% url 'webapp:sellitems' 1967 %}"> foo </a> it reversed to 'webapp:sellitems' and working perfect. What is wrong here? i was checking many question look … -
Blueprints in Flask vs Apps in Django
I am new to Flask and noticed something called Blueprint in Flask. I searched it and now I am using it in my Flask project. I had already worked in Django and I guess Blueprints are the Flask's equivalent of Apps in Django. Is my thinking and approach right? -
Why i get this error TemplateSyntaxError at / Invalid block tag on line 15: 'provider_login_js'. Did you forget to register or load this tag?
I want to connect login system with Facebook and Google . But i face this error my code is: {% load socialaccount %} {% providers_media_js %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div class="container" style="margin-top: 20px"> <button><a href="#">Google Login</a></button> <button><a href="{% provider_login_js "facbook" method="oauth2" %}">Facebook Login</a> </button> </div> </body> </html> -
I am working on django.The first code i am running only "Hello world" printing but it is not printing.The following problem ocurring
I am working on django.The first code i am running only "Hello world" printing but it is not printing.The following problem ocurring. -
Django Select ForeignKey filed for Admin using a condition
I'm working on a project using Python(3.7) and Django(3) in which I have implemented a few models. One of them is ReportsModel which has ForeignKey field to other models. Now I want to display other models data in ReportsModel admin. Here what I have tried so far: From models.py: class ReportsModel(models.Model): cdr_report = models.ForeignKey(CurrencyDistributionModel, on_delete=models.CASCADE, null=True, default=None) cme_report = models.ForeignKey(CurrencyManagementExpenditureModel, on_delete=models.CASCADE, null=True, default=None) cps_report = models.ForeignKey(CurrencyProcessingStorageModel, on_delete=models.CASCADE, null=True, default=None) cma_report = models.ForeignKey(CurrencyManagementAssetsModel, on_delete=models.CASCADE, null=True, default=None) def __str__(self): if self.cdr_report is not None: return self.cdr_report.RequestId elif self.cme_report is not None: return self.cme_report.RequestId elif self.cps_report is not None: return self.cps_report.RequestId elif self.cma_report is not None: return self.cma_report.RequestId To display the ForeignKey field in admin I'm using the django_reverse_admin package, here how I did that: From admin.py: class ReportAdmin(ReverseModelAdmin): report = None if ReportsModel.cdr_report is not None: report = 'cdr_report' elif ReportsModel.cme_report is not None: report = 'cme_report' elif ReportsModel.cps_report is not None: report = 'cps_report' elif ReportsModel.cma_report is not None: report = 'cma_report' search_fields = ['name'] inline_reverse = [report] inline_type = 'stacked' admin.site.register(ReportsModel, ReportAdmin) now in the admin, it only works for the cdr_report, when I add a report of type cme_report, I'm getting the RequestField correctly, but the cme_report field is … -
TypeError: data.allEmployers.map is not a function
I am getting this error when i try fetching data to React Frontend using GraphQL from Django Backend Error enter image description here This is the react code to fetch in the React frontend side enter image description here -
Django Messages do not disappear
I'm facing the issue that on some browsers my Django messages do not dissapear, for example If a new post gets created the side indicates with a message that the new post has been successfully created. If I reload the page the message doesn't disappear and keep showing up, why that? The issue goes so far that messages are stacking after using the side for a while you only see messages xD ... Can smb help with this? Is this just because of the browser that being used? This is how I display my messages: <div class="messages"> {% if messages %} {% for message in messages %} <span><li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li></span> {% endfor %} {% endif %} </div> Thanks in advance -
Python manage.py runserver command not working and error message not specific
I just started learning Django this day and I got stuck because when I ran python manage.py runserver it gave this message.... I've tried python manage.py migrate still nothing. I've waited an hour to see if it makes a difference and it doesn't. It seems stupid but I've been stuck here for a while. I have activated virtual environments and added python to Path ... I don't know what went wrong. File "C:\Users\owner\Envs\test\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute("args, *cmd_options) File "C:\Users\owner\Envs\test\lib site-packages\django\core management commands \runserver.py", line 61, in execute super().execute(*args, **options) File "C:\Users\owner\Envs\test\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\owner\Envs\test\lib\site-packages\django\core management commands \runserver.py", line 68, in handle if not settings. DEBUG and not settings.ALLOWED_HOSTS: File "C:\Users\owner\Envs\test\lib\site-packages\django\conf\_init__.py", line 83, in getattr self._setup(name) File "C:\Users\owner\Envs\test\lib\site-packages\django\conf\_init__.py", line 70, in _setup self. wrapped = Settings(settings_module) File "C:\Users\owner\Envs\test\lib\site-packages\django\conf\_init_.py", line 177, in __init__ mod = importlib. import_module(self.SETTINGS_MODULE) File "c:\python\python39\lib\importlib __init__.py", line 127, in import_module return _bootstrap. gcd_import(name [level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _ecd_import File "<frozen importlib. bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>" line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named "C:\Python' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\owner\Desktop\goals\viva … -
How to store paypal transaction email and id in my database
Here I am integrating braintee paypal payment in my django app. The payment works fine. But the problem I got is while saving the paypal transaction email and payer Id in my database. While printing the result I can get payment_instrument_type: 'paypal_account', But I am not being able to get this account email and payer id in my result. Is there anyone who can help me on this ? def braintree_payment(customer_kwargs, amount, nonce): gateway = braintree_config() customer_create = gateway.customer.create(customer_kwargs) result = gateway.transaction.sale({ "amount": amount, "payment_method_nonce": nonce, "options": { "submit_for_settlement": True, } }) return result view nonce_from_the_client = request.POST['payment_method_nonce'] customer_kwargs = { "first_name": payment_donar.first_name, "last_name": payment_donar.last_name, "email": payment_donar.email, } amount = payment_donar.donation_amount result = braintree_payment( customer_kwargs=customer_kwargs, amount=amount, nonce=nonce_from_the_client ) if result.is_success: data = { 'transaction_id': result.transaction.id, 'currency_iso_code': result.transaction.currency_iso_code, 'last_4': result.transaction.credit_card_details.last_4, 'card_type': result.transaction.credit_card_details.card_type, 'expiration_month': result.transaction.credit_card_details.expiration_month, 'expiration_year': result.transaction.credit_card_details.expiration_year, 'customer_location': result.transaction.credit_card_details.customer_location, 'cardholder_name': result.transaction.credit_card_details.cardholder_name, 'merchant_account_id': result.transaction.merchant_account_id, 'network_transaction_id': result.transaction.network_transaction_id, } Model.objects.create(**data) return redirect('home') this is the transaction result <SuccessfulResult {transaction: <Transaction {id: 'n0gxdkcf', graphql_id: 'dHJhbnNhY3Rpb25fbjBneGRrY2Y', additional_processor_response: None, amount: Decimal('10.00'), authorization_adjustments: [], authorization_expires_at: datetime.datetime(2021, 2, 23, 13, 59, 3), avs_error_response_code: None, avs_postal_code_response_code: 'A', avs_street_address_response_code: 'A', channel: None, created_at: datetime.datetime(2021, 1, 24, 13, 59), credit_card_details: <CreditCard {token: None, bin: None, last_4: None, card_type: None, expiration_month: '', expiration_year : … -
Name Error by python, name 'ArticleDetailView' is not defined
this is the problem File "C:\simpleblog\ablog\myblog\urls.py", line 8, in path('article/int:pk',ArticleDetailView.as_view(), name='article-detail'), NameError: name 'ArticleDetailView' is not defined my urls.py from django.urls import path from .views import HomeView urlpatterns = [ path('article/<int:pk>',ArticleDetailView.as_view(), name='article-detail'), ] In my views.py I have clearly defined it. below is my views.py from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post class HomeView(ListView): model = Post template_name = 'home.html' class ArticleDetailView(DetailView): model = Post template_name = 'article_details.html' So please help me to solve it. -
Error during deploying django app in Heroku
I am trying to deploy a Django application to Heroku. When I followed the documentation and tried the command git push heroku master, I am getting an error: failed to push some refs to 'https://git.heroku.com/sleepy-eyrie-25993.git'. I searched online and tried to use git pull. But it didn't work. I also tried using git push -f heroku master, but still getting the same error. Is there any other way to do it? I followed this doc https://devcenter.heroku.com/articles/python-support -
Backend Cache not Shared with Django
I've created a python package that does some expensive computation and uses lru_cache in order to save the result so the user don't have to wait too long for the result being calculated. import cachetools.func @cachetools.func.ttl_cache(ttl=60*60) def main_function(): # some expensive computations return result The code works pretty well when I call directly the function from a file or from the Python Shell, my issue is that when calling this package from my Django project, somehow it doesn't look up the already cached results. In my __init__.py file I'm calling main_function and then I try to call it again from my Django project but it does not return the cached response, instead it runs the function again. The package that I've created has a complex cache system, it works nice so I think this may be a problem with Django, that somehow I need to manage the caches from my Django project, any suggestions on how can I solve this? -
(NoReverseMatch at / Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['<int:id>/']). please help me to remove this error
It is a multiple image program in which we can add multiple image at one time to see grouped photos. Error during template rendering In template C:\Users\a\dev\mysite\templates\base.html, error at line 15 I am able to open my admin panel but i am not able to my files. thus please help me to find error: models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=120) description = models.TextField() image = models.ImageField(upload_to='products/', null=True, blank=True) def __str__(self): return self.title class PostImage(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to='images/') def __str__(self): return self.post.title views.py from django.shortcuts import render, get_object_or_404 from .models import Post, PostImage def blog_view(request): posts = Post.objects.all() return render(request, 'blog.html', {'posts':posts}) def detail_view(request, id): post = get_object_or_404(Post, id=id) photos = PostImage.objects.filter(post=post) return render(request, 'detail.html', { 'post':post, 'photos':photos, }) admin.py from django.contrib import admin from .models import Post, PostImage class PostImageAdmin(admin.StackedInline): model=PostImage @admin.register(Post) class PostAdmin(admin.ModelAdmin): inlines = [PostImageAdmin] class Meta: model=Post @admin.register(PostImage) class PostImageAdmin(admin.ModelAdmin): pass base.html <!DOCTYPE html> <html lang='en'> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha2/css/bootstrap.min.css" integrity="sha384-DhY6onE6f3zzKbjUPRc2hOzGAdEf4/Dz+WJwBvEYL/lkkIsI3ihufq9hk9K4lVoK" crossorigin="anonymous"> <title>Multi Image Tutorial</title> </head> <body> <div class="container py-4"> {% block content %} {% endblock %} </div> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </body> </html> … -
withour server restarting changes not apply
after changing somthing in django for example views or models No changes are made without a restart. after restarting ubuntu / plesk server changes are appled. pls help me is there a way to apply changes on django withour server restart. -
Rendering images in Django ModelForm instead of __str__ representation
I have the following django models / forms / views / html setup. So I am rendering the InputFileForm in the html and the user should select from dropdown list a face_file that is saved in the Face model (preloaded via fixtures). I would like to have the face_file images to be rendered in the dropdown (alternatively a radio select would be fine as well) instead of the image str names - as it currently looks like the following: Image of current dropdown So in short: I would like to have an image rendered in the dropdown instead of the "Face 1", "Face 2",... Thanks in advance for your help! class Face(models.Model): face_id = models.AutoField(primary_key=True) name = models.CharField(max_length=64) face_file = models.ImageField(upload_to='../media/faces', blank=True, null=True) def __str__(self): return self.name class InputFile(models.Model): input_id = models.AutoField(primary_key=True) input_flatlay_file = models.ImageField(upload_to='../media/flatlays', blank=True, null=True) input_face_file = models.ForeignKey(Face, null=True, blank=True, on_delete=models.CASCADE, related_name="inputs_using_this_face") input_user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE, related_name="user_inputs") class Prediction(models.Model): prediction_id = models.AutoField(primary_key=True) prediction_inputs = models.ForeignKey(InputFile, null=True, blank=True, on_delete=models.CASCADE, related_name="prediction_inputs") output_lookbook_file = models.ImageField(upload_to='../media/lookbooks', blank=True, null=True) prediction_user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE, related_name="user_predictions") I have a ModelForm for InputFile: class InputFileForm(forms.ModelForm): class Meta: model = InputFile fields = ['input_flatlay_file','input_face_file'] In my views.py: def prediction(request): form=forms.InputFileForm() if request.method == …