Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting user input using django forms.py return nothing
I'm trying to get the users input and add to a table in the database, everything goes smoothly with no errors .. but the input is not added to DB urls.py path('category/add/', views.add_cat, name="add_cat"), view.py def add_cat(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = CatForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required entry = Categories.objects.create(category_name=new_cat_name) entry.save() # ... # redirect to a new URL: return HttpResponseRedirect('/') # if a GET (or any other method) we'll create a blank form else: form = CatForm() return render(request, 'add_cat.html', {'form': form}) add_cat.html {% extends 'base.html' %} {% block content %} {% load static %} <form action="/" method="post"> {% csrf_token %} {% for form in form %} <h3 align="center">{{ form.label }}</h3> <div align="center">{{ form }}</div> <br> <br> {% endfor %} <div align="center"> <input type="submit" class="btn btn-dark" style="width: 100px;"value="إضافة" /> </div> </form> {% endblock %} -
how to filter a model objects by related table's foreign key in django REST
I want to make an API for a restaurant, and my models.py is like this: class Table(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30, null=False, blank=False) is_free = models.BooleanField(default=True) def __str__(self): return '%s %s %s' % (self.id, self.name, self.is_free) class Order(models.Model): order_id = models.AutoField(primary_key=True) table_id = models.ForeignKey(Table, on_delete=models.CASCADE) total_price = models.IntegerField() factor_id = models.IntegerField() def __str__(self): return '%s %s %s' % (self.order_id, self.table_id.id, self.total_price) class OrderDetail(models.Model): order_detail_id = models.IntegerField(primary_key=True) order_id = models.ForeignKey(Order, on_delete=models.CASCADE) food_id = models.ForeignKey(Food, on_delete=models.CASCADE) amount = models.IntegerField() price = models.IntegerField() def __str__(self): return '%s %s %s' % (self.order_detail_id, self.order_id, self.food_id.name) When an Order with a Table created, some OrderDetails should add to it. I want to filter all OrderDetail objects that are for a specific Table and are for the latest Order(I mean all OrderDetail objects that are active now). The client request URL with filter contains table_id and not order_id. How can I filter OrderDetail objects by the table that have it? Each table can only have one order in a moment, When an Order creates with a specific Table, the is_free will set to False. So the table_id field of Order class should be models.ForeignKey not models.OneToOneField, I think so! :) If it's wrong please tell … -
Edit UserProfile using Django Forms
I am creating a web application using the Django web framework. As part of the application, I wanted to give users the ability to update their profile as they choose. When a user tries to update their profile however, the information remains the same even after the user has submitted new information. I've checked my database and the values are not being updated in there either. It is possible however, to change a Users information on the admin page. Below is how I have tried to implement the functionality. Model class UserProfileModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) age = models.PositiveIntegerField(blank=True, null=True) email = models.EmailField(max_length=254, null=True, blank=True, unique=True) height = models.PositiveIntegerField(blank=True, null=True) weight = models.PositiveIntegerField(blank=True, null=True) Form class UpdateProfile(forms.ModelForm): class Meta: model = UserProfileModel fields = ('email', 'age', 'height', 'weight') Views def update_profile(request): args = {} if request.method == 'POST': form = UpdateProfile(request.POST, instance=request.user) if form.is_valid(): form.save() # return HttpResponseRedirect(reverse('account:profile')) return render(request, 'account/profile.html') else: form = UpdateProfile() if request.user.is_authenticated(): form = UpdateProfile(instance=request.user) args['form'] = form return render(request, 'account/edit_profile.html', args) Url app_name = 'account' urlpatterns = [ url(r'^profile/$', views.profile, name='profile'), url(r'^profile/edit/$', views.update_profile, name='edit_profile'), url(r'^home/$', views.home, name='home'), ] HTML {% block body %} <div class="container"> <form method="POST" action="."> {% csrf_token %} {{ form.as_p }} … -
How do I update my endpoint with new foreign keys in javascript/react?
First post and kind of a newbie in the javascript/react/django world. I am making a form for a school-project and my intention is that the submit should add objects to multiple tables in my database. I am using django with react so the form is created in javascript and I am using fetch() to submit the data. The idea is that the first fetch creates a new object in one table that is later refered to in the second table using a foreign key. However when the fetch to the second table executes is says that the new primary key doesn't exist even though the first fetch has gone through. I guess that the "instance" needs to be updated somehow so that the second fetch knows that new foreign keys exist. I've played around with forceUpdate but that doesn't seem to do the job. Here is my code for the handlesubmit(): handleSubmit = e => { e.preventDefault(); var locationNames = []; var locationValues = []; for (var i = 0, l = e.target.location[0].options.length; i< l; i++) { locationNames.push(e.target.location[0].options[i].attributes['name'].value); locationValues.push(e.target.location[0].options[i].attributes['value'].value); }; if(!(locationNames.includes(this.state.location)) && !(locationValues.includes(this.state.location.toString()))){ console.log("added new location"); name = this.state.location; const lng = this.state.lng; const lat = this.state.lat; const location = … -
Django rest framework model serializer read_only_fields not working
I have the following ListCreateAPIView class TodoAPI(generics.ListCreateAPIView): permission_classes = (IsAuthenticated, ) serializer_class = TodoSerializer def get_queryset(self): user = self.request.user return Todo.objects.filter(user=user) And in my serializers.py, I have class TodoSerializer(serializers.ModelSerializer): class Meta: model = Todo fields = ('id', 'title', 'description', 'completed', 'created_at') read_only_fields = ('id', ) But the problem is when I POST data into the form, I get the following error: IntegrityError at /todo/ NOT NULL constraint failed: todo_todo.user_id models.py class Todo(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.TextField(max_length=50) description = models.TextField(max_length=200, blank=True, null=True) completed = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) -
Django ModelForms is ignoring a clean field method
I have the following model where I have a DateField: class E(models.Model): name = models.CharField(max_length=255 description = models.TextField(max_length=EVENT_DESCRIPTION_MAX_LENGTH) start_date = models.DateField(verbose_name='Start Date') the ModelForm: class EventModelForm(forms.ModelForm): class Meta: model = Event fields = ['name', 'description''start_date'] def clean_start_date(self): datetime_format = '%a %b %d %Y' start_date = self.cleaned_data['start_date'] return datetime.strptime(start_date, datetime_format) My issue is that Django ignores the clean method for the start_date, but take in consideration the clean methods for the other fields. So I use the debugger to check, and I see that is appearing in change_data, but not in cleaned_data changed_data: <class 'list'>: [name', 'description', ''start_date'] cleaned_data: name, description which is strange, so I checked the input, and looks ok: <input name="start_date" class="c-fi' type="text"> I don't understand why is not calling the clean method, instead make a validation on the Model a fails, so this is why I need clean to change date format before saving. -
How can I display the number of items per category in the Django admin filter panel?
In Django admin, how could I add the number of items for each category of a filter directly in the filter panel (see mock-up below)? Current filter panel Desired filter panel Model I am filtering my UserProfile table by its languages field. This is a many-to-many field on the Language table. class UserProfile(models.Model): # ... languages = models.ManyToManyField(Language, blank=True) class Language(models.Model): name = models.CharField(max_length=64) # ... My current admin configuration is: @admin.register(UserProfile): class UserProfileAdmin(admin.ModelAdmin): # ... list_filter = ('languages',) -
django + iis request.body problems
local host used macOS 10.13 python 3.6 django 2.0.2 windowServer2012R2 used django 2.0.2, python 3.4, iis ,fastCGI if run localhost this screenshot enter image description here and put data and post return 200 connect success enter image description here but window Server run not work css this screenshot enter image description here and put data and post exception the JSON object must be str, not 'bytes' in json.loads(request.body) django debug Post data _content_type 'application/json' _content ('{\r\n' ' "UserEmail": "",\r\n' ' "UserPassword": "",\r\n' ' "UserSex": 1,\r\n' ' "UserAge": 1,\r\n' ' "DeviceId": "",\r\n' ' "PushKey": "",\r\n' ' "OS": 1,\r\n' ' "OSVersion": ""\r\n' '}') enter image description here i think encoding problem but i can't solve localhost print(request.body) result b'{\n "UserEmail": "",\n "UserPassword": "",\n "UserSex": 1,\n "UserAge": 1,\n "DeviceId": "",\n "PushKey": "",\n "OS": 1,\n "OSVersion": ""\n}' windowserver b'_content_type=application%2Fjson&_content=%7B%0D%0A++++%22UserEmail%22%3A+%22%22%2C%0D%0A++++%22UserPassword%22%3A+%22%22%2C%0D%0A++++%22UserSex%22%3A+1%2C%0D%0A++++%22UserAge%22%3A+1%2C%0D%0A++++%22DeviceId%22%3A+%22%22%2C%0D%0A++++%22PushKey%22%3A+%22%22%2C%0D%0A++++%22OS%22%3A+1%2C%0D%0A++++%22OSVersion%22%3A+%22%22%0D%0A%7D' plz help -
NoReverseMatch at /upload/ when redirecting
When I am executing the code, I get this error. NoReverseMatch at /upload/ Reverse for 'compare' with keyword arguments '{u'uploaded_file_url2': '/media/SAMPLE1.xlsx', u'uploaded_file_url': '/media/SAMPLE.xlsx'}' not found. 1 pattern(s) tried: ['home/'] urls.py urlpatterns = [ url(r'^upload/', views.upload,name='upload'), url(r'^compare/',views.home,name='home'), ] view.py from django.shortcuts import render,redirect from django.conf import settings from django.core.files.storage import FileSystemStorage from django.conf.urls import url from django.http import HttpResponseRedirect from django.urls import reverse def upload(request): if request.method == 'POST': myfile=request.FILES['myfile'] myfile2=request.FILES["myfile2"] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) filename2=fs.save(myfile2.name, myfile2) uploaded_file_url = fs.url(filename) uploaded_file_url2 = fs.url(filename2) return redirect(reverse('myapp:compare',kwargs={"uploaded_file_url":uploaded_file_url,"uploaded_file_url2":uploaded_file_url2 } )) return render(request, 'myapp/upload.html') def compare(request,uploaded_file_url,uploaded_file_url2): a=uploaded_file_url b=uploaded_file_url2 #some code here return render(request,'myapp/compare.html',{"a":a,"b":b}) Here I want to pass uploaded_file_url and uploaded_file_url2 to compare -
My Django App can't connect to DB through a TypeError
My Django web application can't run because of a TypeError through my DB connection. File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/backends/sqlite3/base.py", line 198, in get_new_connection conn = Database.connect(**conn_params) TypeError: Can't convert 'int' object to str implicitly The error seems to happen when DB try to connect with connection parameters. Also, I'm trying to open my DB (sqlite) with credentials and connection was successful. Other django commands like python manage.py flush didn't work through a DB connection can't be established. settings.py file : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } Any suggestions ? -
How do i pass id in url?
In my views.py i'm using two parameters in my function. In my form action attribute i'm trying to pass the url but NoReverseMatch is showing. I guess i'm not passing the id along with url and i don't know how to do it. This is what i'm doing: <form action = "{% url 'studentapp:editrow' %}" id="editform" method = "POST"> This edit button is inside a for loop <a data-href="{{item.id}}" onclick="update_entry({{item.id}})" class="btn btn-danger" data-toggle="modal"> Edit </a> This is my function in views.py: def editrow(request, rowid): This is my urls.py url(r'^editrow/(?P<rowid>[0-9]+)/$', views.editrow, name='editrow'), -
Is there any aggregator for Django rest framework?
In the home page of an app we need to call multiple resources like Sliders, Top Brands, Best Selling Products, Trending Products etc. Single Call: www.example.com/api/GetAllInHome Multiple Calls: www.example.com/api/GetSliders www.example.com/api/GetTopBrands www.example.com/api/GetBestSellingProducts www.example.com/api/GetTrendingProducts -
Django polls Error "GET /polls/ HTTP/1.1" 404 2127
\mysite>python manage.py runserver Performing system checks... System check identified no issues (0 silenced). April 25, 2018 - 12:39:04 Django version 2.0.4, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: /polls/ [25/Apr/2018 12:39:13] "GET /polls/ HTTP/1.1" 404 2127 -
Django channels 2 with selenium test failed
I am trying to follow Django channels tutorial. I was able to implement chat functionality as discribed here. But unittests completly copy pasted from this page failed with following error AttributeError: Can't pickle local object 'DaphneProcess.__init__.<locals>.<lambda>'. Full traceback: Traceback (most recent call last): File "C:\Users\user\PycharmProjects\django_channels_test\venv35\lib\site-packages\django\test\testcases.py", line 202, in __call__ self._pre_setup() File "C:\Users\user\PycharmProjects\django_channels_test\venv35\lib\site-packages\channels\testing\live.py", line 42, in _pre_setup self._server_process.start() File "C:\Users\user\AppData\Local\Programs\Python\Python35\Lib\multiprocessing\process.py", line 105, in start self._popen = self._Popen(self) File "C:\Users\user\AppData\Local\Programs\Python\Python35\Lib\multiprocessing\context.py", line 212, in _Popen return _default_context.get_context().Process._Popen(process_obj) File "C:\Users\user\AppData\Local\Programs\Python\Python35\Lib\multiprocessing\context.py", line 313, in _Popen return Popen(process_obj) File "C:\Users\user\AppData\Local\Programs\Python\Python35\Lib\multiprocessing\popen_spawn_win32.py", line 66, in __init__ reduction.dump(process_obj, to_child) File "C:\Users\user\AppData\Local\Programs\Python\Python35\Lib\multiprocessing\reduction.py", line 59, in dump ForkingPickler(file, protocol).dump(obj) AttributeError: Can't pickle local object 'DaphneProcess.__init__.<locals>.<lambda>' My consumer class: class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group async def chat_message(self, event): message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) My tests … -
Django Class Based Views: Is it considered wrong or bad to extend dispatch method?
In our django codebase, we extend dispatch method for the following reasons: To set variables that are common to both GET/POST methods. To restrict user access (For this created a separate mixin that just extends dispatch and does the checks) If its considered bad, why is that and What is the alternative? -
(Django) AJAX call doesn't hit view, form submit does. Why?
I have a form that successfully hits this url: url(r'(?P<slug>[a-z0-9-_]+?)-(?P<product_id>[0-9]+)-(?P<hotel>[0-1]+)-(?P<shuttle>[0-1]+)/add/$', views.product_add_to_cart, name="add-to-cart"), This is the form: <form id="product-form" role="form" class="product-form clearfix" method="post" action="{% url 'product:add-to-cart' product_id=product.pk slug=product.get_slug hotel=1 shuttle=1 %}" novalidate> </form> However when I try to hit the same url from a button click with an AJAX call like this: $(".book-event-variants .book-main").click(() => { const id = $(".book-main").attr("event-id"); const slug = $(".book-main").attr("event-slug"); $.ajax({ url: "/products/" + slug + "-" + id + "-0-0/add", type: 'POST', success: () => { onAddToCartSuccess(); }, error: (response) => { onAddToCartError(response); } }); }); I am getting an error: jquery.js?eedf:9566 POST http://127.0.0.1:8000/products/sofia-fall-2018-1-0-0/add 404 (Not Found) Why is there a difference between the two? Why can't I make the call? First concern: Can different namespaces be a problem. e.g. I am am doing the AJAX request from a different app template. -
No Search results after query when using Q Expression in django
I have the following class based view which I have Implemented a custom query functionality but when I try to search I am not getting the results. I have the data available in the db for employee details but no results. o far this is how my Q filter looks like. class PayslipSearch(ListAPIView): # queryset = Payslip.obejcts.all() serializer_class = PayslipDetailSerializer filter_backends = [SearchFilter] search_fields = ['employee__user__first_name', 'employee__user__last_name', 'basic_salary', # 'payment_mode', # 'payslip_no', # 'month_ending', # 'deductions', # 'allowances' ] def get_queryset(self, *args, **kwargs): queryset_list = Payslip.objects.all() # call GETs get to get your values query = self.request.GET.get("q") print(query) if query: queryset_list = Payslip.objects.filter( Q(employee__first__name__icontains=query) | Q(employee__user__last_name__icontains=query) # Q(basic_salary__salary_value__icontains=query) # Q(payment_mode__icontains=query) | # Q(payslip_no__icontains=query) | # Q(month_ending__icontains=query) | # Q(allowances__icontains=query) | # Q(deductions__icontains=query) ).distinct() return queryset_list -
I'm getting an "ERROR (spawn error)" when I try to start my celery/supervisor instance
I've gone through how to use celery on my django production server using supervisor. However when I try to start supervisor with sudo supervisorctl start app-celery - it returns: app-celery: ERROR (spawn error) Here is my config /etc/supervisor/conf.d/app-celery.conf: [program:app-celery] command=/home/zorgan/app/env/bin/celery worker -A draft1 --loglevel=INFO directory=/home/zorgan/app/draft1 numprocs=1 stdout_logfile=/var/log/supervisor/celery.log stderr_logfile=/var/log/supervisor/celery.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase this if you have very long running tasks. stopwaitsecs = 600 stopasgroup=true ; Set Celery priority higher than default (999) ; so, if rabbitmq is supervised, it will start first. priority=1000 I've followed the tutorial word for word - I don't know why it is not working. I've checked that my path to celery is /home/zorgan/app/env/bin/celery, and my celery.py and tasks.py is in /home/zorgan/app/draft1. As well as the init file in /home/zorgan/app/draft1 being changed to: from __future__ import absolute_import, unicode_literals #This will make sure the app is always imported when #Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ['celery_app'] Here's my celery.py: import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'draft1.settings') app = Celery('draft1') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() Are there any red flags here? … -
Show any type of file saved in a model to a container div in the template
Hi am working on django I would like to show a file which is saved in the django model into a div in the django template.The file can be any format like .txt, .html, .png, .gif etc... my model look like this class RepositoryFiles(models.Model): file = models.FileField(upload_to='files') name = models.CharField(max_length=255) class Meta: unique_together = (('file', 'name'),) -
Python-django.db.migrations.exceptions.NodeNotFoundError
In existing wagtail project ,i run python3 manage.py makemigrations gives this issue django.db.migrations.exceptions.NodeNotFoundError: Migration 'collection-name' dependencies reference nonexistent parent node ('wagtailcore', '0029_unicode_slugfield_dj19') if i hide wagtailcore dependencies from that particular collection,then i am getting other wagtail dependancies error(like wagtail images). so i think this issue related to wagtail How do i resolve it?? -
Direct assignment to the forward side of a many-to-many set is prohibited. Use emails_for_help.set() instead
I am new to Django and didn't find any reference regarding this issue. I am getting this error when i use many to many field in django model(models.py). i guess the issue is assining m2m filed in view(views.py) from form(forms.py). How to assign m2m field in view. Django version 2.O python 3.5 models.py class User(AbstractUser): username=models.CharField(max_length=20) email = models.EmailField(_('email address'), unique=True) class Setupuser(models.Model): organization=models.CharField(max_length=200,blank=False,null=True) emails_for_help = models.ManyToManyField(User) views.py class Set_user(FormView): template_name="pkm_templates/set_up_user.html" form_class = Set_User_Form success_url = '/thanks/' def form_valid(self, form): org = form.cleaned_data.get('organization') emails = form.cleaned_data.get("share_email_with") instance = Setupuser(organization=org,emails_for_help=emails) instance.save() return redirect("/") forms.py class Set_User_Form(ModelForm): emails_for_help = forms.ModelMultipleChoiceField(queryset=User.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model=Setupuser fields=["organization","emails_for_help"] -
Django OSError [Errno 22] Invalid Argument
thanks for taking the time to read this. First off, I have found many answers on google to this question, however, after implementing many of them, none have fixed my issue. I am getting the following error: OSError at /index/[Errno 22] Invalid argument: 'C:\\Users\\username\\PycharmProjects\\DjangoTestS\\templates\\ <django.template.backends.django.Template object at 0x00000262E5F2F2B0>' I believe this is due to my django code failing to find my template file. The code to get the template in django is as follows: index_model = loader.get_template('index.html') and my template dict is as follows: 'DIRS': [os.path.join(BASE_DIR, 'templates'), 'C:\\Users\\username\\PycharmProjects\\DjangoTestS',], Solutions from similar questions I have tried: 1) Hard coded the project location into the templates dict. Originally it was a way that should generally find the templates folder of any project, but that did not work. The hard coded way did not work either. 2) A pycharm shell helper change that hard coded a path element to the pycharm projects folder. Did not work either. Please let me know what I am doing wrong. I hope it is obvious to you, because this has held me up for a few days. Thank you! -
Django Add Form to Formset
This is example to make an form object. Is there any way to add that form to a formset? obj = get_object_or_404(example_model, id=id) form = example_form(instance=obj) Or how to make a formset which each forms have an insctance? -
Passing parameters from Django view to form not working
I have been trying to pass parameter from my createview to form, but that parameter is not received at the form. I don't know what is wrong, has been trying to solve it for some time Here is my view, class ItemCreateView(LoginRequiredMixin,CreateView): form_class = ItemForm template_name = 'form.html' def get_form_kwargs(self): kwargs = super(ItemCreateView, self).get_form_kwargs() kwargs['user'] = self.request.user # pass the 'user' in kwargs return kwargs def get_context_data(self,**kwargs): context = super(ItemCreateView,self).get_context_data(**kwargs) context['title'] = 'Add Items' return context def form_valid(self,form): instance = form.save(commit = False) instance.user = self.request.user instance.save() return super(ItemCreateView, self).form_valid(form) The following is my form class: from django import forms from .models import Item from restaurants.models import RestaurantLocation class ItemForm(forms.ModelForm): class Meta: model = Item fields=[ 'name', 'restaurant', 'contents', 'excludes', 'public' ] def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) print(user) super(ItemForm,self).__init__(*args,**kwargs) self.fields['restaurant'].queryset = RestaurantLocation.objects.filter(owner=user) Can somebody please help me here? -
How to get pre-populated form using edit button
I'm trying to get a pre-populated form using "edit" button that i'm using in my table. I've tried everything but i'm not able to get pre-populated form. I'm using only one form to add as well as edit. this is my views.py edit function: def edit_row(request, rowid): item = get_object_or_404(Studentapp, id=rowid) print item if request.method=="POST": form = EntryForm(request.POST, instance=item) if form.is_valid(): post=form.save(commit=False) post.save() return HttpResponseRedirect(reverse('studentapp:index'),rowid.id) else: form=EntryForm(instance=item) return render(request, 'index.html',{'form':form}) This is the form that i'm using: <div class="modal fade" id="addform" role="dialog"> <div class="modal-dialog"> <div class = "modal-content"> <div class = "modal-header"> <button type = "button" class = "close" data-dismiss="modal">&times;</button> <h3 class="modal-title"><b>Add Student</b></h3> </div> <div class = "modal-body"> <form action = "{% url 'studentapp:addstudent' %}" id="addform" method = "POST"> {% csrf_token %} <div class = "form-group"> <label for = "your_name">Your name: </label> <input class = "form-control" id="new_name" type = "text" name="your_name" value="{{ current_name }}" placeholder="Enter your name"> </div> <div class="form-group"> <label for = "course_name">Course: </label> <input id="new_course" class = 'form-control' type = "text" name="course_name" value="{{ current_course }}" placeholder="Enter your course"> </div> <div class = "form-group"> <label for = "rollno">Roll No.: </label> <input id="new_rollno" type = "text" class = 'form-control' name="rollno" value="{{ current_roll }}" placeholder="Enter your roll number"> </div> <div class …