My form does not send data to the database.
I have a form that after entering data and clicking 'Order' should send information to the database. However, this does not happen.
It is a 'cart' which, after sending the data, should save in the Order table information provided by the user as well as data on ordered products.
cart/views.py
def cart_detail(request, total=0, counter=0, cart_items = None):
try:
cart = Cart.objects.get(cart_id=_cart_id(request))
cart_items = CartItem.objects.filter(cart=cart, active=True)
for cart_item in cart_items:
total += (cart_item.product.price * cart_item.quantity)
counter += cart_item.quantity
except ObjectDoesNotExist:
pass
if request.method == 'POST':
total = request.POST['total']
billingName = request.POST['billingName']
billingAddress1 = request.POST['billingAddress1']
billingCity = request.POST['billingCity']
billingPostcode = request.POST['billingPostcode']
billingCountry = request.POST['billingCountry']
shippingName = request.POST['shippingName']
shippingAddress1 = request.POST['shippingAddress1']
shippingCity = request.POST['shippingCity']
shippingPostcode = request.POST['shippingPostcode']
shippingCountry = request.POST['shippingCountry']
order_details = Order.objects.create(total=total, billingName=billingName, billingAddress1=billingAddress1, billingCity=billingCity, billingPostcode=billingPostcode,billingCountry=billingCountry, shippingName=shippingName, shippingAddress1=shippingAddress1, shippingCity=shippingCity, shippingPostcode=shippingPostcode, shippingCountry=shippingCountry)
order_details.save()
for order_item in cart_items:
oi = OrderItem.objects.create(
product = order_item.product.name,
quantity = order_item.quantity,
price = order_item.product.price,
order = order_details
)
oi.save()
'''Reduce stock when order is placed or saved'''
products = Product.objects.get(id=order_item.product.id)
products.stock = int(order_item.product.stock - order_item.quantity)
products.save()
order_item.delete()
'''The terminal will print this message when the order is saved'''
print('The order has been created')
return redirect('cart:cart_detail')
return render(request, 'cart/cart.html', dict(cart_items = cart_items, total = total, counter = counter))
orders/models.py
from django.db import models
class Order(models.Model):
total = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='GBP Order Total')
created = models.DateTimeField(auto_now_add=True)
billingName = models.CharField(max_length=250, blank=True)
billingAddress1 = models.CharField(max_length=250, blank=True)
billingCity = models.CharField(max_length=250, blank=True)
billingPostcode = models.CharField(max_length=10, blank=True)
billingCountry = models.CharField(max_length=200, blank=True)
shippingName = models.CharField(max_length=250, blank=True)
shippingAddress1 = models.CharField(max_length=250, blank=True)
shippingCity = models.CharField(max_length=250, blank=True)
shippingPostcode = models.CharField(max_length=10, blank=True)
shippingCountry = models.CharField(max_length=200, blank=True)
class Meta:
db_table = 'Order'
ordering = ['-created']
def __str__(self):
return str(self.id)
class OrderItem(models.Model):
product = models.CharField(max_length=250)
quantity = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='GBP Price')
order = models.ForeignKey(Order, on_delete=models.CASCADE)
class Meta:
db_table = 'OrderItem'
def sub_total(self):
return self.quantity * self.price
def __str__(self):
return self.product
templates/cart/cart.html
<button class="btn send-click btn-md my-1 btn-block" data-toggle="modal" data-target="#inquiryModal">Complete Order</button>
<!-- Inquiry Modal -->
<div class="modal fade" id="inquiryModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="inquiryModalLabel">Complete Order</h5>
<button type="button" class="close" data-dismiss="modal">
<span>×</span>
</button>
</div>
<div class="modal-body">
<form action="{% url 'cart:cart_detail' %}" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="billingName" class="col-form-label">Name:</label>
<input type="text" name="billingName" class="form-control"
value="" required>
</div>
<div class="form-group">
<label for="billingAddress1" class="col-form-label">Adress:</label>
<input type="text" name="billingAddress1" class="form-control"
value="" required>
</div>
<div class="form-group">
<label for="billingCity" class="col-form-label">City:</label>
<input type="text" name="billingCity" class="form-control"
value="" required>
</div>
<div class="form-group">
<label for="billingPostcode" class="col-form-label">Post code:</label>
<input type="text" name="billingPostcode" class="form-control"
value="" required>
</div>
<div class="form-group">
<label for="billingCountry" class="col-form-label">Country:</label>
<input type="text" name="billingCountry" class="form-control"
value="" required>
</div>
<div class="form-group">
<label for="shippingName" class="col-form-label">Shop name:</label>
<input type="text" name="shippingName" class="form-control"
value="" required>
</div>
<div class="form-group">
<label for="shippingAddress1" class="col-form-label">Shop adress:</label>
<input type="text" name="shippingAddress1" class="form-control"
value="" required>
</div>
<div class="form-group">
<label for="shippingCity" class="col-form-label">Shop City:</label>
<input type="text" name="shippingCity" class="form-control"
value="" required>
</div>
<div class="form-group">
<label for="shippingPostcode" class="col-form-label">Shop Post code:</label>
<input type="text" name="shippingPostcode" class="form-control"
value="" required>
</div>
<div class="form-group">
<label for="shippingCountry" class="col-form-label">Shop Country:</label>
<input type="text" name="shippingCountry" class="form-control"
value="" required>
</div>
<hr>
<input type="submit" value="Order" class="btn send-click btn-md my-0 btn-block">
</form>
</div>
</div>
</div>
cart/urls.py
app_name='cart'
urlpatterns = [
path('add/<int:product_id>/', views.add_cart, name='add_cart'),
path('', views.cart_detail, name='cart_detail'),
path('remove/<int:product_id>/', views.cart_remove, name='cart_remove'),
path('full_remove/<int:product_id>/', views.full_remove, name='full_remove'),
]
Related
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>
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.
i wanted to check whether the name is exists in owner table or not.
this is my models.py
class owner(models.Model):
id = models.AutoField
name = models.CharField(max_length=255, blank=True, null=True)
password = models.CharField(max_length=255)
def __str__(self):
return self.name
this is my index.html
`
<form style="color:black" method="POST" action="check" class=" mt-3">
{% csrf_token %}
<div class="row mb-3">
<label for="inputText" class="col-sm-3 col-form-label">Username</label>
<div class="col-sm-8">
<input type="text" name="name" placeholder="Username" class="form-control">
</div>
</div>
<div class="row mb-3">
<label for="inputText" class="col-sm-3 col-form-label">Password</label>
<div class="col-sm-8">
<input type="text" name="password" placeholder="password" class="form-control">
</div>
</div>
<button class="btn btn-success mb-3" type="submit">Login</button>
<a class="btn btn-danger mb-3" href="index">Go Back</a>
</form>
this is my urls.py
path('index', views.index),
path('check', views.check),
this is my views.py
def check(request):
owners = owner.objects.all()
if request.method == "POST":
name = request.POST.get('name')
password = request.POST.get('password')
if owners.name == name and owners.password == password :
return render(request, "card/check.html")
it gives error on this line
if owners.name == name and owners.password == password :
`
how to check whether the name exist or not in table
owners = owner.objects.all() # This line fetches all the record in the owner table and returns queryset object
if owners.name == name and owners.password == password # The queryset can not have a name attribute. Use an instance.
Solution:
name = request.POST.get('name')
password = request.POST.get('password')
owner = Owner.objects.filter(name=name, password=password).first()
if owner:
return render(request, "card/check.html")
Here you can see my models.py.
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name = 'customer', null=True, blank=True)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200)
tel = models.CharField(max_length=200)
def __str__(self):
return self.name
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
imya = models.CharField(max_length=200, null=False)
familiya = models.CharField(max_length=200, null=False)
tel = models.CharField(max_length=200, null=False)
address = models.CharField(max_length=200, null=False)
city = models.CharField(max_length=200, null=False)
state = models.CharField(max_length=200, null=False)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False)
transaction_id = models.CharField(max_length=100, null=True)
def __str__(self):
return str(self.id)
Here you can see my forms.py. Here I just created forms, but, the data should be got from template inputs.
from django import forms
from django.forms import ModelForm
from .models import *
class OrderForm(forms.ModelForm):
class Meta:
model = Order
fields = '__all__'
views.py
def checkout(request):
data = cartData(request)
cartItems = data['cartItems']
order = data['order']
items = data['items']
form = OrderForm()
if request.method == 'POST':
name = request.POST.get('name')
surname = request.POST.get('surname')
email = request.POST.get('email')
number = request.POST.get('number')
address = request.POST.get('address')
city = request.POST.get('city')
state = request.POST.get('state')
form = OrderForm(request.POST)
if form.is_valid():
Order.object.create(
imya=name,
familiya=surname,
tel=number,
adres=address,
city=city,
state=state,
)
form.save()
return HttpResponse('Заказ отправлен', safe=False)
context = {'items':items, 'order':order, 'cartItems':cartItems, 'form':form}
return render(request, 'store/checkout.html', context)
My template:
<section class="shop checkout section">
<div class="container">
<div class="row">
<div class="col-lg-8 col-12">
<div class="checkout-form">
<h2>Make Your Checkout Here</h2>
<p>Please register in order to checkout more quickly</p>
<!-- Form -->
<form class="form" method="post" action="#">
{% csrf_token %}
<div class="row">
<div class="col-lg-6 col-md-6 col-12">
<div class="form-group">
<label>First Name<span>*</span></label>
<input type="text" name="name" placeholder="" required="required">
</div>
</div>
<div class="col-lg-6 col-md-6 col-12">
<div class="form-group">
<label>Last Name<span>*</span></label>
<input type="text" name="surname" placeholder="" required="required">
</div>
</div>
<div class="col-lg-6 col-md-6 col-12">
<div class="form-group">
<label>Email Address<span>*</span></label>
<input type="email" name="email" placeholder="" required="required">
</div>
</div>
<div class="col-lg-6 col-md-6 col-12">
<div class="form-group">
<label>Phone Number<span>*</span></label>
<input type="number" name="number" placeholder="" required="required">
</div>
</div>
<div class="col-lg-6 col-md-6 col-12">
<div class="form-group">
<label>Address<span>*</span></label>
<input type="text" name="adress" placeholder="" required="required">
</div>
</div>
<div class="col-lg-6 col-md-6 col-12">
<div class="form-group">
<label>City<span>*</span></label>
<input type="text" name="city" placeholder="" >
</div>
</div>
<div class="col-lg-6 col-md-6 col-12">
<div class="form-group">
<label>State<span>*</span></label>
<input type="text" name="state" placeholder="" required="required">
</div>
</div>
<div class="col-12">
<div class="form-group create-account">
<input id="cbox" type="checkbox">
<label>Create an account?</label>
</div>
</div>
<input type="submit" value="Продолжить">
</div>
</form>
In my views, I want to create an object for my order model. I tried this code, It's not giving any errors, but it's not working. PLease, help with saving the order.
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"