Django Model Form

Models.py

from django.db import models
# Create your models here.
class Students(models.Model):
    sid = models.CharField(max_length=15)
    name = models.CharField(max_length=100)
    email = models.EmailField(max_length=50)


py manage.py makemigrations students
py manage.py  migrate



Forms.py

from django import forms
from django.forms import ModelForm
from .models import Students
class StudentForm(forms.ModelForm):
    class Meta:
        model = Students
        fields = "__all__"


Views.py

from django.shortcuts import render
from .forms import StudentForm
from .models import Students
# Create your views here.
def students(request):
    form = StudentForm()
    if request.method == "POST":
        form = StudentForm(request.POST)
        if form.is_valid():
            form.save()
    return render(request,"index.html",{'form':form})



def sv(request):
    view = Students.objects.all()
    context = {
        'view':view,
    }
    return render(request,"view.html",context)


Template  index.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
         <form method="POST" action="">
             {%csrf_token%}
             {{ form.as_p }}
             <button type="submit">Save</button>

         </form>

        <a href="/sv">show data</a>
</body>
</html>


Template View.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
 <ul>
        {% for x in view %}
        <li>{{ x.sid}} {{ x.name }} {{ x.email }}</li>
        {% endfor %}
        </ul>
</body>
</html>




Urls.py


from django.urls import path
from . import views

urlpatterns = [
    path('', views.students),
    path('sv/',views.sv)

]


py manage.py runserver

Comments

Popular posts from this blog

Django Class Based Views Blog App

Insert And Retrieve Images From SQlite Database using Tkinter and Python

Flask and Sqlite Basic Crud Python Tutorial