How to store many to many fields with checkbox values in databse using django - django

With this code i want to store multiple courses to the student table.But this code is not working.Neither it throws any error neither saves any data.The main problem is while clicking submit button the submit button does not perform any action at all.It does not load the submit button.How can i solve this??
I think the problem is in add_student.html template.When i return form.error it throws course.Is there anything i have to change??but i want to keep my design like this
models.py
class Course(models.Model):
title = models.CharField(max_length=250)
basic_price = models.CharField(max_length=100)
advanced_price = models.CharField(max_length=100)
basic_duration = models.CharField(max_length=50)
advanced_duration = models.CharField(max_length=50)
def __str__(self):
return self.title
class Student(models.Model):
name = models.CharField(max_length=100)
course = models.ManyToManyField(Course)
address = models.CharField(max_length=200)
email = models.EmailField()
phone = models.CharField(max_length=15)
image = models.ImageField(upload_to='Students',blank=True)
joined_date = models.DateField()
def __str__(self):
return self.name
views.py
def addstudent(request):
courses = Course.objects.all()
if request.method == 'POST':
form = AddStudentForm(request.POST,request.FILES)
if form.is_valid():
student = form.save()
student.save()
# student.course.set(courses)
messages.success(request, 'student saved.')
return redirect('students:add_student')
else:
return HttpResponse(form.errors) # it returns course.i think the problem is while saving the course
else:
form = AddStudentForm()
return render(request,'students/add_student.html',{'form':form,'courses':courses})
forms.py
class AddStudentForm(forms.ModelForm):
course = forms.ModelMultipleChoiceField( queryset=Course.objects.all(), widget=forms.CheckboxSelectMultiple)
class Meta:
model = Student
fields = ['name','course','email','address','phone','image','joined_date']
add_student.html
<form action="{% url 'students:add_student' %}"
method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<h5>Full Name <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="name" class="form-control" required data-validation-required-message="This field is required"> </div>
</div>
<div class="form-group">
<h5>Courses <span class="text-danger">*</span></h5>
<div class="controls">
{% for course in courses %}
<input name ="course" type="checkbox" id="{{course.title}}" required value="{{course.id}}">
<label for="{{course.title}}">{{course.title}}</label>
{% endfor %}
</div>
</div>
<div class="form-group">
<h5>Address<span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="address" class="form-control" required data-validation-required-message="This field is required"> </div>
</div>
<div class="form-group">
<h5>Phone Number <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="phone" data-validation-required-message="This field is required" class="form-control" required> </div>
</div>
<div class="form-group">
<h5>Email <span class="text-danger">*</span></h5>
<div class="controls">
<input type="email" name="email" data-validation-required-message="This field is required" class="form-control" required> </div>
</div>
<div class="form-group">
<h5>Joined Date <span class="text-danger">*</span></h5>
<div class="controls">
<input type="date" name="joined_date" data-validation-required-message="This field is required" class="form-control" required> </div>
</div>
<div class="form-group">
<h5>Image <span class="text-danger">*</span></h5>
<div class="controls">
<input type="file" name="image" class="form-control" > </div>
</div>
<div class="text-xs-right">
<button type="submit" class="btn btn-info">Submit</button>
</div>
</form>

I'd recommend this solution:
courses = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset= Course.objects.all())
in views.py
if form.is_valid():
student = form.save(commit=False)
courses = form.cleaned_data['courses']
student.course = courses
student.save()
ps. it's a good practice to name m2m fields in plural:
courses = models.ManyToManyField(Course)
here's what I meant with templates:
in add_student.html
Comment out whole <form> block and replace it with Django's {{ form }} and see how it'd render
You have a queryset of courses passed in context to template. Try to change it from:
{% for course in courses %}
<input name ="course" type="checkbox" id="{{course.title}}" required value="{{course.title}}">
<label for="{{course.title}}">{{course.title}}</label>
{% endfor %}
to just:
{{ form.cource }}

Try a Class Based View
class CreateStudent(CreateView):
model = Student
form_class = AddStudentForm
template_name = "add_student.html"

Related

Why the changes I made in the Django model not being reflected in the html form?

I have a field named 'amount' of type Floatfield.
I changed it to DecimalField and ran makemigrations and migrate commands and it successfully generated 0002_alter_expense_amount.py file.
This change is reflected in the database.
But in the html form when I try to add new amount It's showing this message.
When I tried the same from the admin panel it was successful
What should I do to make the html form accept the decimal value? Is there anything I'm missing?
models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils.timezone import now
class Expense(models.Model):
amount = models.DecimalField(decimal_places=2, max_digits=10)
date = models.DateField(default=now)
description = models.TextField()
owner = models.ForeignKey(to=User, on_delete=models.CASCADE)
category = models.CharField(max_length=255)
def __str__(self):
return self.category
class Meta:
ordering = ['-date']
class Category(models.Model):
name = models.CharField(max_length=255)
class Meta:
verbose_name_plural = 'Categories'
def __str__(self):
return self.name
views.py
#login_required(login_url="/authentication/login")
def add_expenses(request):
categories = Category.objects.all()
context = {
'categories': categories,
'values': request.POST
}
if request.method == 'POST':
amount = request.POST['amount']
description = request.POST['description']
date = request.POST['expense_date']
category = request.POST['category']
Expense.objects.create(owner=request.user, amount=amount, date=date, category=category, description=description)
messages.success(request, 'Expense saved successfully')
return redirect('expenses')
else:
return render(request, 'expenses/add-expenses.html', context)
html form
<form action="{% url 'add-expenses' %}" method="post">
{% include 'partials/messages.html' %}
{% csrf_token %}
<div class="form-group mb-3">
<label for="">Categories</label>
<select class="form-control form-control" name="category" required>
{% for category in categories%}
<option name="category" value="{{category.name}}">
{{category.name}}
</option>
{% endfor %}
</select>
</div>
<div class="form-group mb-3">
<label for="">Amount</label>
<input type="number" class="form-control form-control-sm" name="amount" required />
</div>
<div class="form-group mb-3">
<label for="">Description</label>
<input type="text" class="form-control form-control-sm" name="description" value="{{values.description}}">
</div>
<div class="form-group mb-3">
<label for="">Date</label>
<div class="d-grid gap-2 col-3">
<input type="date" class="form-control form-control-sm" name="expense_date" required>
</div>
</div>
<div class="d-grid gap-2 col-3">
<input type="submit" value="Add" class="btn btn-outline-dark" />
</div>
</form>

django form return Cannot assign "'1'": "Primary.album" must be a "PrimaryAlbum" instance

Am working on school database, when I'm trying to submit my django form using pure html form, it throws me an error like this: ValueError at /primary Cannot assign "'1'": "Primary.album" must be a "PrimaryAlbum" instance. How can i solve this error please?
Am using this method for the first time:
class PrimaryCreativeView(LoginRequiredMixin, CreateView):
model = Primary
fields = ['profilePicture', 'firstName', 'sureName',
'gender', 'address', 'classOf', 'album',
'hobbies', 'dateOfBirth','year',
'name', 'contact', 'homeAddress',
'emails', 'nationality','occupations',
'officeAddress', 'state', 'localGovernments',
'relationship' ]
template_name = 'post_student_primary.html'
success_url = reverse_lazy('home')
def form_valid(self, form):
form.instance.user = self.request.user
return super (PrimaryCreativeView, self).form_valid(form)
so I changed it to this method down below, but I don't know why it throws me this error:ValueError at /primary Cannot assign "'1'": "Primary.album" must be a "PrimaryAlbum" instance. when I submitted the form. How can I solve? And why this error is shown?
my Views:
def primary_submit_form(request):
albums = PrimaryAlbum.objects.filter(user=request.user)
if request.method == 'POST':
addmisssion_number = request.POST.get('addmisssion_number')
profile_picture = request.POST.get('profile_picture', None)
first_name = request.POST.get('first_name')
sure_name = request.POST['sure_name']
gender = request.POST['gender']
address_of_student = request.POST['address_of_student']
class_Of_student = request.POST['class_Of_student']
album = request.POST['album']
date_of_birth = request.POST['date_of_birth']
nationality_of_student = request.POST['nationality_of_student']
state_of_student = request.POST['state_of_student']
local_government_of_student = request.POST['local_government_of_student']
certificate_of_birth_photo = request.FILES.get('certificate_of_birth_photo')
residential_certificate_photo = request.FILES.get('residential_certificate_photo')
name = request.POST['name']
contact = request.POST['contact']
address_2 = request.POST['address_2']
nationality_2 = request.POST['nationality_2']
occupations = request.POST['occupations']
work_address = request.POST['work_address']
state_2 = request.POST['state_2']
local_government_2 = request.POST['local_government_2']
relationship = request.POST['relationship']
student_create = Primary.objects.create(
addmisssion_number=addmisssion_number, profile_picture=profile_picture,
first_name=first_name, sure_name=sure_name, gender=gender, address_of_student=address_of_student,
class_Of_student=class_Of_student, album=album, date_of_birth=date_of_birth,
nationality_of_student=nationality_of_student, state_of_student=state_of_student, local_government_of_student=local_government_of_student,
certificate_of_birth_photo=certificate_of_birth_photo, residential_certificate_photo=residential_certificate_photo,
name=name, contact=contact, address_2=address_2, nationality_2=nationality_2, occupations=occupations, work_address=work_address,
state_2=state_2, local_government_2=local_government_2, relationship=relationship
)
student_create.save()
return redirect('Primary-Albums')
return render(request, 'create_primary_student_information.html', {'albums':albums})
my models:
class PrimaryAlbum(models.Model):
name = models.CharField(max_length=100)
user = models.ForeignKey(User,
on_delete=models.CASCADE)
def __str__(self):
return self.name
class Primary(models.Model):
addminssion_number = models.CharField(max_length=40)
profilePicture = models.FileField(upload_to='image')
first_name = models.CharField(max_length=40)
sure_name = models.CharField(max_length=40)
gender = models.CharField(max_length=25)
address_of_student = models.CharField(max_length=50)
class_Of_student = models.CharField(max_length=20)
date_of_birth = models.CharField(max_length=20)
album = models.ForeignKey(PrimaryAlbum, on_delete=models.CASCADE)
hobbies = models.TextField(blank=True, null=True)
nationality_of_student = models.CharField(max_length=50)
state_of_student = models.CharField(max_length=30)
local_government_of_student = models.CharField(max_length=50)
certificate_of_birth_photo = models.FileField(upload_to='image')
residential_certificate_photo = models.FileField(upload_to='image')
#Guadians
name = models.CharField(max_length=30)
contact = models.CharField(max_length=15)
address_2 = models.CharField(max_length=50)
nationality_2 = models.CharField(max_length=50)
occupations = models.CharField(max_length=50)
work_address = models.CharField(max_length=50)
state = models.CharField(max_length=30)
local_government = models.CharField(max_length=50)
relationship = models.CharField(max_length=25)
def __str__(self):
return str(self.first_name)
My Templates:
<form action="{% url 'Create-Primary-Student' %}" method="POST">
{% csrf_token %}
<div class="container">
<div class="row">
<div class="text-center">
{% for message in messages %}
<h5>{{message}}</h5>
{% endfor %}
</div>
<div class="col-md-4">
<label for="" class="form-label">Admission Number</label>
<input type="text" class="form-control" name="addmission_number">
<br>
</div>
<div class="col-md-4">
<label for="" class="form-label">Profile Picture</label>
<input type="file" class="form-control" name="profile_picture">
</div>
<div class="col-md-4">
<label for="" class="form-label">First Name</label>
<input type="text" class="form-control" name="first_name">
</div>
<div class="col-md-4">
<label for="" class="form-label">Sure Name</label>
<input type="text" class="form-control" name="sure_name">
<br>
</div>
<div class="col-md-4">
<label for="" class="form-label"> Gender</label>
<input type="text" class="form-control" name="gender">
</div>
<div class="col-md-4">
<label for="" class="form-label">Student Address</label>
<input type="text" class="form-control" name="address_of_student">
</div>
<div class="col-md-4">
<label for="" class="form-label">Student Class</label>
<input type="text" class="form-control" name="class_Of_student">
</div>
<div class="col-md-4">
<label for="" class="form-label">Student Date Of Birth</label>
<input type="date" class="form-control" name="date_of_birth">
</div>
<div class="col-md-4">
<label for="" class="form-group">Year Of Graduation</label>
<select class="form-select" aria-label="Default select example" name="album">
<option selected>Select Year Of Graduation</option>
{% for album in albums %}
<option value="{{ album.id }}">{{ album.name }}</option>
{% endfor %}
</select>
<br>
</div>
<div class="col-md-4">
<label class="form-label">Example textarea</label>
<textarea class="form-control" rows="3" name="hobbies"></textarea>
<br>
</div>
<div class="col-md-4">
<br>
<label class="form-label">Student Country</label>
<input type="text" class="form-control" name="nationality_of_student">
</div>
<div class="col-md-4">
<br>
<label for="" class="form-label">State Of Origin</label>
<input type="text" class="form-control" name="state_of_student">
</div>
<div class="col-md-4">
<label for="" class="form-label">Student Local Government</label>
<input type="text" class="form-control" name="local_government_of_student">
<br>
</div>
<div class="col-md-4">
<label for="" class="form-label">Student Certificate of Birth Photo</label>
<input type="file" class="form-control" name="certificate_of_birth_photo">
</div>
<div class="col-md-4">
<label for="" class="form-label">Student Indigen Photo</label>
<input type="file" class="form-control" name="residential_certificate_photo">
</div>
<div class="text-center">
<br>
<h2>Guidance Information</h2>
<br>
</div>
<div class="col-md-4">
<label for="" class="form-label">Full Name</label>
<input type="text" class="form-control" name="name">
</div>
<div class="col-md-4">
<label for="" class="form-label">Phone Number</label>
<input type="text" class="form-control" name="contact">
</div>
<div class="col-md-4">
<label for="" class="form-label">Home Address</label>
<input type="text" class="form-control" name="address_2">
</div>
<div class="col-md-4">
<label for="" class="form-label">Country</label>
<input type="text" class="form-control" name="nationality_2">
</div>
<div class="col-md-4">
<label for="" class="form-label">Occupation</label>
<input type="text" class="form-control" name="occupations">
</div>
<div class="col-md-4">
<label for="" class="form-label">Work Address</label>
<input type="text" class="form-control" name="work_address">
</div>
<div class="col-md-4">
<label for="" class="form-label">State Of Origin</label>
<input type="text" class="form-control" name="state_2">
</div>
<div class="col-md-4">
<label for="" class="form-label">Local Government</label>
<input type="text" class="form-control" name="local_government_2">
</div>
<div class="col-md-4">
<label for="" class="form-label">Relationship To Student</label>
<input type="text" class="form-control" name="relationship">
</div>
<button type="submit" class="btn btn-success">create album</button>
</div>
</div>
</form>
You create this by assigning it to album_id, not album:
student_create = Primary.objects.create(
addmisssion_number=addmisssion_number,
profile_picture=profile_picture,
first_name=first_name,
sure_name=sure_name,
gender=gender,
address_of_student=address_of_student,
class_Of_student=class_Of_student,
album_id=album,
date_of_birth=date_of_birth,
nationality_of_student=nationality_of_student,
state_of_student=state_of_student,
local_government_of_student=local_government_of_student,
certificate_of_birth_photo=certificate_of_birth_photo,
residential_certificate_photo=residential_certificate_photo,
name=name,
contact=contact,
address_2=address_2,
nationality_2=nationality_2,
occupations=occupations,
work_address=work_address,
state_2=state_2,
local_government_2=local_government_2,
relationship=relationship,
)
I would however strongly advise to use a ModelFormĀ [Django-doc] this will remove a lot of boilerplate code from the view, do proper validation, and create the object effectively.

How to output fields to html template correctly from User model in Django ORM?

Task: Create a Django SQL query, pulling out only the required fields. Submit them to the template.
I have a Post model with a foreign key to a standard User model:
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
text = models.TextField()
pub_date = models.DateTimeField("date published", auto_now_add=True)
author = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name="posts"
)
Here is the required fragment in the HTML template, where you need to insert the author's name:
{% for post in posts %}
<h3>
Author: {{ post.author.first_name }}, Date: {{ post.pub_date|date:'d M Y' }}
</h3>
view function:
from django.shortcuts import render
from .models import Post
def index(request):
latest = (
Post
.objects
.order_by('-pub_date')[:10]
.select_related('author')
.values('pub_date', 'author__first_name')
)
return render(request, 'index.html', {'posts': latest})
Here's what the page fragment looks like on the local server:
template
And here is the final sql query shown by django debug toolbar:
Query
In the user table, I have one user and all posts are related to him. If I do not use .values in the view, then all the attributes of the author that I request in the template are displayed perfectly (for example, last_name, username, get_full_name()), but then sql requests all the fields of the user table (as it usually does), and I want get only certain ones to save memory. I also tried to recreate the project, use User = get_user_model(). Nothing helped.
You can refer this:
Model
from django.db import models
# Create your models here.
class CoachDetailsModel(models.Model):
coach_id=models.AutoField(primary_key=True)
name=models.CharField(max_length=100,help_text="Enter FullName")
email=models.EmailField(max_length=100,help_text="Enter Email id")
contact=models.BigIntegerField(help_text="Enter Mobile Number" ,null=True)
password=models.CharField(max_length=100,help_text="Enter Password")
coach_status=models.CharField(max_length=100,default='pending',help_text="Enter Password")
def __str__(self):
return self.email
class Meta:
db_table="Coach_details"
Views
def coach_register(request):
if request.method == "POST":
name= request.POST.get('name')
email = request.POST.get('email')
contact = request.POST.get('contact')
password = request.POST.get('password')
CoachDetailsModel.objects.create(name=name,email=email,contact=contact,password=password)
return render(request,'coach/coach-register.html')
### url
path('coach-register',coachviews.coach_register,name='coach_register'),
Html page
<form method="POST" id="contactForm" name="contactForm" class="contactForm" enctype="multipart/form-data">
{% csrf_token %}
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="label" for="subject">Enter UserName</label>
<input type="text" class="form-control" name="name" id="subject" placeholder="UserName">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="label" for="subject">Enter Contact</label>
<input type="text" class="form-control" name="contact" id="subject" placeholder="Contact">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="label" for="subject">EMAIL-ADDRESS</label>
<input type="text" class="form-control" name="email" id="subject" placeholder="Email">
</div>
</div>
<div class="col-md-6">
<div class="form-group-col-6">
<label class="label" for="subject">PASSWORD</label>
<input type="text" class="form-control" name="password" id="subject" placeholder="Password">
</div>
</div>
<div class="col-md-12">
<div class="form-group col-9">
<input type="submit" value="Register" class="btn btn-primary">
<div class="submitting"></div>
</div>
</div>
</div>
</form>

How to get value in Dropdown list on edit in Django template

I have a form (edit_city.html) where I want to edit my record, there is also one dropdown
field in which data is retrieving from another model name Country. How can I get the exact
value in dropdown field, when I click on edit.
Here is my Code
class Country(models.Model):
CountryID = models.AutoField(primary_key=True)
CountryName = models.CharField(max_length=125, verbose_name="Country Name")
def __str__(self):
return self.CountryName
class City(models.Model):
CityID = models.AutoField(primary_key=True)
CityName = models.CharField(max_length=125, verbose_name='City Name')
Country = models.ForeignKey(Country, verbose_name='Country Name',
on_delete=models.CASCADE)
def __str__(self):
return self.CityName
views.py
def Edit_City(request, id):
city = City.objects.get(CityID=id)
country = Country.objects.all()
context = {
'city':city,
'country':country,
}
return render(request, 'City/edit_city.html', context)
edit_city.html
<form method="post" action="{% url 'update_city' %}">
{% csrf_token %}
<div class="row">
<div class="col-12">
<h5 class="form-title"><span>Edit City</span></h5>
</div>
{% include 'includes/messages.html' %}
<div class="col-12 col-sm-6">
<div class="form-group">
<label for="">Country</label>
<select class="form-control" name="country_id" required>
<option>Select Country</option>
{% for con in country %}
<option value="{{con.CountryID}}">{{con.CountryName}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="col-12 col-sm-6">
<div class="form-group">
<label>City Name</label>
<input type="text" class="form-control" name="city_name" value="{{city.CityName}}" required>
<input type="text" class="form-control" name="city_id" value="{{city.CityID}}" required hidden>
</div>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary">Update City</button>
</div>
</div>
</form>

how to save many to many field in django

I am trying to save students from addstudent form but it is not saving students and it is displaying error message 'error in form'.Is there any solutions for this code.I think the error is in html template.
Error is like this:
AttributeError at /students/add/student/
'ErrorDict' object has no attribute 'status_code'
Request Method: POST
Request URL: http://127.0.0.1:8000/students/add/student/
Django Version: 2.1.5
Exception Type: AttributeError
Exception Value:
'ErrorDict' object has no attribute 'status_code'
models.py
class Course(models.Model):
title = models.CharField(max_length=250)
basic_price = models.CharField(max_length=100)
advanced_price = models.CharField(max_length=100)
basic_duration = models.CharField(max_length=50)
advanced_duration = models.CharField(max_length=50)
class Student(models.Model):
name = models.CharField(max_length=100)
course = models.ManyToManyField(Course)
address = models.CharField(max_length=200)
email = models.EmailField()
phone = models.CharField(max_length=15)
image = models.ImageField(upload_to='Students',blank=True)
joined_date = models.DateField()
forms.py
class AddStudentForm(forms.ModelForm):
class Meta:
model = Student
fields = '__all__'
views.py
def addstudent(request):
courses = Course.objects.all()
if request.method == 'POST':
form = AddStudentForm(request.POST,request.FILES)
if form.is_valid():
student = form.save()
student.save()
messages.success(request,'student saved.')
return redirect('students:add_student')
# else:
# return HttpResponse(form.errors) --> it returns course
else:
form = AddStudentForm()
return render(request,'students/add_student.html',{'form':form,'courses':courses})
add_student.html
<form action="{% url 'students:add_student' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<h5>Full Name <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="name" class="form-control" required data-validation-required-message="This field is required"> </div>
</div>
<div class="form-group">
<h5>Course <span class="text-danger">*</span></h5>
<div class="controls">
<select name="course" id="select" required class="form-control">
<option value="">Select Your Course</option>
{% for course in courses %}
<option value="{{course.title}}">{{course.title}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group">
<h5>Address<span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="address" class="form-control" required data-validation-required-message="This field is required"> </div>
</div>
<div class="form-group">
<h5>Phone Number <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="phone" data-validation-match-match="password" class="form-control" required> </div>
</div>
<div class="form-group">
<h5>Email <span class="text-danger">*</span></h5>
<div class="controls">
<input type="email" name="email" data-validation-match-match="password" class="form-control" required> </div>
</div>
<div class="form-group">
<h5>Date <span class="text-danger">*</span></h5>
<div class="controls">
<input type="date" name="joined_date" data-validation-match-match="password" class="form-control" required> </div>
</div>
<div class="form-group">
<h5>Image <span class="text-danger">*</span></h5>
<div class="controls">
<input type="file" name="image" class="form-control" > </div>
</div>
<div class="text-xs-right">
<button type="submit" class="btn btn-info">Submit</button>
</div>
</form>
You should output the value of form.errors as suggested in the comments to discover the exact error. However, I can see two immediate issues that are likely causing form validation to fail.
Firstly, because your form contains an image upload you must set the enctype to multipart/form-data in the template:
<form action="{% url 'students:add_student' %}" method="post" enctype="multipart/form-data">
Second, the uploaded image exists in request.FILES so you need to pass that to the form:
form = AddStudentForm(request.POST, request.FILES)
You have to save many to many field after save method.
if form.is_valid():
student = form.save(commit=False)
student.save()
form.save_m2m()