'how to connect bootstrap form to Django database to create a model instance
I am new to bootstrap and django both, so please don't mind my skills. I have made a custom bootstrap form for my todo app that will add item in the database which looks like this add task field here is the bootstrap code:
<form method="post" class="form-control">
{% csrf_token %}
{{ form.as_p }}
<p class="lead">
Create your task:
</p>
<div class="form-row">
<div class="col-7">
<input type="text" class="form-control" placeholder="Enter your task here:" name="task">
</div>
<div class="col-2">
<input type="time" class="form-control" placeholder="Enter your time here:" name="time">
</div>
<div class="col-2">
<select class="custom-select mr-sm-2" id="inlineFormCustomSelect" name="status">
<option selected>Choose...</option>
<option value="1">In Complete</option>
<option value="2">Completed</option>
</select>
</div>
<div class="col-1">
<button type="button" class="btn btn-outline-primary">Confirm</button>
</div>
<div class="row mt-3"></div>
</div>
</form>
the model and the form are below:
class Task(models.Model):
choices = (
('Completed', 'Completed'),
('In Complete', 'In Complete'),
)
name = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
task = models.CharField(max_length=200, null=False, blank=False)
time = models.TimeField(auto_now_add=False, blank=True)
status = models.CharField(max_length=200, choices=choices, null=True, blank=False)
def __str__(self):
return self.task
from django.forms import ModelForm
from .models import *
from django import forms
class TaskForm(ModelForm):
class Meta:
model = Task
fields = '__all__'
and the view is:
def create_task(request):
form = TaskForm()
if request.method == 'POST':
form = TaskForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
context = {'form': form}
return render(request, 'task/home.html', context)
what I'm asking is how can I connect this form to database, so it can create model instance. thanks in advance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|