Friday, 24 February 2017

Django Models as Forms

(Warning: Here the Form Validation is not done )


Here i will show you how to use the Django Models a Forms .


I have Model as bellow .

models.py:

class Publisher(models.Model):
        name=models.CharField(max_length=100)
        addess=models.CharField(max_length=100)
        city=models.CharField(max_length=10)
        state_province=models.CharField(max_length=20)
        country=models.CharField(max_length=20)
        website=models.URLField()

Now i want this models as Form . For this you have to following .

Your New models.py file will be like bellow :

from django.db import models
from django.forms import ModelForm

class Publisher(models.Model):
        name=models.CharField(max_length=100)
        addess=models.CharField(max_length=100)
        city=models.CharField(max_length=10)
        state_province=models.CharField(max_length=20)
        country=models.CharField(max_length=20)
        website=models.URLField()

        def __str__(self):
                return u'%s'%self.name

class PublisherForm(ModelForm):
        class Meta:
                model =Publisher
                fields = ['name','addess','city','state_province', 'country', 'website']



Your views.py file will be like bellow:

from django.shortcuts import render_to_response
from books.models import *
from django.http import HttpResponse,Http404,HttpResponseRedirect
from books.forms import *
from django.template import RequestContext


def add_publisher(request):
        if request.method=='POST':
                form=PublisherForm(request.POST)
                if form.is_valid():
                        form.save()
                        return HttpResponseRedirect('/books/thanks/')
        else:
                form=PublisherForm()
        return render_to_response('add_publisher.html',{'form':form},context_instance =          RequestContext(request))

def thanks(request):
        Thanks=Publisher.objects.all()
        return render_to_response('thanks.html',{'Thanks':Thanks})


Your urls.py file will be :

from django.conf.urls import *
from books.views import *

urlpatterns = [
        url(r'^$', index),
        url(r'^add_publisher/$', add_publisher),
        url(r'^thanks/$', thanks),
]




Template add_publisher.html:


<!DOCTYPE html>
<html>
<head>
        <title>Publisher Submission</title>
</head>
<body>
<h1>Publisher Submission</h1>
<form action="." method="POST">
{% csrf_token %}
        <table>
                {{form.as_table}}
        </table>
        <p><input type="submit" value="Submit" ></p>
</form>
</body>
</html>

Template thanks.html:

<!DOCTYPE html>
<html>
<head>
        <title>Total Publisher</title>
</head>
<body>
<h1>Now Overall Publisher: </h1>
{%for i in Thanks%}
<br/>{{i}}
{%endfor%}
</body>
</html>


Bellow are some SS :




 




No comments:

Post a Comment

Popular Posts