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 :




 




Thursday 23 February 2017

Django easy way

The Django 1.8  main Tutorials site as given bellow .

https://docs.djangoproject.com/en/1.8/contents/

They are explaining one app called polls  as example . If you go through the tutorial at certain point you will get confused . I have made the same tutorial easiest way . See the main config files . It will also work same as the tutorial .

 I will show the  files one by one :

mysite/urls.py:

from django.conf.urls import *
from django.contrib import admin
from polls.views import *

urlpatterns = [
        url(r'^admin/', include(admin.site.urls)),
        url(r'^$', index),
        url(r'^polls/', include('polls.urls')),

]

polls/urls.py:

from django.conf.urls import url
from polls.views import *

urlpatterns = [
    url(r'^$', index, name='polls'),
    url(r'^(?P<question_id>[0-9]+)/$', details, name='detail'),
    url(r'^(?P<question_id>[0-9]+)/vote/$', votess, name='vote'),
]


polls/models.py:

from django.db import models
from django.utils import timezone
import datetime

class Question(models.Model):
        question_text=models.CharField(max_length=200)
        pub_date=models.DateTimeField('Date Published')

        def __str__(self):
                return self.question_text

        def was_published_recently(self):
                now=timezone.now()
                return now - datetime.timedelta(days=1) <= self.pub_date <= now

class Choice(models.Model):
        question=models.ForeignKey(Question)
        choice_text=models.CharField(max_length=200)
        vote=models.IntegerField(default=0)

        def  __str__(self):
                return self.choice_text


polls/admin.py:

from django.contrib import admin
from polls.models import *


class QuestionAdmin(admin.ModelAdmin):
        list_display=['question_text','pub_date','was_published_recently']

admin.site.register(Question,QuestionAdmin)
admin.site.register(Choice)


polls/views.py:

from django.http import HttpResponse,Http404,HttpResponseRedirect
from django.shortcuts import render,render_to_response,get_object_or_404
from polls.models import *
from django.template import RequestContext


def index(request):
        latest_question_list=Question.objects.all()
        return render_to_response('index.html',{'latest_question_list':latest_question_list})


def details(request,question_id):
        question=get_object_or_404(Question,id=question_id)
        return  render_to_response('detail.html',{'question':question},context_instance = RequestContext(request))


def votess(request,question_id):
        p = get_object_or_404(Question, pk=question_id)
        try:
                selected_choice = p.choice_set.get(pk=request.POST['choice'])
        except :
                return render(request, 'detail.html', {
                'question': p,
                'error_message': "You didn't select a choice.",
        })
        else:
                selected_choice.vote += 1
                selected_choice.save()
                return render(request,'results.html',{'question':p})


Template/index.html:

{%if latest_question_list%}
<ul>
{%for question in latest_question_list%}
<li><a href='/polls/{{question.id}}/'>{{question.question_text}}</a></li>
{%endfor%}
</ul>
{%else%}
<p>No question found.</p>
{%endif%}


Template/detail.html:

<h1>{{ question.question_text }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="/polls/{{question.id}}/vote/" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
    <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>

Template/results.html:

<h1> {{question.question_text}}</h1>
<ul>
{%for choice in question.choice_set.all%}
<li>
{{choice.choice_text}} -- {{choice.vote}} vote{{choice.vote|pluralize}}
</li>
{%endfor%}
</ul>
<a href="/polls/{{question.id}}/vote/">Vote Again ?</a>
<a href="/polls/">Home</a>


Bellow are some SS from the running app:

 
 




Popular Posts