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:

 
 




3 comments:

Popular Posts