asai nikhil
asai nikhil

Reputation: 37

getting data from html files and saving it to models django

I have created multiple input fields and when i click submit i need that data to be saved into my database through models.py that i created. However I am unable to understand how to redirect that data from html to django.

This is my html file

<!DOCTYPE html>

<head>
    <meta charset="utf-8" />
    <title>Cars</title>
    <h1> Enter sales data to store</h1>
</head>

<body>

<div>
    <form method="post">
        {% csrf_token %}
        <label for="billingnumber">Billing Number:</label>
        <input type="number" id="billingnumber" name="billingnumber"><br/>
        <label for="customername" >Customer Name :</label>
        <input type="text" id="customername" name="customername"><br/>
        <label for="purchasedate">Purchase Date:</label>
        <input type="date" id="purchasedate" name="purchasedate"><br/>
        <label for="price">Price:</label>
        <input type="number" id="price" name="price" ><br/>
        <label for="carcompany">Car Company:</label>
        <input type="text" id="carcompany" name="carcompany"><br/>
        <label for="carmodel">Car Model:</label>
        <input type="text" id="carmodel" name="carmodel"><br/>
        <label>Car Serial Number:</label>
        <input type="number" id="carserial" name="carserial"><br/>
        <label for="mfgdate">Car Manufacturing Date:</label>
        <input type="date" id="mfgdate" name="mfgdate"><br/>
        <label for="shippingdate">Shipping Date:</label>
        <input type="date" id="shippingdate" name="shippingdate"><br/>
        <button type="submit" value="submit">Submit</button>
        </form>
</div>
<a href="/">Home<a>
</body>
</html>

This is my models.py

class cars(models.Model):
    billingnumber = models.BigIntegerField(primary_key=True)
    customer = models.TextField()
    price = models.IntegerField()
    purchasedata = models.DateTimeField()
    carcompany = models.TextField()
    carmodel = models.TextField()
    carserialnumber = models.BigIntegerField()
    carmfgdate = models.DateTimeField()
    shippingdate = models.DateTimeField()

These are my url patterns

urlpatterns = [
    url(r"^$", TemplateView.as_view(template_name="index.html"), name="home"),
    url(r"^store/$", TemplateView.as_view(template_name="store.html"), name="store"),
    url(r"^access/$", TemplateView.as_view(template_name="access.html"), name="access"),
    url(r"^about/$", TemplateView.as_view(template_name="about.html"), name="about"),
    ]

I am unable to understand how to write views.py however this is how i tried to get data

from django.shortcuts import render
from django.views.generic import TemplateView
from django.http import HttpResponseRedirect

# Create your views here.
from .forms import myform
from .models import cars

def get_data(request):
        if request.method=="POST":
            form = myform(request.POST)
            if form.is_valid():
                cars.billingnumber(form)
                cars.save()
                return HttpResponse('<html><body>Data Saved</body></html>')
        else:
            form = myform()
            return render(request, 'sample.html', {'form': form})

forms.py

from django import forms

class myform(forms.Form):
    billingnumber = forms.CharField(label="billing number")

How can i change these files, I am a novice considering django

Upvotes: 1

Views: 8874

Answers (2)

umat
umat

Reputation: 715

In django there is a ModelForm which automatically creates forms from models.

models.py

Here is the models.py file with small changes:

  • class names should be in PascalCase
  • you probably don't need TextFields, I guess CharField will suffice
  • if we are inside Car model you do not have to prepend each name with car (eg. it is better to write model instead of carmodel)
  • use underscores for separating multi-word variables (eg. shipping_date instead of shippingdate)

So there is a file:

from django.db import models


class Car(models.Model):
    billing_number = models.BigIntegerField(primary_key=True)
    customer = models.CharField(max_length=100)
    price = models.IntegerField()
    purchase_date = models.DateTimeField()
    company = models.CharField(max_length=100)
    model = models.CharField(max_length=100)
    serial_number = models.BigIntegerField()
    mfg_date = models.DateTimeField()
    shipping_date = models.DateTimeField()

forms.py

Now, having Car model ready, we can create ModelForm. It is as easy as that:

from django.forms import ModelForm
from .models import Car

class CarForm(ModelForm):
    class Meta:
        model = Car
        exclude = ()  # this says to include all fields from model to the form

If you wanted to display limited number of fields in your form you could write:

class CarForm(ModelForm):
    class Meta:
        model = Car
        fields = ('customer', 'price', 'model')  # this would only display 3 fields on the form

views.py

We have everything we need to create the view to handle model creation form.

Add a new function in views.py file:

from django.http import HttpResponse
from django.shortcuts import render
from .forms import CarForm


def add_car(request):
    if request.method == 'POST':  # data sent by user
        form = CarForm(request.POST)
        if form.is_valid():
            form.save()  # this will save Car info to database
            return HttpResponse('Car added to database')
    else:  # display empty form
        form = CarForm()

    return render(request, 'add_car.html', {'car_form': form})

urls.py

Add this new view to urls.py file:

from django.urls import path
from myapp import views

urlpatterns = [
    # ...
    # your other urls
    # ...
    path('add-car', views.add_car, name='add_car'),
]

templates/add_car.html

Template that add_car view uses:

<form action="{% url 'add_car' %}" method="post">
    {% csrf_token %}
    {{ car_form.as_p }}
    <input type="submit" value="Save new car">
</form>

Important line is <form action="{% url 'add_car' %}" method="post">. This says to send POST request to add_car url. Url name was defined here: path('add-car', views.add_car, name='add_car') (name argument).

After applying these changes, you should be able to visit /add-car and fill in a form which will add a new record to the database.

Displaying stored records

To display records that you have in your database you have to:

  • add new url
  • create new view to fetch records
  • create new template to list cars

urls.py - add this line to urlpatterns

path('cars', views.car_list, name='car_list'),

View:

def car_list(request):
    return render(request, 'car_list.html', {
        # this will fetch all cars from database
        'cars': Car.objects.all()
    })

Now create template car_list.html where you can display all cars

<ul>
    {% for car in cars %}
        <li>{{ car.model }}</li>
    {% endfor %}
</ul>

Display single record details

urls.py add new line:

path('car/<int:car_billing_number>', views.car_details, name='car_details'),

views.py Retrieving single model info is also simple

def car_details(request, car_billing_number):
    return render(request, 'car_details.html', {
        'car': Car.objects.get(billing_number=car_billing_number)
    })

And finally - the car_details.html template.

<table style="border: 1px solid black">
    <tr><td>Billing number</td><td>{{ car.billing_number }}</td></tr>
    <tr><td>Model</td><td>{{ car.model }}</td></tr>
    <tr><td>Company</td><td>{{ car.company }}</td></tr>
    <tr><td>Price</td><td>{{ car.price }} $</td></tr>
    {# and so on #}
</table>

Now when you have a Car with billing number 123 you can visit site car/123 and see detailed information.

Upvotes: 1

Uroš Trstenjak
Uroš Trstenjak

Reputation: 903

You should use ModelForm instead of form and bound it to your cars model. This way all the model fields will be available through the form.

from django.forms import ModelForm
from .models import cars

class myform(ModelForm):
    class Meta:
        model = cars

Than in your html just show all the form fields. You can do it with form.as_p or you can render each field separately inside desired html element. Check Django form rendering for more info on form rendering.

<div>
    <form method="post">
        {% csrf_token %}

        {{ form.as_p }}

        <button type="submit" value="submit">Submit</button>
    </form>
</div>

Upvotes: 0

Related Questions