Skip to main content

Command Palette

Search for a command to run...

django example

Published
•5 min read•View as Markdown

✅ Step 1: Model (models.py)

This defines the structure of your database table.

pythonCopyEdit# models.py
from django.db import models

class Patient(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()

✅ Step 2: Form (forms.py)

This helps validate input and map it to the model.

pythonCopyEdit# forms.py
from django import forms
from .models import Patient

class PatientForm(forms.ModelForm):
    class Meta:
        model = Patient
        fields = ['name', 'email']

✅ Step 3: HTML Template (patient_form.html)

This is the form the user fills out.

htmlCopyEdit<!-- patient_form.html -->
<form method="POST">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Submit</button>
</form>

✅ Step 4: View (views.py)

This processes the form and saves the data to the database.

pythonCopyEdit# views.py
from django.shortcuts import render, redirect
from .forms import PatientForm

def register_patient(request):
    if request.method == 'POST':
        form = PatientForm(request.POST)
        if form.is_valid():
            form.save()  # ✅ This saves the data to the database
            return redirect('success')  # or wherever you want
    else:
        form = PatientForm()
    return render(request, 'patient_form.html', {'form': form})

✅ Step 5: URL (urls.py)

Connects the view to a URL.

pythonCopyEdit# urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('register/', views.register_patient, name='register'),
]

Final Flow:

  1. User opens /register/ page → sees the form.

  2. User fills the form and clicks Submit.

  3. Django validates the form.

  4. If valid → form.save() saves data to the database table Patient.

Now, what Django is doing here with forms.Form is helping you on the backend — to:

✅ Validate the data
✅ Easily connect the form to your database
✅ Show errors automatically if something’s wrong
✅ Reuse the form code and make it secure


So here's the difference:

🖼️ Your HTML form = What the user sees and fills (frontend)
🐍 Django Form (forms.Form) = Python code that helps handle and validate that data (backend)


For example:

If your HTML form sends:

<input type="text" name="first_name" />

Django will catch it using:

first_name = forms.CharField(max_length=100)

Then Django can check:

  • Is the first name empty? ❌

  • Is it too long? ❌

  • Is the phone number exactly 10 digits? ✅ or ❌

  • Do the passwords match? ✅ or ❌

  • Did the user agree to the terms? ✅

\==================================================================

Sure! Here's a complete and simple working example that includes:

✅ Django model
✅ Django ModelForm
✅ View to handle form submission
✅ HTML file with manual <input> fields (not {{ form.as_p }})
✅ How data flows to the database


🧩 1. models.py

from django.db import models

class Patient(models.Model):
    first_name = models.CharField(max_length=100)
    email = models.EmailField(unique=True)

    def __str__(self):
        return self.first_name

🧩 2. forms.py

from django import forms
from .models import Patient

class PatientForm(forms.ModelForm):
    class Meta:
        model = Patient
        fields = ['first_name', 'email']

🧩 3. views.py

from django.shortcuts import render, redirect
from .forms import PatientForm

def register_patient(request):
    if request.method == 'POST':
        form = PatientForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('success')  # You can define a simple success page
    else:
        form = PatientForm()
    return render(request, 'patient_form.html', {'form': form})

🧩 4. urls.py

Make sure to add this in your urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('register/', views.register_patient, name='register'),
    path('success/', views.success, name='success'),  # optional
]

Add a success view if needed:

pythonCopyEditdef success(request):
    return render(request, 'success.html')

🧩 5. patient_form.html (manual input tags)

htmlCopyEdit<!DOCTYPE html>
<html>
<head>
  <title>Patient Registration</title>
</head>
<body>
  <h2>Register</h2>

  <form method="POST">
    {% csrf_token %}

    <label>First Name:</label>
    <input type="text" name="first_name" required><br><br>

    <label>Email:</label>
    <input type="email" name="email" required><br><br>

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

</body>
</html>

✅ Flow Summary

  1. User fills the form → HTML sends data to view via POST

  2. View gets form data → Validates → Saves using form.save()

  3. Data gets stored in the database using Django ORM

  4. Redirect to success page (optional)

  5. \==========================================================

    ✅ The name attribute in your HTML input:

<input type="text" name="first_name">

MUST match the field name in your Django ModelForm — which in turn must match the name in your Model.


🔁 All 3 should be in sync:

LayerField Name
Modelfirst_name
Formfirst_name
HTMLname="first_name"

✅ Why this matters:

When you submit the form:

  • Django collects the data using the name values in the HTML.

  • It maps those to the fields in the ModelForm.

  • The ModelForm maps those to your database model and saves them.

If the names don’t match, Django won’t be able to connect the dots.

\=========================================================

✅ You should store data from the signup page in the database.

Why?

  • The signup page is where a user registers their details (like name, email, password, etc.).

  • This data needs to be saved in your database so you can use it later to check if the user exists when they try to log in.

❌ You should not store data from the login page.

  • The login page is only for checking if the entered email/password matches what's already stored in your database.

  • It just verifies, not stores.

🌟 Why use Django forms if we are only taking values and storing them?

Because Django forms do more than just capture input — they:


✅ 1. Validate input automatically

For example:

  • Is the email valid?

  • Is the phone number too long?

  • Did the user leave a required field empty?

With Django forms, you don’t need to write all those checks yourself.


✅ 2. Make rendering forms easier

Instead of manually writing lots of <input> tags and error messages in HTML, you just write this in the template:

htmlCopyEdit{{ form.as_p }}

And Django takes care of rendering all form fields with labels, input tags, and error messages (if any).


✅ 3. Make saving to the database easier

Using a ModelForm, you can directly save data to the database with just:

pythonCopyEditform.save()

No need to write code to extract values and assign them to a model manually.

So, 'patient': patient is basically telling Django to pass the patient object to the template, and you can use the key 'patient' to access the patient data inside the template.