Python Lover(2)Django Doc - URL Mapping - View - Template

299 篇文章 0 订阅

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Django是一个用于快速开发Web应用程序的Python Web框架。而python-docx-template是一个Python库,它可以使用Word文档作为模板,然后根据传入的数据批量生成Word文档。在Django中,我们可以利用python-docx-template库来实现批量生成Word文档的功能。 首先,我们需要在Django项目中安装python-docx-template库。可以使用pip命令来安装该库: ```bash pip install python-docx-template ``` 接下来,我们可以在Django项目中创建一个视图函数,用于接收数据并根据模板生成Word文档。在视图函数中,我们可以使用python-docx-template库提供的方法将数据填充到Word模板中,生成最终的Word文档。 例如,假设我们有一个Word文档模板`template.docx`,里面包含了一些需要填充数据的位置,我们可以在Django中这样写视图函数: ```python from docxtpl import DocxTemplate from django.http import HttpResponse def generate_word_document(request): # 从请求中获取数据 data = request.GET.get('data', '') # 读取Word模板 doc = DocxTemplate("template.docx") # 根据数据填充模板 context = {'data': data} doc.render(context) # 写入生成的Word文档 doc.save("generated_document.docx") # 返回生成的Word文档给用户 with open("generated_document.docx", 'rb') as f: response = HttpResponse(f.read(), content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') response['Content-Disposition'] = 'attachment; filename=generated_document.docx' return response ``` 通过上述视图函数,我们可以在Django项目中实现批量生成Word文档的功能,用户可以通过传入数据来生成他们所需的Word文档。这样我们就可以方便地利用PythonDjango来批量生成Word文档,提高生产效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值