设为首页 收藏本站
查看: 648|回复: 0

[经验分享] Python Lover(2)Django Doc

[复制链接]

尚未签到

发表于 2017-5-6 12:22:23 | 显示全部楼层 |阅读模式
  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: luohuazju@gmail.com 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

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-373806-1-1.html 上篇帖子: 通过Python脚本创建ArcGIS地图服务缓存 下篇帖子: Ruby、Python不能威胁Java的13个理由
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表