Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
RelatedObjectDoesNotExist at /register/ User has no schoolprofile
hello am trying to create a school profile when a user( schooluser) registers,the profile is created but giving the error RelatedObjectDoesNotExist at /register/User has no schoolprofile.and the strange thing is that in the admin the model fields when you try to edit any field of the created school profile they are empty. help. models.py class SchoolProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,related_name='schoolprofile') schoolname = models.CharField(max_length=200) region = models.CharField(max_length=200) district = models.CharField(max_length=200) code = models.CharField(max_length=20) logo = models.ImageField(default='default.jpg', upload_to='logos') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import SchoolProfile class SchoolRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class SchoolProfileForm(forms.ModelForm): class Meta: model = SchoolProfile fields = ['schoolname', 'code', 'region'] views.py from .forms import SchoolRegisterForm,SchoolProfileForm def register(request): if request.method == 'POST': form = SchoolRegisterForm(request.POST) s_profile_form = SchoolProfileForm(request.POST) if form.is_valid() and s_profile_form.is_valid(): form.save() request.user.refresh_from_db() s_profile_form = SchoolProfileForm(request.POST, instance=request.user.schoolprofile) s_profile_form.full_clean() s_profile_form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in!') return redirect('dashboard') else: form = SchoolRegisterForm() s_profile_form = SchoolProfileForm() return render(request, 'accounts/register.html', {'form': form,'s_profile_form':s_profile_form}) -
It is possible send a http request of a view in another view?
I would want to send a http request in a view. The request URL has relation to another view. Somthing like this: class View_A(APIView): def get(self, request): return Response({'foo':'bar'}) class View_B(APIView): def post(self, request): # Here I would want to send a request to View_A, something like this: request_view_A = View_A.as_view().get('URL_FROM_VIEW_A') # ... return Response({'foo2':'bar2'}) I have seen this question which has a different focus, however don't working for me because http method from View_A (get) is different to http method from View_B (post). -
Crypting/decrypting user passwords used for basic auth in Django
I have a Django application. Via the app, users can access a third party API which uses basic auth credentials. I was planning on adding a section where user can add their credentials to said Api, which would then be stored to the database as a basic auth header. But then I facepalmed as obviously encoding them as base64 can be decoded to plain text. What would be the best way to achieve a encrypting/decrypting mechanism in Django for this purpose? In this case, the credentials would be encrypted when saved to the database and encrypted when they are fetched from there. -
Render personalized data in template against django.contrib.auth.models.User
When my users answer a challenge, I want it to be stored against their profile. When they log in, they will see an index of challenges and it will show which ones have been answered. Like this: Trivia What is the capital of France? - answered How high is the Empire State building? Maths What is 2+2 - answered My model for the above contains Category and Challenge. I am also using Django auth User for log-in. To get the 'answered' bit, I thought I could add a User_Challenge model in models.py: class User_Challenge(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) challenge = models.ForeignKey(Challenge, on_delete=models.CASCADE, null=True) answered = models.BooleanField(default=False) But because you can't do filtering in a template, I am finding this really cumbersome. Is there a simpler way to associate challenge status against a user profile without introducing another table? I find that passing Category, Challenge, User and User_Challenge from my view to my template too complicated since you can't execute functions in templates. Thanks in advance! -
is there performance difference in using model name istead of object in ForeignKey?
Well Django docs do not say anything about performance or particular situations when to use model name class SomeModel(Model): related_model = ForeignKey('RelatedModel') or the class itself class SomeModel(Model): related_model = ForeignKey(RelatedModel) in my experience is much better to use the model name to avoid import loops but does it have any particular impact on app's live peformance or just server startup takes longer? Can't really think of a test that would reliably check the performance thus the quetion PS I know the similar answer was asked but it says nothing about real performance. -
Getting RelatedObjectDoesNotExist error accessing field on custom form
I'm relatively new to Django (and python in general) and I'm working on project I have not coded myself. Specifically I'm trying to save some information from a form via POST but I get a RelatedObjectDoesNotExist error when accessing the user field defined in my custom Profile model and I don't get why. Here is my views.py: def conferma(request): family = request.user.profile.family # cannot be null already_confirmed = request.user.profile.conferma_inviata if(already_confirmed == False): ProfileFormSet = modelformset_factory( Profile, form=ConfirmForm, extra=0) if request.method == 'POST': formset = ProfileFormSet( request.POST, queryset=Profile.objects.filter(family=family)) if formset.is_valid(): for form in formset: f = form.save(commit=False) f.conferma_inviata = True f.save() If I try to access f.user I get a RelatedObjectDoesNotExist error and I need that information in order to save the form. Here is my forms.py: class ConfirmForm(forms.ModelForm): class Meta: model = Profile fields = ('user', 'conferma_pranzo', 'conferma_sera', 'conferma_inviata',) def __init__(self, *args, **kwargs): super(ConfirmForm, self).__init__(*args, **kwargs) self.fields['user'].required = False self.fields['conferma_inviata'].required = False Here is my models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_day = models.BooleanField(default=True) family = models.TextField(max_length=100, blank=True) conferma_pranzo = models.BooleanField(default=False) conferma_sera = models.BooleanField(default=False) conferma_inviata = models.BooleanField(default=False) def __str__(self): return self.user.first_name + ' ' + self.user.last_name I have already checked the Database but the Profile records are correctly stored … -
drf-spectacular is using the wrong AutoSchema to generate Swagger
Previously I was using drf-yasg but want to update to use OpenAPI 3. I am trying to switch over to drf-spectacular. Following the instruction, I ran pip install drf-spectacular, I've removed all references to the drf-yasg package, and updated Settings.py as follows: INSTALLED_APPS = [ ... "drf_spectacular", ] REST_FRAMEWORK = { "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema", } When I use the CLI to generate the schema, I get the bellow AssertionError. If anyone has run into this problem before and has any insight, it would be much appreciated! I'm using Python 3.7, Django 3.0, Django Rest Framework 3.11, and DRF Spectacular 0.10.0. Traceback (most recent call last): File "manage.py", line 23, in <module> main() File "manage.py", line 19, in main execute_from_command_line(sys.argv) File "/opt/anaconda3/envs/dev/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/opt/anaconda3/envs/dev/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/anaconda3/envs/dev/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/opt/anaconda3/envs/dev/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/opt/anaconda3/envs/dev/lib/python3.7/site-packages/drf_spectacular/management/commands/spectacular.py", line 50, in handle schema = generator.get_schema(request=None, public=True) File "/opt/anaconda3/envs/dev/lib/python3.7/site-packages/drf_spectacular/generators.py", line 187, in get_schema paths=self.parse(request, public), File "/opt/anaconda3/envs/dev/lib/python3.7/site-packages/drf_spectacular/generators.py", line 160, in parse 'Incompatible AutoSchema used on View. Is DRF\'s DEFAULT_SCHEMA_CLASS ' AssertionError: Incompatible AutoSchema used on View. Is DRF's DEFAULT_SCHEMA_CLASS pointing to "drf_spectacular.openapi.AutoSchema" or any other drf-spectacular compatible … -
How to use wkHTMLtoPDF with docker-compose and Django
I need help to understand how to use wkHTMLtoPDF with docker-compose and then apply it in Django. I tried to build docker-compose: version: '3.7' services: db: image: postgres:13.0 restart: always environment: POSTGRES_PASSWORD: trytofindme ports: - 15432:5432 adminer: image: adminer restart: always ports: - 8020:8080 wkhtmltopdf: image: diegovieira/wkhtmltopdf:latest volumes: - .:/data It was the first image of wkhtmltopdf, that I found and it was working. When I type docker-compose up - everything runs correctly, but at least i see that message: server_wkhtmltopdf_1 exited with code 1 Does someone know how to solve this problem? And then how to use it in Django. For example: I need to convert HTML to PDF simple page with text and need to save it in "../project-name/media/pdf. I will be insanely grateful for your help. -
Django ModelMultipleChoiceField - Can't unselect all checkboxes
I'm passing a checklist form to my template. When no items are selected, there is no request.POST object passed to the view. This means I can't deselect all existing checkboxes and hit save. How can the view detect that the request.method is "POST" when no data is submitted? Code below: View.py if request.method == "POST": form = AssignedUsersForm(request.POST, instance=assignment) if form.is_valid(): assignment = form.save(commit=False) assignment.save() form.save_m2m() return redirect('assignment', id) -
Method Not Allowed (POST): /profiles/flash/ Method Not Allowed: /profiles/flash/
Well here i am simply trying to add follow toggle button in django tmeplate with django and jqeury ajax but its showing me an error Method Not Allowed (POST): /profiles/flash/ Method Not Allowed: /profiles/flash/. I dont get it where i am making mistake. Even i triple check my code. html <form method='post'> <button class="btn {% if is_following %}btn-warning{% else %}btn-primary{% endif %}" id="like-button" toggle="{{user.userprofile}}">{% csrf_token %} {% if is_following %}Unfollow {% else %}Follow{% endif %} </button> </div> </form> jquery,ajax <script> var user = $('#test').attr('user'); console.log(user,'test purpose'); $(document).on('click', '#follow-button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "profiles:follow" %}', data: { user_toggle: user, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function (json) { document.getElementById("is_following").innerHTML = json['is_following'] }, error: function (xhr, errmsg, err) { } }); }) </script> urls.py app_name = 'profiles' urlpatterns = [ path('follow/',follow,name = 'follow'), ] views.py def follow(request): if request.POST.get('action') == 'post': result = '' profile_ = UserProfile.objects.get(user__username__iexact=request.user.username) is_following = False username_to_toggle=request.POST.get('user_toggle') follower = profile_.follower.filter(username__iexact=username_to_toggle).first() if follower: profile_.follower.remove(follower.id) else: new_follower = User.objects.get(username__iexact=username_to_toggle) profile_.follower.add(new_follower.id) is_following = True return JsonResponse({'is_following': is_following, }) if more information is require than tell me in a comment section. will update my question with that information. -
Jinja Statement ( {% for loop%}) cannot be read on line server
I deployed an ecommerce website on the live server using heroku but having issue with product images as they are not being displayed. The website is working fine on the local host but causing problem when being deployed online. I inspected the html code and found out that the live website doesn't show the jinja for loop template which is added to the html file. Can anyone please guide me on how to solve this issue? Here is the link to the website,https://ahad-ecommerce-website.herokuapp.com/ and also the code snippet for the html file main.html {% load static %} <!DOCTYPE html> <html> <head> <title> Ecom </title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css'%}"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1" /> <script type="text/javascript"> var user = '{{request.user}}' function getToken(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getToken('csrftoken'); function getCookie(name) { … -
purchased_products = validated_data.pop("products") KeyError: 'products'
I have a M2M relationship between Product and Purchase. What I am trying to achieve is when a purchase is made, to also fill the PurchasedProduct(the through model) model. But every time I send the data to the API and I try to access the products key in the serializer from the validated_data a keyError exception is thrown but if I return the validated_data for the purpose of debugging the product key is part of the response. djangorestframework==3.11.0 django==2.2.10 class Product(Model): name = CharField(max_length=20, unique=True) date_added = DateTimeField(default=now) models.py class Purchase(Model): manager = ForeignKey('users.User', on_delete=PROTECT, related_name='purchases') quantity = DecimalField(max_digits=6, decimal_places=2) products = ManyToManyField('branches.Product', through='PurchasedProduct', through_fields=('purchase', 'product')) amount_fc = IntegerField(default=0) amount_usd = IntegerField(default=0) total_amount = IntegerField(default=0) date_purchased = DateTimeField(default=now) class PurchasedProduct(Model): purchase = ForeignKey('Purchase', on_delete=CASCADE, related_name="to_products", blank=True) product = ForeignKey('branches.Product', on_delete=CASCADE, related_name='purchases') unit_price = DecimalField(max_digits=12, decimal_places=4, default=0.00) quantity = DecimalField(max_digits=5, decimal_places=2) amount_fc = DecimalField(max_digits=10, decimal_places=2) date_purchased = DateTimeField(default=now) serializer.py class PurchasedProductSerializer(ModelSerializer): class Meta: model = PurchasedProduct fields = [ "id", "purchase", "product", "unit_price", "quantity", "amount_fc", "date_purchased" ] class PurchaseSerializer(ModelSerializer): # https://github.com/encode/django-rest-framework/issues/5403 products = PurchasedProductSerializer(source="to_products", many=True) class Meta: model = Purchase fields = [ "id", "manager", "quantity", "amount_fc", "amount_usd", "total_amount", "products", "date_purchased" ] def create(self, validated_data): purchased_products = validated_data.pop("products") manager = validated_data.pop('manager') … -
How do I implement a simple Python program in my Django web app?
I have this simple Python code: import random a = random.randint(0,101) if a >= 0 and a <= 10: return(a, "There is a 10% chance a is between 0, 10") else: return(a, "There is a 90% chance a is between 11, and 100") I want to be able to run and display the output from the program on a web app made with Django? For example that I have a Web page with a button. And when I click the button the programm is being run and the return is displayed next to the button. -
How to display a ForeignKey field in a ModelForm with no default value?
I need to create a form for Player that has Role objects as choices in a dropdown field, but with their string field shown instead. models.py class Player(models.Model): role = models.ForeignKey(role) ... class Role(models.Model): designation = models.CharField() forms.py class PlayerForm(ModelForm): class Meta: model = Player fields = ['role'] Say I have three role objects with these as their designations, respectively: Warrior, Mage, Rouge, how can I display it in a PlayerForm instance as a dropdown, with no default value so the user has to choose one? Currently this code displays the objects as the objects themselves (Role object (1), Role object (2), ...) -
I have 2 classes Teams and ToDo, and 2 serializers and the code in View. In a query set i want as outcome "the team ID or PK which owns the Todo
class Teams(models.Model): name = models.CharField(max_length=20) file = models.FileField(upload_to='team_icons', null='True', blank='True') members = models.ManyToManyField(User, related_name='member') class ToDo(models.Model): title = models.CharField(max_length=200) description = models.TextField() owner = models.ForeignKey('auth.user', related_name='todos', on_delete=models.CASCADE) file = models.FileField(upload_to='uploads', null='True', blank='True') teamOwner = models.ForeignKey("Teams", related_name='team', on_delete=models.CASCADE) ==> the serializers class ToDoSerializer(serializers.ModelSerializer): class Meta: fields= ( 'id', 'title', 'description', 'owner', 'file', 'teamOwner', ) model = ToDo class TeamSerializer(serializers.ModelSerializer): # name = serializers.SerializerMethodField() class Meta: fields = ( 'id', 'name', 'file', ) model = Teams And finally the view code of the query: class ListTodo(generics.ListCreateAPIView): queryset = models.ToDo.objects.all() serializer_class = serializers.ToDoSerializer def get_queryset(self): owner_queryset = self.queryset.filter(Teams) return owner_queryset Every combination in .filter(xxx) fails. ik want as outcome the Team ID or PK number in the return queryset. Iam a beginner so i hope i explained my problem in a clear way -
Why django-rest-auth SocialLoginView is not working?
https://django-rest-auth.readthedocs.io/en/latest/installation.html here is the official docs about social login in django-rest-auth. they say the way to make the LoginView(GithubLogin, FacebookLogin, etc..) inheriting SocialLoginView like this. from allauth.socialaccount.providers.github.views import GitHubOAuth2Adapter from allauth.socialaccount.providers.oauth2.client import OAuth2Client from rest_auth.registration.views import SocialLoginView class GithubLogin(SocialLoginView): adapter_class = GitHubOAuth2Adapter callback_url = CALLBACK_URL_YOU_SET_ON_GITHUB client_class = OAuth2Client but when i try to access the url with this as as.view(), they always say { "non_field_errors": [ "View is not defined, pass it as a context variable" ] } I tried the best. I have been suffering it for a few days. plz anybody save my life.. What's wrong with it? I've searched a lots but there wasn't any good answer for me. -
How do i get the context to test my view page?
I'm trying to test my search results to check the response when there are no results. this is the function in my view: def get_context_data(self, *args, **kwargs): result = super().get_context_data(**kwargs) query = self.request.GET.get('q') result['book'] = get_object_or_404(books,ISBN = query) return result this is my test class and function class Test_Search_results_view(TestCase): def test_no_results(self): response1 = self.client.get('/TextSearch/results1/?books=new&q=9780815345244') response2 = self.client.get('/TextSearch/results2/?books=new&author=Bruce+Alberts&Book+Name=Molecular+Biology+of+the+Cell&edition=6') self.assertEqual(response1.status_code, 404) self.assertEqual(response2.status_code, 404) self.assertQuerysetEqual(response2.context['book'],[]) but i keep getting this error self.assertQuerysetEqual(response2.context['book'],[]) File "C:----\context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'book' how do I check if my book query got empty results? -
Connect IIS FastCGIModule to Executable on NAS
I have a FastCGIModule handler that points to Python executables on a hard drive on the server. This works, and my Django site is displayed. When I change the executables section of the handler mapping to point to a NAS mapped to a drive on the server, I get this error when I navigate to the site: HTTP Error 500.0 - Internal Server Error An unknown FastCGI error occurred I am using the full DFS path in the path to the executable, because just using the mapped drive letter results in The specified executable does not exist on the server. How do I create a handler mapping in IIS that points to executables on a NAS? -
Django with Haskell
I have a program written in Haskell that does resource analysis, and I would like to build a web interface for this program. I will also start learning Django, for professional reasons, and it would be very convenient if I could combine both these goals, and build a web interface for this program using Django. What I would like to know is, is this even possible? At the moment I know nothing about Django, other than the fact that it is a python web framework. Keep in mind that this will be a very simple web interface, with almost no user interaction, it will be a simple "Insert you code here" and "This is the result". And because I have little hope that the above would work, what Haskell framework would you recommend to build this interface? Thank you! -
How to pass variables in a paramter of an html component with django
I'm today working on a django porject composed of only one application (an encyclopedia), but I am facing some struggles. I have a view named index that is displaying all the encyclopedias that the user can access to. On each file, I want to add a link to can redirect the user to the concerned encyclopedia. To do that, in my index view, I am calling a function that lists all the encyclopedias that we can have access to. This list will be used for rendering an html page. The problem that I am facing is on this html page named index.html. I am trying to pass the name of each encyclopedia in the href parameter for my link. Here is my html code: {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block body %} <h1>All Pages</h1> <ul> {% for entry in entries %} <li><a href ="/{{entry}}">{{ entry }}</a></li> {% endfor %} </ul> {% endblock %} P.S: my django project is based on a base code provided by : https://cs50.harvard.edu/web/2020/projects/1/wiki/ -
How can solve a DeleteView problem in Django concerning a foreign key?
I have to apps (DMS and ObjPDW). The first one is for managing some files. In this I have a model DMS_Dokument, which includes a FileField and some more. Recently I added a new model to the latter app (ObjPDW) and I included a foreign key to Dokument_DMS: class Zahlungsstrom(models.Model): zahlung_bezeichnung = models.CharField(max_length=550, blank=False, null=False, verbose_name="Bezeichnung") zahlung_betrag = models.DecimalField(max_digits=7, decimal_places=2, default=None, blank=True, null=True) zahlung_dok_fk = models.ForeignKey(dmsdok.DMS_Dokument, on_delete=models.SET_DEFAULT, default=None, null=True, blank=True, verbose_name="Zahlungsdokument") Now I wanted to delete a DMS_Dokument object (using the DeleteView CBV), but it gives me a "prorammingerror": "(1146, "Table 'DB_DMS.ObjPDW_zahlungsstrom' doesn't exist")" I have no clue what the problem is. :( -
Django filters update query when user changes value in dropdown filter
I have a filter that is for my model that is a select of all the values in that columns. I would like to make it so that when the user select a value from the select it automatically filters the data without the need for a submit button. I believe I need an onclick attribute for the select field but I cant figure out how to set that up for filter forms. filters.py import django_filters from django_filters import CharFilter, AllValuesFilter from .models import * class SetFilter(django_filters.FilterSet): name = CharFilter(field_name='name', lookup_expr='icontains', label='', ) type = AllValuesFilter(field_name='type', choices=Set.objects.values_list('type', flat=True).distinct(), label='', ) class Meta: model = Set fields = '' exclude = [''] sets.html: <td class="d-none d-xl-table-cell">{{ myFilter.form.type }}</td> -
Django Model For An About Page
I have an about page which contains some information that I want editable through Django's admin interface, I created the following model for the page: from django.db import models class About(models.Model): office_address = models.CharField(max_length=100) phone_one = models.CharField(max_length=16) phone_two = models.CharField(max_length=16, null=True, null=True) mail_one = models.EmailField(max_length=40) mail_two = models.EmailField(max_length=40, null=True, blank=True) I have a couple of questions though. Number one, is what I am doing the right way? If it were you, how would you store those? What should I name my model? "About" is obviously not good, even in a plural case it will be Abouts! -
Execute function using curl
I have a function: def foo(request): qs = Example.objects.all() for query in qs: query.param += 10 query.save(update_fields=['param']) return redirect('main:index') urlpatterns = path('foo/', foo) When i use http://localhost:8000/foo in the browser, the function executes just fine, but when i try to execute it in the console using curl http://localhost:8000/foo, the function doesn't work, even though it accesses the server: * Trying 127.0.0.1:8000... * TCP_NODELAY set * Connected to localhost (127.0.0.1) port 8000 (#0) * Server auth using Basic with user 'admin' > GET /foo HTTP/1.1 > Host: localhost:8000 > Authorization: Basic YWRtaW46TTd0d2E5bWo= > User-Agent: curl/7.68.0 > Accept: */* > * Mark bundle as not supporting multiuse < HTTP/1.1 301 Moved Permanently < Date: Mon, 26 Oct 2020 19:42:20 GMT < Server: WSGIServer/0.2 CPython/3.8.5 < Content-Type: text/html; charset=utf-8 < Location: /foo/ < Content-Length: 0 < X-Content-Type-Options: nosniff < Referrer-Policy: same-origin < * Connection #0 to host localhost left intact -
How to use Django model variable in form to set the input value in the HTML template
I have a database model called projects and a form model called project_id. I am looping through the projects in the database model -- {% for p in projects %}--to create bootstrap cards but I am trying to dynamically set the form's hidden input value to my project's primary key database id --{{ p.id }}--. The point here is to be able to click the view button to redirect to another page that will show the information of the project BUT that redirect is going to use the input value to run a database query in views.py. I've scoured the internet everywhere and can't find anything that doesn't use JS. project.html <div class="row"> {% for p in projects %} <div class="col-md-6"> <div class="card mb-4 box-shadow"> <img class="card-img-top" data-src="holder.js/100px225?theme=thumb&amp;bg=55595c&amp;fg=eceeef&amp;text=Thumbnail" alt="Thumbnail [100%x225]" src="{{p.showcase}}" data-holder-rendered="true" style="height: auto; width: 100%; display: block;"> <div class="card-body"> <h2 class="card-title">{{p.name}}</h2> <h6 class="card-subtitle mb-2 text-muted">{{p.contractor}}</h6> <p class="card-text py-3">{{p.description}}</p> <div class="d-flex justify-content-between align-items-center"> <form action="" method="POST">{% csrf_token %} <div class="form-group"> {{ form.project_id.value|deafult_if_none:{{p.id}} }} </div> <div class="form-group"> <input type="submit" value="View >>" class="btn btn-primary" /> <div class="submitting"></div> </div> </form> </div> <div class="text-right"> <small class="text-muted">{{p.date}}</small> </div> </div> </div> </div> {% endfor %} </div>