Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Obtaing Max Allowed Value of PositiveSmallIntegerField Django Field
I have the following PositiveSmallIntegerField attached to a Model as follows: class Proficiency(models.Model): class Meta: verbose_name = 'Proficiency' verbose_name_plural = 'Proficiencies' ... ... rating = models.PositiveSmallIntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(10)]) I have to do some complex calculations (*which can't be done within the ORM as far as I can see) on an endpoint which returns an average value: The calculation turns out to be: candidate['average'] = (candidate['total'] / count) * maximum_value_of_proficiency_rating_field i.e., maximum_value_of_rating_field is 10. Inspection of this field, and some digging into object attributes etc has lead me to find 10 dynamically as the following: proficiency._meta.get_field('rating')._validators[1].limit_value However, I was wondering if there was a simpler way to find the maximum value of a PositiveSmallIntegerField... i.e., either whatever value passed into the MaxValueValidator(10) i.e., "10" or if there is no MaxValueValidator, then 32767. I was thinking something like maybe a method would return this safely, or maybe an attribute on the field, i.e.,: proficiency.rating.get_maximum_value() or proficiency.rating.max_value Does anyone know if there is such a class method or attribute on the field to do this? -
Bootstrap dual list box POST Selected
I'm trying to post selected data from Bootstrap dual list (https://www.virtuosoft.eu/code/bootstrap-duallistbox/) do django. I'm using example code from https://codepen.io/jaredbell/pen/OejgMe. Problem occurs when i try to send selected items to view in django - i'm always getting one selected item instead of multiple selected items. Given example from https://codepen.io/jaredbell/pen/OejgMe showing selected items with js alert script works well but when I try to get selected items with django there is always one selected item instead of list of selected items. If you have any ideas i would be very appreciate. Regards django ( views.py ): if request.method=='POST': q=request.POST.get('duallistbox_demo1[]','') return HttpResponse(q) # always one item html: same code as https://codepen.io/jaredbell/pen/OejgMe -
Django - Why is the folder in html are not able to read?
I'm new to Django and just started to create an app and still learning. Right now, I'm actually in a part where I'm trying to call the HTML file. But I don't understand why if I put the line like this below. I get an error saying TemplateDoesNotExist:- views.py def index(request): return render(request, "hello/index.html") But if I put the line like this, it works like a charm:- views.py def index(request): return render(request, "index.html") but by the way, I create a new folder name templates under hello and another new folder hello under the templates and inside there is a file index.html was placed. The directory view:- lecture3/hello/templates/hellp/index.html Can anybody help me to understand why such an occurrence can happen? -
Is there any good tutorial for django leaflet which uses raster tiles? [closed]
I am creating a website using django leaflet. I want to create a world map and want to set colors of different regions according to my data by a region name. For this purpose, I am trying to use raster tiles, but I do not know how to do it. I am working on leaflet first time. I need some help. Thank you in advance. -
How to show this blog django backend by its id in react frontend
models class Blog(models.Model): title = models.CharField(max_length=50) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) serializers class BlogSerializer(serializers.ModelSerializer): class Meta: model = Blog fields = '__all__' views class BlogDetailView(generics.RetrieveUpdateDestroyAPIView): queryset = Blog.objects.all() serializer_class = BlogSerializer and urls from django.urls import path from .views import BlogDetailView urlpatterns = [ path('blog/<int:pk>/', BlogDetailView.as_view()), ] I'm trying to make a blog website. How can we show blogs by id in react js -
My deployed django app fail to load static files even collectstatic fail to fix
My django web app failed to load static files even after collecting all static files with manage.py collectstatic, I tried to look for solution but i failed to help. The deployment was done by uploading files from github repositories so they were accommodated in repositories/surveyapp folder. github link is https://github.com/carlomoan/surveyapp -
500 Server Error in my Django App in App Engine (Google Cloud)
I am new to Google Cloud an I followed the steps in https://cloud.google.com/python/django/appengine and deployed the App successfully. However, when I go to the page https://PROJECT_ID.REGION_ID.r.appspot.com the next message is displayed: Error: Server Error The server encountered an error and could not complete your request. Please try again in 30 seconds. I have seen this is something really usual but cannot find any useful solution. I would appreciate any help. -
django rest powered by json using nosql
I'm trying to develop an REST app which is flexible in term's of fields, means new fields can be added or removed dynamically, fields can be powered using json. for example, Here is json, can be edited at runtime to add new field or remove existing field, { "model": "MyModel", fields:{ "title": "CharField", "description": "CharField" } } Serializer can be, class MyModelSerializer(serializers.ModelSerializer): class Meta = MyModel How to achieve this ? Any guidance/ suggestion appreciated. -
save an instance of object in two models simultaneously
I am trying to create a route that will track all the history of a product. I have created a model for the product and a similar model for producthistory. Now, whenever I am creating an object I want it to be saved in the product table as well as the producthistory table. The only difference in both the tables is the id field. The producttable contains the id of the product & the producthistorytable has an id field of the historytable as well as the id of the product. I want to filter with the id of the product for further usage of the data. How can I insert the product object in the producthistory table along with the id of the product that was created at that point in time? Here is the models: class Product(Base): __tablename__ = "product" id = Column(Integer, primary_key=True, index=True) product_url= Column(String) current_price= Column(Integer) updated_at= Column(String) created_at= Column(String) target_price= Column(Integer) product_name= Column(String) class ProductHistory(Base): __tablename__ = "producthistory" id = Column(Integer, primary_key=True, index=True) product_id = Column(Integer) product_url= Column(String) current_price= Column(Integer) updated_at= Column(String) created_at= Column(String) target_price= Column(Integer) product_name= Column(String) here is the logic for creating product: @app.post('/createproducts/') def createproducts(request: Product, db:Session = Depends(get_db)): product = models.Product( … -
Django fat model update field reference model
i have two models: class Demand(models.Model): name = models.CharField(max_length=500) status = models.CharField(max_length=50, default="PREPARE") insert_user = models.ForeignKey(User, on_delete=models.PROTECT, editable=False) insert_date = models.DateTimeField(default=datetime.datetime.now, editable=False) def __str__(self): return self.name def submitt(self, *args, **kwargs): if self.pk : demand_detail = DemandDetails.objects.filter(demand_id = self.pk).update(status='SUBMITTED') self.status = 'SUBMITTED' self.save() class Meta: verbose_name = 'Demand' verbose_name_plural = 'Demand' class DemandDetails(models.Model): demand = models.ForeignKey(Demand, on_delete=models.CASCADE) component = models.ForeignKey(Component, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) comment = models.CharField(max_length=150, null=True, blank=True) status = models.CharField(max_length=50, default="PREPARE") insert_user = models.ForeignKey(User, on_delete=models.PROTECT, editable=False) insert_date = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): if not self.pk: try: super(DemandDetails, self).save(*args, **kwargs) except IntegrityError as e: obj = DemandDetails.objects.get(demand_id=self.demand_id, component_id=self.component_id) obj.quantity = obj.quantity + 1 obj.save() else: super(DemandDetails, self).save(*args, **kwargs) def __str__(self): return self.demand.name class Meta: verbose_name = 'Demand Detail' verbose_name_plural = 'Demand Details' constraints = [ models.UniqueConstraint(fields=['demand_id', 'component_id'], name='epm - DemandDetail (demand, component)' ) ] when I call the defined "submitt" method then I get this error: demand_detail = DemandDetails.objects.filter(demand_id = self.pk).update(status='SUBMITTED') NameError: name 'DemandDetail' is not defined how can i fix this error ? -
How to pass a variable from view1 which is inside view2 to view2's template in Django
I have a view home: def home(request): return render(request, 'detection/home.html') And here is its' template templates/detection/home.html: {% extends "detection/base.html" %} {% block content %} <h1>Camera View</h1> <img src="{% url 'cam-feed' %}"></img> {% endblock content %} which is based on templates/detection/base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {% block content %} {% endblock content %} </body> </html> In this view, as can be seen from home.html, I show camera output using view cam_feed: def cam_feed(request): return StreamingHttpResponse(gen(VideoCamera()), content_type="multipart/x-mixed-replace;boundary=frame") which uses the class VideoCamera which is an openCV class to show the camera and which outputs a prediction variable in get_frame: class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) def __del__(self): self.video.release() def get_frame(self): _, image = self.video.read() ### All the detections # Person Existence Classification # RGB_img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) im = Image.fromarray(image) im = im.resize((128, 128)) img_array = np.array(im) img_array = np.expand_dims(img_array, axis=0) prediction = int(model.predict(img_array)[0][0]) # plt.imshow(RGB_img) # plt.show() if prediction == 0: print('You ARE here') else: print('You are NOT here') _, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() cam_feed also uses function gen which passes the camera output in the appropriate form: def gen(camera): while True: frame = camera.get_frame() … -
How to Skip preview page (step 4 ) and redirect the user to Thank you page(Step 5) in Djnago-Oscar
I have been working on django-oscar, where i am integrating stripe prebuilt checkout page, i want to be able to achieve this 2 scenarios, Scenario 1: How to skip step 4(Preview) and redirect the user to the step 5(Thank you) without clicking on the "Place order" button on Preview page ? the rest functionality should work as it is. Scenario 2: How to make the preview page first and then the payment page after preview ? Let me know if you need more explanation or you want to see what i have done yet ? -
How to create env file in GCP for Django?
I was trying to create .env in GCP cloud build. The cloudbuild.yaml file steps: - name: 'python:3.8' entrypoint: python3 args: ['-m', 'pip', 'install', '-t', '.', '-r', 'requirements.txt'] - name: 'python:3.8' entrypoint: python3 args: ['touch', '.env'] env: - 'DATABASE_HOST=$$DB_HOST' - 'DATABASE_USER=$$DB_USER' - 'DATABASE_PASSWORD=$$DB_PASS' - 'DATABASE_NAME=$$DB_NAME' - 'FIREBASE_CREDENTIALS=$$FIRE_CRED' - name: 'python:3.8' entrypoint: python3 args: ['./manage.py', 'collectstatic', '--noinput'] - name: "gcr.io/cloud-builders/gcloud" args: ["app", "deploy"] timeout: "1600s" I've tried with several ways to do that but it's not yet solved. Created Substitution variable in GCP Trigger that I used in env. The problem is - name: 'python:3.8' entrypoint: python3 args: ['touch', '.env'] env: - 'DATABASE_HOST=$$DB_HOST' - 'DATABASE_USER=$$DB_USER' - 'DATABASE_PASSWORD=$$DB_PASS' - 'DATABASE_NAME=$$DB_NAME' - 'FIREBASE_CREDENTIALS=$$FIRE_CRED' This portion of the code. Thank you in advance. -
Django Application data not persisting for deployment
Currently developing a Django application to be deployed onto a digital ocean droplet. On this droplet there is 4 docker containers for: PostgreSQL, PGADMIN4, Django App, Certbot. In Django Admin (localhost), I have added some values to my database and they will be displayed throughout the web application. However, when I deploy my Django Application to the digital ocean droplet, this data is nowhere to be seen. I read that I can make a sql dump file of my local database and get the values on my droplet that way. But id rather another way if possible. I have done this process before but I was using a postgis database that came with a prebuilt database, whereas now I have to create a database again on my postgresql container (locally and on droplet). I am creating an image of my Django Application through a Docker file that I then push to dockerhub and pull to my digital ocean droplet. Any help is appreciated. Dockerfile ## ## Dockerfile to generate a Docker image ## # Start from an existing image with Python 3.8 installed FROM python:3.8 MAINTAINER Mark Foley # Run a series of Linux commands to ensure that # 1. … -
Highcharts Sankey Colors not working in django
Does anyone know why the sankey chart responds differently in a django compared to just an HTML file that is not in a server. The chart options and the data provided to them is the same and the chart definition is also the same but the rendering of the charts is different. For example, the colors in the server do not work yet on the static HTML they render perfectly. Kindly assist. Thanks -
Django REST framework HyperlinkedIdentityField format kwarg not working
I have just started looking into Django REST Framework and am following the tutorial in the official documentation. In this tutorial, we use HyperLinkedIdentityField for highlight attribute. We set the format kwarg to html. The tutorial states: Notice that we've also added a new 'highlight' field. This field is of the same type as the url field, except that it points to the 'snippet-highlight' url pattern, instead of the 'snippet-detail' url pattern. Because we've included format suffixed URLs such as '.json', we also need to indicate on the highlight field that any format suffixed hyperlinks it returns should use the '.html' suffix. The problem is that when I visit the snippet-list using the url http://127.0.0.1:8000/snippets/?format=json I get the highlight url as http://127.0.0.1:8000/snippets/1/highlight/?format=json while I expected it to be http://127.0.0.1:8000/snippets/1/highlight/?format=html because no matter what format we request the snippet-list url, the highlight link will always have HTML format. My code looks like this: highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html') class Meta: model = Snippet fields = ['url', 'id', 'highlight', 'owner', 'title', 'code', 'linenos', 'language', 'style'] Any help will be highly appreciated Thanks, -
Bootstrap + Django navbar not opening on toggle
I am attempting to use the collapsible navbar component provided by bootstrap. I believe I am not importing the correct libraries. Here is my base.html <!doctype HTML> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous"> <title>Course!</title> </head> <body> {% include 'navbar.html' %} {% block content %} {% endblock %} <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script> </body> </html> And here is my navbar.html: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="/"> <img src="http://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg" width="30" height="30" alt=""> Navbar </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent" > <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> </ul> </div> </nav> I am sure that the error is actually in base.html itself where I am not importing the correct scripts. Additionally, if it would be greatly appreciated if I could get advice on how to store these files locally. -
serializing foreing key variable in update method
I'm trying to override the update method of a serializer. This serializer have a field 'gear' which is a foreing key of the Trawl table. But when I try to save the updated instance in update method, I get the error: ValueError: Cannot assign "2": "Haul.gear" must be a "Trawl" instance This is the serializer: class HaulTrawlSerializer(serializers.ModelSerializer): gear = serializers.IntegerField() class Meta: model = Haul fields = ['id', 'haul', 'gear', 'valid', ] def update(self, instance, validated_data): if validated_data: for attr, value in validated_data.items(): print(attr, value) setattr(instance, attr, value) instance.save() return instance So I try to convert Haul.gear to a Trawl instance changing the update method: def update(self, instance, validated_data): instance.gear = Trawl.objects.get(pk=validated_data.pop('gear')) if validated_data: for attr, value in validated_data.items(): print(attr, value) setattr(instance, attr, value) instance.save() return instance And then, the error TypeError: int() argument must be a string, a bytes-like object or a number, not 'Trawl' is thrown and I don't understand it. Why first ask for a Trawl instance, but after ask for a int? -
Get Page_not_found on Django project
I got page_not_found when try to use url: from django.urls import path from . import views urlpatterns = [ path('api/v1/posts/int:post_id/', views.get_post, name='get_post'), ] To my view function in small Django project: from django.http import JsonResponse from rest_framework.response import Response def get_post(post_id): if request.method == 'GET': post = get_object_or_404(Post, id=post_id) serializer = PostSerializer(post) return JsonResponse(serializer.data) Asking for help) -
AssertionError at /wiki/Facebook
def markdown_to_html(markdown_string): if '\r' in markdown_string: markdown_string = markdown_string.replace('\r\n', '\n') assert('\r' not in markdown_string) unique_marker = 'PROTECTED_CHARS_fwargnmejlgnsjglsibgtnovdrsfeaijler' heading_matcher = re.compile(r'^(?P<hash_tags>#{1,6})\s*(?P<heading_title>.*)$', re.MULTILINE) heading_substituted = heading_matcher.sub( lambda m: rf"{unique_marker}<h{len(m.group('hash_tags'))}>{m.group('heading_title')}{unique_marker}" + rf"</h{len(m.group('hash_tags'))}>", markdown_string) bold_matcher = re.compile(r"(\*\*|__)(?P<bolded_content>.+?)\1") bold_substituted = bold_matcher.sub(r"<b>\g<bolded_content></b>", heading_substituted) list_outside_matcher = re.compile(r"^([-*])\s+.*?(?=\n\n|\n((?!\1)[-*])\s|\Z)", re.MULTILINE | re.DOTALL) list_inside_matcher = re.compile(r"^([-*])\s+(?P<list_item>.*?)(?=\n[-*]\s+|\Z)", re.MULTILINE | re.DOTALL) list_substituted = list_outside_matcher.sub(lambda m: unique_marker + '<ul>\n' + list_inside_matcher.sub(unique_marker + r"<li>\g<list_item>" + unique_marker + "</li>", m.group()) + '\n' + unique_marker + '</ul>', bold_substituted) link_matcher = re.compile(r"\[(?P<text>((?!\n\n).)*?)\]\((?P<link>((?!\n\n).)*?)\)", re.DOTALL) link_substituted = link_matcher.sub(rf'<a href="\g<link>">\g<text></a>', list_substituted) paragraph_matcher = re.compile(rf"^(?!{unique_marker}|\n|\Z)(?P<paragraph_text>.*?)(?=(\n\n)|{unique_marker}|\Z)", re.MULTILINE | re.DOTALL) paragraph_substituted = paragraph_matcher.sub(r"<p>\g<paragraph_text></p>", link_substituted) html_string = paragraph_substituted.replace(unique_marker, '') return html_string -
How to add item to wishlist with only specific variant object(s) in django rest framework?
Before my product model doesnt include variants. Now I have added variants which is ManytoMany relationships with Product model. Variants model consists of fields like color,size,price etc. I had already created api endpoints for adding items to wishlist. Now, if I had added with same api, it will includes all the variants. But,in frontend, user has the flexibility of choosing only a single varaint. How to change this? My models: class Variants(models.Model): SIZE = ( ('not applicable', 'not applicable',), ('S', 'Small',), ('M', 'Medium',), ('L', 'Large',), ('XL', 'Extra Large',), ) AVAILABILITY = ( ('available', 'Available',), ('not_available', 'Not Available',), ) price = models.DecimalField(decimal_places=2, max_digits=20,blank=True,null=True) size = models.CharField(max_length=50, choices=SIZE, default='not applicable',blank=True,null=True) color = models.CharField(max_length=70, default="not applicable",blank=True,null=True) quantity = models.IntegerField(default=10,blank=True,null=True) # available quantity of given product vairant_availability = models.CharField(max_length=70, choices=AVAILABILITY, default='available') class Meta: verbose_name_plural = "Variants" class Product(models.Model): AVAILABILITY = ( ('in_stock', 'In Stock',), ('not_available', 'Not Available',), ) WARRANTY = ( ('no_warranty', 'No Warranty',), ('local_seller_warranty', 'Local Seller Warranty',), ('brand_warranty', 'Brand Warranty',), ) SERVICES = ( ('cash_on_delivery', 'Cash On Delivery',), ('free_shipping', 'Free Shipping',), ) category = models.ManyToManyField(Category, blank=False) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) featured = models.BooleanField(default=False) # is product featured? best_seller = models.BooleanField(default=False) top_rated = models.BooleanField(default=False) tags = TaggableManager(blank=True) # tags mechanism … -
Why is This Simple BeautifulSoup and Django Webscrapping Code Not Working
from bs4 import BeautifulSoup from django.core.management.base import BaseCommand from urllib.request import urlopen from bs4 import BeautifulSoup import json import html5lib from blog.models import Post, Category import csv class Command(BaseCommand): help = "collect news" # define logic of command def handle(self, *args, **options): # collect html html = requests.get('https://bbc.com') # convert to soup soup = BeautifulSoup(html.content, 'html5lib') # grab all postings postings = soup.find_all("div", class_="posting") for p in postings: url = p.find('a', class_='posting-btn-submit')['href'] title = p.find('h3' class_="media__title").text category = p.find('b').text images = soup.find_all('img') content_1 = soup.find_all('blockquote').text # check if url in db try: # save in db Post.objects.create( title=title, category=category, content_1=content_1, image=images ) print('%s added' % (title,)) except: print('%s already exists' % (title,)) self.stdout.write( 'News Added succesfully' ) This is supposed to scrap bbc website when i run python manage.py scrapper. can anybody shows me a way out or simply show me a way to scrap that website quickly. am desperately waiting for solutions -
Ajax call towards django views
Good morning. I made an ajax call on a button that goes to the Django views. I don't find any issues with it but it doesn't work at all, I can't even get a console response from it. I can get the response I want (redirection) without issues if not using AJAX. I am working with Django on localhost. I did not forget to put the JQuery script. Can anyone help, please? Button HTML <a href="{% url 'Like' post.id %}"> <button id="like-button" class="btn btn-outline-dark btn-lg w-100">Like</button> </a> AJAX $('.like-button').click(function(e){ console.log('TEST1') ---#Nothing shows on console e.preventDefault(); console.log('TEST2') ---#Nothing shows on console $.ajax({ type: "POST", url: $(this).attr('href'), data: {'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: "json", success: function(response) { console.log(response) ---#Nothing shows on console selector = document.getElementsByName(response.content_id); if(response.liked==true){ $(selector).css("color","blue"); } else if(response.liked==false){ $(selector).css("color","black"); } } }); }) -
Updating values in django
I am trying to update the profile value of a particular user. If the user has logged in for the first he needs to go to Edit Profile and then enter the details which are getting stored in the database. When I am trying to update the values of a User Profile. It is not getting updated in the database. I know the code is not that perfect but I am just trying to do it through normal logic. You can also find the comment in the code which represent what the code of block is doing. Code # edit user profile def edit_profile(request): try: # checking if the user exist in UserProfile through the logged in email id user_data = UserProfile.objects.get(emailID = request.user.email) except UserProfile.DoesNotExist: name = UserProfile.objects.all() response_data = {} # when the submit button is pressed if request.POST.get('action') == 'post': name = request.user.username emailID = request.user.email phone = request.POST.get('phone') college_name = request.POST.get('college_name') branch = request.POST.get('branch') response_data['name'] = name response_data['emailID'] = emailID response_data['phone'] = phone response_data['college_name'] = college_name response_data['branch'] = branch try: # checking if the user exist # if the user exist update the values user_data = UserProfile.objects.get(emailID = request.user.email) if(user_data.emailID == request.user.email): UserProfile.objects.filter(emailID = request.user.email).update( name … -
Django booleanfield modelform
So I'm making a to-do list and I made a booleanfield modelform which has attribute "complete". I want that user to check it when it's complete and I tried wriring if task.complete == True cross out the item and it didn't work(it only worked when I checked it from the admin panel). Then I tried form.complete instead of task.complete and it doesn't do anything. models: class Task(models.Model): title = models.CharField(max_length=200) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title forms: from .models import * class TaskForm(forms.ModelForm): title = forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Add new task...'})) class Meta: model = Task fields = '__all__' html: <div class="main-container"> <form method="POST" action="/"> {% csrf_token %} <input type="submit"/> {{ form.title }} </form> {% for task in tasks %} {{ form.complete }} {% if form.complete == True %} <h1><strike>{{task.title}}</strike></h1> {% else %} <h1>{{task.title}}</h1> {% endif %} {% endfor %} </div> views: def index(request): tasks = Task.objects.order_by('-created') form = TaskForm() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = { 'tasks': tasks, 'form': form, } return render(request, 'to-do.html', context)