Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django creation report
I need to create a report with graphs in django with data from the database. How will it be done? I have db in mysql. I need to create a report with graphs in django with data from the database. How will it be done? -
Django NOT NULL constraint failed: product_product.price
I am learning Django, and is following this online tutorial for creating forms. https://www.youtube.com/watch?v=6oOHlcHkX2U&list=PLEsfXFp6DpzTD1BD1aWNxS2Ep06vIkaeW&index=23. Upon rendering in browser, I receive NOT NULL constraint failed: product_product.price. In my models.py I have from django.db import models # Create your models here. class Product(models.Model): title = models.CharField(max_length = 200, null = False, blank = False) description = models.TextField(null = True, blank = True) price = models.DecimalField(decimal_places=0, max_digits = 10) active = models.BooleanField(default = True) def __str__(self): return self.title In my views.py under the same app I have from django.shortcuts import render from .forms import ProductForm # Create your views here. def productCreateView(request): form = ProductForm(request.POST or None) if form.is_valid: print('form is valid now to saving') print('\n\n') form.save() context = {'form' : form} return render(request, '../templates/product_create.html', context=context) I have tried to python manage.py makemigrations python manage.py migrate when I tried to modify my price in my models.py e.g. by stating price = models.DecimalField(decimal_places=0, max_digits = 10, blank = False, null = False) Each time it says that there is nothing to migrate. For the sake of learning, can anybody tell me what I am missing? My complete error messages looks like below [09/Mar/2020 23:24:41] "GET /create HTTP/1.1" 301 0 form is valid now to … -
Concurrent.futures.Executor.map() is only running fragments of passed function
I'm trying to make a Django application using Spotify's API with Spotipy. When a user logs in, I want to create models for the User, their playlists, and the tracks in the playlists. I did so successfully with the following code: import sys import spotipy import spotipy.util as util import json from .models import User, Track, Playlist #functionality for interacting with the Spotify API through spotipy class SpotifyServices(): scope = "user-library-read user-read-recently-played" username = "ratiugo" token = util.prompt_for_user_token( username, scope, client_id="", client_secret="", redirect_uri="http://localhost:8001/radio/home") spotify = spotipy.Spotify(auth=token) #create User model and Playlist models for each of the user's playlists, and Track objects for each track connected to a playlist def create_user_playlist_and_track_models(self): current_user = User.objects.create(username=self.spotify.current_user()["display_name"]) current_user.save() # create playlist objects for each playlist for playlist in self.spotify.current_user_playlists(limit=50)["items"]: image_url = self.spotify.playlist_cover_image(playlist["id"])[0]["url"] created_playlist = Playlist.objects.create( owner=current_user, name=playlist["name"], playlist_href=playlist["id"], image_url=image_url ) created_playlist.save() #create Track models for each track in playlist just created #get playlist track objects playlist_items = self.spotify.playlist_tracks(playlist["id"])["items"] #get each track from playlist track object for item in playlist_items: #filter 'none' items to prevent crashing if item["track"] is None: continue #if the track object exists, grab the audio features of the track else: audio_features = self.spotify.audio_features(item["track"]["id"]) #filter 'none' items to prevent crashing if audio_features[0] … -
Django model DateField attribute limit choices
background: So im trying to build a "Bill" model with the attributes Name (name of payee), Amount (how much $ to pay), and PayDate (when to pay the bill). What I am stuck on: I'm having some hard time trying to limit the PayDate input from 1 (first of the month) to 31 (last day of the month (Depending on the month)) This is my code for the model: from django.db import models # Create your models here. class Bill(models.Model) : Name = models.CharField(max_length=200, editable=True, blank=False) Amount = models.DecimalField(editable=True, blank=False, decimal_places=2, max_digits=6) PayDate = models.IntegerField( blank=False, editable=True) def __str__(self): return f"{self.Name} @ ${self.Amount} every {self.PayDate} of the month" I would love to get your suggestions on how to set the PayDate attribute. -
React frontend not receiving response from Django HttpResponse after successful request
I'm working on an application with a React frontend and Django backend. The frontend request is hitting the backend (and updating the db) but a response is not being returned to the frontend. I'm new to both Django and React so I haven't been able to debug it. React Frontend var csrftoken = Cookies.get('csrftoken') let headers = { "X-CSRFToken": csrftoken, "Content-Type": "application/x-www-form-urlencoded" }; const qs = require('qs'); axios.post('/api/thing/new/', qs.stringify({thing_text: thing.thing_text}), {'headers': headers}) .then((result) => { console.log(results) }); Django Backend class ThingForm(ModelForm): class Meta: model = Thing fields = ['thing_text'] def thing_create(request): form = ThingForm(request.POST or None) if form.is_valid(): form.save() return JsonResponse({'foo':'bar'}) I've also tried returning a response with return HttpResponse(status=204) to no avail. This is resulting in an error, Uncaught (in promise) ReferenceError: results is not defined Which I interpret as nothing being returned to the frontend (though I could be wrong). Again, I know the backend is receiving the request because a record is created in the db. Is there anything I should try to debug this? -
Django, get value of the ChoiceField form
I have a form which contain a choicefield of items on my database. My question is How can I get the selected value of my choicheField? forms.py class list_data(forms.Form): message = forms.CharField(widget=forms.Textarea) def __init__(self, author, *args, **kwargs): super(list_data, self).__init__(*args, **kwargs) self.fields['List'] = forms.ChoiceField( choices=[(o.id, str(o)) for o in List.objects.filter(author=author)] ) views.py def sms(request): form2 = list_data(author=request.user) if request.method == "POST": form2 = list_data(request.POST) if form2.is_valid(): choice = form2.cleaned_data["List"] print(choice) else: return render(request, "data_list/sms.html", {"form2": form2}) return render(request, "data_list/sms.html", {"form2": form2}) When I try to press the submit button it give me this error: int() argument must be a string, a bytes-like object or a number, not 'QueryDict' So I changed the form2 = list_data(request.POST) for form2 = list_data(author=request.user) the error is gone but it print nothing else. Thanks for helping -
Django: How to retrieve in an AJAX POST request the value of two different variables?
I'm trying to send to my Django view two values from two different dropdowns but it doesn't work. Only the first dropdown value is sent to the view. Let's say I have the following view: def MyView(request): if request.method == 'POST' and request.is_ajax: result_1 = request.POST.get('d1') print(result_1) result_2 = request.POST.get('d2') print(result_2) And this is the html code: <script type="text/javascript"> function dropdownChange () { var selectedRegion = $(".toChange option:selected").val(); $.ajax({ url: '/myApp/templates/', type: 'POST', data: {'d1': selectedRegion}, } }); } $(".toChange").change(dropdownChange); </script> <select name="d1" class="toChange"> <option val="1"> 1 </option> <option val="2"> 2 </option> </select> <select name="d2"> <option val="3"> 3 </option> <option val="4"> 4 </option> </select> When the dropdown d1 faces a change, I want both d1 and d2 values to be sent to my view. The value of d1 is properly captured but d2 (so result_2) shows "[]". How can I capture the two variables? -
File Upload with Model Forms: not getting the selected file
I am trying to follow https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html however I failing to find my error: models.py: class PurchaseOrderRequest(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, db_index=True) request_object = models.CharField(max_length=80) # Should be a ForeignKey later order_summary = models.CharField(max_length=80) vendor = models.CharField(max_length=80) currency = models.CharField(max_length=40, choices=CURRENCY_CHOICES, default="USD") quote = models.FileField(upload_to='uploads/po-quotes/%Y/%m') date_updated = models.DateTimeField(auto_now=True) date_uploaded = models.DateTimeField(auto_now_add=True) def __str__(self): return self.order_summary forms.py class PurchaseOrderRequestForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( 'request_object', 'order_summary', Row( Column('vendor', css_class='form_group col-md-4 mb0'), Column('currency', css_class='form_group col-md-4 mb0'), Column('quote', css_class='form_group col-md-4 mb0'), css_class='form_row' ), Submit('submit', 'Request') ) class Meta: model = PurchaseOrderRequest fields = '__all__' labels = { 'order_summary': _('Summary of ordered goods'), 'quote': _('Quotation'), } help_texts = { 'order_summary': _('Example: Construction - Kitchen - Electrical Appliances'), } widgets = { } My challenge is the quote FileField. The HTML-template looks like this: po_request.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %} {% endblock title %} {% block content %} <h1>Request a Purchase Order</h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% crispy form %} </form> {% endblock content %} My Google-Fu indicated I need to add the enctype="multipart/form-data" option for FileFields to work. views.py def createRequest(request): if request.method == 'POST': form = PurchaseOrderRequestForm(request.POST, request.FILES) … -
Test login protected page with permissions in django (pytest)
I am trying to test a view which only shows a template thus far. To access the view the user needs the permission 'projects.can_view'. I am trying to create a user with this permission in the test db using a fixture, then I am trying to log a client in with the username and password of my user in the db. I try to visit the view but I get a 302 error (redirect to login view.) I can verify that I actually pass the permissions correctly: My fixture: @pytest.fixture() def create_users_with_permissions(): User = get_user_model() u = User.objects.create( username="test", password="pass", ) permission = Permission.objects.get(name='Can view project') u.user_permissions.add(permission) u = User.objects.get(username='test') print(u.has_perm('appname.view_project')) return u I query the user again to delete the permissions cache like explained in the doc (https://docs.djangoproject.com/en/3.0/topics/auth/default/). When I print out print(u.has_perm('appname.view_project')) it returns True. Thus I assume I have a user with this specific permission created. Now I pass the fixture to my test and log pytests client-fixture in: def test_xyz( self, client, create_users_with_permissions ): client.login( username=create_users_with_permissions.username, password=create_users_with_permissions.password ) url = reverse('urlforview') response = client.get(url) assert response.status_code == 200 This fails with error code: assert 302 == 200 If I create a superuser in the db and … -
Why am I getting the pylint error: Value 'self.body' is unsubscriptable?
I am trying to get the summary method the return the first 50 characters from the body. class Blog(models.Model): # Title for the Blog title = models.CharField(max_length=255) # Blog body body = models.TextField() def __str__(self): return self.title def summary(self): return self.body[:50] # I get the error here -
Django adding form dynamically but unable to save to DB
I’m dynamically adding a form to a Django formset using empty_form with Jquery. I can add as many forms as wanted, fill them, but when I record them using button, I got in my database only empty form. What am’I missing ? Following is the template : { % csrf_token%} ……….. My Ingredients {{ myformset.management_form }} {% for form in myformset.forms %} {{ form }} {% endfor %} {{ myformset.empty_form}} $('#add_more').click(function() { debugger; var form_idx = $('#id_ingredientsdelarecette_set-TOTAL_FORMS').val(); $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx)); $('#id_ingredientsdelarecette_set-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); Enregistre Recette -
Python-telegram-bot issue
I have deployed a telegram bot (with Django) on Heroku with python version 3.6.9 It worked well without any issues. After months I did some changes and while trying to deploy it again I get issues. Heroku doesn't support python 3.6.9 anymore. It supports 3.6.10 So I set up venv with python 3.6.10 and I'm still getting the same issue after running the server. Short issue: from .callbackcontext import CallbackContext File "/home/usr/bot-name/venv/lib/python3.6/site-packages/telegram/ext/callbackcontext.py" , line 21, in <module> from telegram import Update ImportError: cannot import name 'Update' from 'telegram' (/home/usr/bot-name/venv/lib/python3.6/site-packages/telegram/init.py) Also I have tried python 3.7.6 (it's also supported by Heroku) but I get the same issue after running the server: _python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/local/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/usr/bot-name/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/usr/bot-name/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/usr/bot-name/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/home/usr/bot-name/venv/lib/python3.7/site-packages/django/core/management/init.py", line 337, in execute autoreload.check_errors(django.setup)() File "/home/usr/bot-name/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/usr/bot-name/venv/lib/python3.7/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/usr/bot-name/venv/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/usr/bot-name/venv/lib/python3.7/site-packages/django/apps/config.py", line … -
Django/Python: Calculate DateTimeField() via variables
I am new to python and can't wrap my head around a solution for my simple issue for days now. I have an Event model which should allow the user to book a timeslot, room and event type that will be shown in a timetable. class Event(models.Model): title = models.CharField(max_length=200) description = models.TextField() start_time = models.DateTimeField() end_time = models.DateTimeField() get_date = models.DateTimeField() # set via form, has year and day start_time_choices = [('1', '07:30'), ('2', '07:45'), ('3', '08:00'), ('4', '08:15'), ('5', '08:30')] timeslots = models.TimeField( choices=start_time_choices, "%H:%M", default='1', null=True) room_choices = [('1', 'Room 1'), ('2', 'Room 2'), ('3', 'Room 3'), ('4', 'Room 4'), ('5', 'Room 5')] room = models.CharField( choices=room_choices, max_length=1, default='1', null=True) event_choices = [('1', 'Event A'), ('2', 'Event B')] # A is 15min long, B is 30min long events= models.CharField( choices=event_choices, max_length=1, default='1', null=True) Now I want to calculate the start_time and end_time for this event which is used for the calendar view Where do I put the following calculation? Directly in models.py? How do I handle proper date calculation? # this is not a real code @property def date_calc(self): start_date = get_date + timeslots # Year & Day + Hour & Min if events == "Event A": … -
Split django models.py into multiple files inside folder (Django 3.0.4)
I'm trying to split the models.py into multiple files inside a folder. what is the proper way to do that ? all the methods in the internet from 8 years ago and it's not working now. -
POST method is not working when i sumbiting form in django
I created feedback form using form module in django. i wrote the code for printing form data entered by user when sumbiting form.But when i sumbiting form post not working as a result user data is not printing . I am beginner in django.I tried lots to solve this.but i couldn't .please help me if anyone know what is my wrong in code forms.py from django import forms class feedbackForm(forms.Form): Name=forms.CharField() RollNo=forms.IntegerField() Email=forms.EmailField() feedback=forms.CharField(widget=forms.Textarea) views.py from django.shortcuts import render from .import forms def feedback_view(request): form=forms.feedbackForm() if request.method=='POST': form=forms.feedbackForm(request.POST) if form.is_valid(): print('form validation success and printing feeback info') print('student name :',form.cleaned_data['Name']) print('student RollNo:',form.cleaned_data['RollNo']) print('student Email :',form.cleaned_data['Email']) print('student feedback :',form.cleaned_data['feedback']) return render(request,'testapp/feedback.html',{'form':form}) urls.py from django.conf.urls import url from django.contrib import admin from testapp import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^feed/', views.feedback_view), ] feedback.html <!DOCTYPE html> {% load staticfiles %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="{%static "css/demo1001.css"%}"> <title></title> </head> <body> <div class="container" align=center> <h1>ShefJaz Student 2feedbackform </h1><br> <form method="post"> {{form.as_p}} {%csrf_token%} <button type="button" class="btn btn-primary">sumbit feedback</button> </form> </div> </body> </html> -
Is a defined app_name recommended in urls.py for Django 2?
I'm trying to figure out what the best practices are around writing urls.py files in my Django app. I'm updating an old project to Django 2, and I read in the update documentation that urls.py files should be properly namespaced. A bit of googling suggests to me to define app_name in my urls.py always, so you don't have to manually add the app_name to each url endpoint. Instead you can then access it like ("app_name:url_name"). In my project I have: avatar/urls.py tests/urls.py So in this case, I am not sure how to name them, but for now I've gone with app_name = "avatar" in avatar/urls.py and app_name = "avatar-tests" in tests/urls.py. Do these both need an app_name for proper namespacing? Is it best practice to always have a defined app_name per urls.py? I'm uncertain still if this is required or even recommended. If I've understood correctly, it's just for easier/logical access of the url, not strictly required, but recommended in the sense that it's easier to follow. -
why does i got error in recaptcha in setting module in django?
when i used settings in Django,i got error because of using captcha in setting package def grecaptcha_verify(request): data = request.POST captcha_rs = data.get('g-recaptcha-response') url = "https://www.google.com/recaptcha/api/siteverify" params = { 'secret': settings.RECAPTCHA_SECRET_KEY, 'response': captcha_rs, 'remoteip': get_client_ip(request) } ``` when i used this method i got error in AttributeError: Settings object has no attribute RECAPTCHA_SECRET_KEY -
Django, how to put database object on a choicefield form
so I have a form that contain a choiche field, I wanna put all the item of my database in that choichefield, how can I do that? thanks for help! (The form is not a models form cause I dont need to edit or change the data) models.py class List(models.Model): item = models.CharField(max_length=100) content = models.TextField() site = models.CharField(max_length=11, choices=THE_SITE) content_list = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.item forms.py data = [ ("LIST1", "LIST1"), ("LIST2", "LIST2") ] class sms_form(forms.Form): list_data = forms.ChoiceField(choices=data) message = forms.CharField(widget=forms.Textarea) -
Problem connecting redis and django in GCP
I have deployed a Redis instance using GCP Memorystore. I also have a django app deployed using App Engine. However, I am facing problems connecting these 2. Both are deployed in the same timezone. The package that I'm using is django_redis The error is: Exception Value: Error 110 connecting to <Redis instance IP>:6379. Connection timed out. Exception Location: /env/lib/python3.7/site-packages/redis/connection.py in connect, line 557 In settings.py I use: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("<Redis instance IP>", 6379)], }, }, } CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": 'redis://<Redis instance IP>/0', "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" } } } -
Is there a way to only load javascript files when certain pages are loaded using Django?
I am making a Django website. I am not an expert but I understand the basics. However I am a complete rookie when it comes to javascript. I am using Django Templates to have each page on my website 'inherit' from a Base page (base.html). I want to include Javascript within a script tag of the base page that will only load when a certain page is loaded. I want to do something like this: {% load static %} <!DOCTYPE html> <html lang="en"> <head> ... ... </head> <body> ... <!-- Main Content --> {% block content %} {% endblock %} ... <script> Some Script on every page </script> <!-- Some Django if statement like the one below goes here --> {% if this_page == '/special_page/' %} <!-- a special script is loaded here --> <script> Special Script </script> {% endif %} </body> </html> I am not sure if this can be done. Can this be done, and if so, is it a security risk? -
Jquery update cart function not sync with Django backend database
I am trying to create a Django eCommerce, and I find a js fiddle where the cart update (increase and decrease operation with final cart calculation) is shown. I am trying to integrate that code with my project. It workes but unfortunately I am not able to syce with my backend database. That means it only working with HTML but not updating my underlying database or in server. I am trying to grab the "data-item-id="{{cart_item.item.id}}"" in the jquery section. but not succeed. i think by grabbing the data-item-id="{{cart_item.item.id}}" can solve the problem. I don't know much js or jquery, so this is a real headache for me. here is my code detail. The exact fiddle that i am following is https://jsfiddle.net/1Lb430o8/18/ Everything is worked but only in the HTML part not in the backend, and that is what I need.So how can it worked with django in the backend? {% block jquery %} var taxRate = 0.15; var shippingRate = 20.00; var fadeTime = 300; $(document).ready(function() { recalculateCart(); }); //On click Plus button $(document).ready(function() { $(".cart-qty-plus").click(function() { var $n = $(this) .parent(".button-container") .parent(".product-quantity") .find(".qty"); $n.val(Number($n.val()) + 1); updateQuantity(this); }); }); // On click minus button $(document).ready(function() { $(".cart-qty-minus").click(function() { var … -
creating windows executable django restful application
I have written a django restful application w/ postgres DB, this application is supposed to be working online over cloud. But I want to add a feature which enables the user to be able to use the application (some features) in case he lost his internet connection then after internet is back I will sync the modifications in DB data with the DB on the cloud. So I want to install the application on his PC in the form of executable EXE file. How can I accomplish this please? -
Create and save django object on click
I have a shoppinglist app. I want that when the user clicks on "add to shopping list" the item is saved to the shopping list. How can I do that? in the template I wrote: <a href="javascript:{document.getElementById('add_item').submit()}" class="btn btn-primary btn-block">Add to shopping list </a> <form action="{% url 'add_to_shopping_list' product.id %}" id="add_item" method="POST"> {% csrf_token %} <input type="hidden"> </form> in urls.py I dispaced the urls like this: urlpatterns = [ path('add_to_shopping_list/<int:pk>', views.add_to_shopping_list, name='add_to_shopping_list'), ] this calls the view add_to_shopping_list where I want create a ShoppingItem object and to link this to the Product object. The problem is that I don't want to redirect the user anywhere, but just stay on the same page without refreshing. But the view wants me to return an HtmlResponse, or I get this error: The view shoppinglist.views.add_to_shopping_list didn't return an HttpResponse object. It returned None instead. Is the idea correct? If yes how can I solve this problem? Thanks -
DRF adding images to a ForeignKey already in the database
I am looking to add Images, to a Listing(ForeignKey), which will already be in my database. I have an Image model.. class Image(models.Model): photo = models.ImageField(blank=True, upload_to=get_image_filename) listing = models.ForeignKey(Listing, on_delete=models.CASCADE) ImageSerializer class ImageSerializer(serializers.HyperlinkedModelSerializer): photo = serializers.ImageField(allow_empty_file=True) class Meta: model = Image fields = ('url', 'photo', 'listing', ) ImageViewSet class ImageViewSet(viewsets.ModelViewSet): queryset = Image.objects.all() serializer_class = ImageSerializer detail_serializer_class = ImageDetailSerializer parser_classes = (FormParser, MultiPartParser) '''Show detailed Image view''' def get_serializer_class(self): if self.action == 'retrieve': if hasattr(self, 'detail_serializer_class'): return self.detail_serializer_class return super(ImageViewSet, self).get_serializer_class() I have tried overriding the create method in the serializer, and perform_create method in the actual viewset. But keep running into errors. Any advice in the right direction would be awesome]1 -
How saving data rows using loop form to save data in django?
I'm trying to save data from input form using django 3.0.3 throw loop form, the problem is when i enter the data into form only the second row saved and repeated in database. This is my code: models.py from django.db import models from datetime import datetime class NumberOfStudent(models.Model): class_num = models.CharField(max_length=100) num_of_student = models.IntegerField() student_abscence = models.IntegerField(default=0) date = models.DateTimeField(blank=True, default=datetime.now) def __str__(self): return self.class_num views.py from django.shortcuts import render, redirect from .models import NumberOfStudent from .forms import Insertdata def home(request): # Number of class's room for Grade 11 num_class_11 = 2 # Check if method of from is post if request.method == 'POST': insertdata = Insertdata(request.POST) # Chck if data inserted is valid if insertdata.is_valid(): for instance in range(num_class_11): instance = insertdata.save(commit=False) instance.pk = None instance.save() return redirect(data) else: insertdata = Insertdata() context = { 'title': 'Home Page', 'num_class_11': num_class_11, 'range': range(num_class_11), 'insertdata': insertdata, } return render(request, 'hello/home.html', context) def data(request): class_11 = NumberOfStudent.objects.all() context = { 'class_11': class_11, } return render(request, 'hello/data.html', context) forms.py from django import forms from .models import NumberOfStudent class Insertdata(forms.ModelForm): class Meta: model = NumberOfStudent fields = ('class_num', 'num_of_student', 'student_abscence') index.html <!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> …