国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Django(part4)

2019-11-14 17:35:43
字體:
來源:轉載
供稿:網友
  1. 一個簡單的form表單:
    #polls/templates/polls/detail.html
    <h1>{{ question.question_text }}</h1>
    {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
    <form action="{% url 'polls:vote' question.id %}" 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>
    • forloop.counter:表示for循環執行的次數
    • action="{% url 'polls:vote' question.id %}":指定處理post 數據的url
    • {% csrf_token %}:用于防止csrf攻擊的tag,所有post的form都應該使用
  2. 處理post的代碼:
    #polls/urls.pyurl(r'^(?P<question_id>/d+)/vote/$', views.vote, name='vote'),#polls/views.pyfrom django.shortcuts import get_object_or_404, renderfrom django.http import HttPResponseRedirect, HttpResponsefrom django.core.urlresolvers import reversefrom polls.models import Choice, Question# ...def vote(request, question_id):    p = get_object_or_404(Question, pk=question_id)    try:        selected_choice = p.choice_set.get(pk=request.POST['choice'])    except (KeyError, Choice.DoesNotExist):        # Redisplay the question voting form.        return render(request, 'polls/detail.html', {            'question': p,            'error_message': "You didn't select a choice.",        })    else:        selected_choice.votes += 1        selected_choice.save()        # Always return an HttpResponseRedirect after successfully dealing        # with POST data. This prevents data from being posted twice if a        # user hits the Back button.        return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))

    # polls/view.py

    from  django.shortcuts import get_object_or_404, renderdef results(request, question_id):    question = get_object_or_404(Question, pk=question_id)    return render(request, 'polls/results.html', {'question': question})
    • request.POST:用于獲取表單的值,同樣的屬性還有request.GET
    • request.POST[‘choice’]:choice是key值,不存在時引發KeyError exception
    • HttpResponseRedirect():參數是一個重定向的url/
    • reverse():返回一個url,通過使用url name避免hardcode
  3. Generic view:
    from django.shortcuts import get_object_or_404, renderfrom django.http import HttpResponseRedirectfrom django.core.urlresolvers import reversefrom django.views import genericfrom polls.models import Choice, Questionclass IndexView(generic.ListView):    template_name = 'polls/index.html'    context_object_name = 'latest_question_list'    def get_queryset(self):        """Return the last five published questions."""        return Question.objects.order_by('-pub_date')[:5]class DetailView(generic.DetailView):    model = Question#template_name 告訴django自動生成的template的name#如果不指定默認為<app name>/<model name>_detail.html    template_name = 'polls/detail.html'#polls/urls.py#注意必須用<pk>指定匹配的組名urlpatterns = patterns('',    url(r'^$', views.IndexView.as_view(), name='index'),    url(r'^(?P<pk>/d+)/$', views.DetailView.as_view(), name='detail'),  )
  4. 靜態文件:django的STATICFILES_FINDERS setting保存了一系列finder,這些finder知道如何去查找靜態文件。如AppDirectoriesFinder就會在INSTALLED_APPS包含的app的子目錄下查找static目錄。通常用如下存放靜態文件,polls/static/polls/style.CSS或者polls/static/polls/images/background.gif,這樣AppDirectoriesFinder可以找到,路徑中第二個polls相當于靜態文件的名字空間
    #polls/templates/polls/index.html{% load staticfiles %}<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
  5. How to packaging your app:參考https://docs.djangoproject.com/en/1.7/intro/reusable-apps/
  6.  

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 沿河| 阿拉善盟| 平谷区| 望谟县| 泗水县| 祥云县| 开鲁县| 武功县| 叙永县| 沁水县| 赫章县| 中西区| 新绛县| 绍兴县| 宣恩县| 蓬溪县| 于都县| 桂阳县| 通许县| 揭阳市| 永定县| 锡林浩特市| 庆云县| 肇东市| 三门县| 平塘县| 台南市| 延川县| 民县| 资溪县| 肇庆市| 奉节县| 南充市| 大埔县| 双牌县| 镇赉县| 安阳县| 清新县| 光山县| 织金县| 仁化县|