Abhay
Abhay

Reputation: 59

how to get value from html form into database using django python

I am newbie in python and django and I am facing difficulty in storing various fields of html page into database. E.g, I have a html page which contains 5 fields and one submit button . On submitting the form, I want all values from html form should be stored in table of the given database. Please help me in this.

Upvotes: 0

Views: 6421

Answers (2)

catherine
catherine

Reputation: 22808

models.py

from django.contrib.auth.models import User
from django.db import models

class AllocationPlan(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=50)
    data = models.CharField(max_length=4096)
    total = models.DecimalField(max_digits=10, decimal_places=2)

forms.py

from django import forms
from django.forms import ModelForm
from app_name.models import AllocationPlan   

class AllocationPlanForm(ModelForm):
    class Meta:
        model = AllocationPlan

views.py

from django.shortcuts import render
from app_name.forms import AllocationPlanForm

def add(request):
    if request.method == 'POST':
        form = AllocatinPlanForm(request.POST)
        if form.is_valid():
            form.save()
return render(request, 'page.html', {
    'form': AllocationPlanForm()
})

 page.html

 <form method="post">{% csrf_token %}
     {% for field in form %}
     {{field}}
     <input type="submit" value="Submit"/>
     {% endfor %}
 </form>

Upvotes: 1

Sami N
Sami N

Reputation: 1180

You should approach this from the angle of models, which map the model's attributes to database fields and can handily be used to create a form. This is called Object-Relational Mapping.

Start by creating (or modifying) models.py in your app's folder, and declare the model there (Essentially the fields you want to be stored). As mentioned, see Django's tutorials for creating forms and model-form mapping.

Upvotes: 1

Related Questions