Home > Software engineering >  how to connect bootstrap form to Django database to create a model instance
how to connect bootstrap form to Django database to create a model instance

Time:01-27

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" >
    {% csrf_token %}
    {{ form.as_p }}
    <p >
        Create your task:
    </p>
    <div >
        <div >
            <input type="text"  placeholder="Enter your task here:" name="task">
        </div>
        <div >
            <input type="time"  placeholder="Enter your time here:" name="time">
        </div>
        <div >
            <select  id="inlineFormCustomSelect" name="status">
                <option selected>Choose...</option>
                <option value="1">In Complete</option>
                <option value="2">Completed</option>
            </select>
        </div>
        <div >
            <button type="button" >Confirm</button>
        </div>
        <div ></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.

CodePudding user response:

welcome to django!

if you are new to django it's better to follow official tutorial first

https://docs.djangoproject.com/en/4.0/intro/tutorial01/

I saw you made some progress but to fill the gaps quickly, tutorial is the best way

so after this I believe you will be able quickly answer your question

  •  Tags:  
  • Related