Python Lover(2)Django Doc - URL Mapping - View - Template
1. Admin Console
Creating an admin user
>python manage.py createsuperuser
Username (leave blank to use 'carl'): admin Email address: [email protected] Password: Password (again): Superuser created successfully.
Visit this page to login in
http://localhost:8000/admin/
Admin is enabled and we can CURD the group and user there.
Add our app polls into admin in admin.py
from django.contrib import admin
from polls.models import Question
# Register your models here.
admin.site.register(Question)
Refresh the page, then I can see the changes there. And there are some ways to customized the forms in admin. But I thought it was not that important.
Adding related objects
Add Choice Registered in the admin.py
from django.contrib import admin
from polls.models import Question, Choice
# Register your models here.
admin.site.register(Question)
admin.site.register(Choice)
Customized the Question Related Choice
from django.contrib import admin
from polls.models import Question, Choice
# Register your models here.
#class ChoiceInline(admin.StackedInline):
class ChoiceInline(admin.TabularInline):
model = Choice
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question_text', 'pub_date', 'was_published_recently')
admin.site.register(Question, QuestionAdmin)
Order and Display
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published Recently?'
Filter
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question_text', 'pub_date', 'was_published_recently')
list_filter = ['pub_date']
Search Part
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question_text', 'pub_date', 'was_published_recently')
list_filter = ['pub_date']
search_fields = ['question_text']
2. Front View
View —Action
Template —— HTML
Write First View
Something like writing PHP, haha.
polls/views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse("This is the index page.”)
Url Mapping in app polls
polls/urls.py
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
)
System URL Mapping
easypoll/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'easypoll.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^polls/', include('polls.urls')),
)
It works after we visit this page
http://localhost:8000/polls/
Write More Views
def index(request):
return HttpResponse("This is the index page.")
def detail(request, question_id):
return HttpResponse("You are looking at question %s." % question_id)
def results(request, question_id):
response = "You are looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You are voting on question %s." % question_id)
More Mapping
urlpatterns = patterns('',
#/polls/
url(r'^$', views.index, name='index'),
#/polls/5/
url(r'^(?P<question_id>\d+)/$', views.detail, name='detail'),
#/polls/5/results/
url(r'^(?P<question_id>\d+)/results/$', views.results, name='results'),
#/polls/5/vote/
url(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote'),
)
Make the Views Working
This will display all the Questions There
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
#latest 5 records
output = ', '.join([p.question_text for p in latest_question_list])
return HttpResponse(output)
But we need to customized the html from my understanding.
Using HTML Template
from django.http import HttpResponse
from polls.models import Question
from django.template import RequestContext, loader
# Create your views here.
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
#latest 5 records
template = loader.get_template('polls/index.html')
context = RequestContext(request, {
'latest_question_list': latest_question_list,
})
return HttpResponse(template.render(context))
easypoll/polls/templates/polls/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 polls are available.</p>
{% endif %}
Using Render
from django.shortcuts import render
# Create your views here.
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
#latest 5 records
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
How to Do the Detail
from django.http import Http404
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404
return render(request, 'polls/detail.html', {'question': question})
Just a very simple page polls/templates/polls/detail.html
{{ question }}
Shortcut
from django.shortcuts import get_object_or_404
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question':question})
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
Change the URL in index.html page as follow:
<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
Namespace the URL Names
In the main urls.py
url(r'^polls/', include('polls.urls', namespace="polls")),
In the Index.html
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
References:
https://docs.djangoproject.com/en/1.7/intro/tutorial02/
deployment
http://sillycat.iteye.com/blog/582074