簡體   English   中英

Django在模板內傳遞視圖URL變量

[英]Django passing view url variables inside a template

我覺得這將是一個令人尷尬的問題,但我找不到嘗試過google的答案,但是我感到非常沮喪,所以我決定在這里提問。 我在Django的模板文件中有此代碼段

{% url cal.views.month year month "next" %}

我運行代碼並獲得此錯誤,但未找到帶有參數'(2013,9,u'next')'的'courseCalendar.views.month'

為什么當我嘗試在字符串中傳遞變量時,它也會將u也放在其中。 這是非常令人沮喪的,我真的很感謝有人兩美分。

編輯:如果我不包括字符串“ next”,而是使用變量(例如年和月變量),則一切正常,因此這不是URL問題或模板問題。

網址格式

from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
    url(r'', 'courseCalendar.views.main'),
    url(r'^month/(?P<year>\d{4})/(?P<month>\d{2})/(?P<change>[a-z])/$', 'courseCalendar.views.month', name="month"),

)

觀看次數

# Create your views here.
import time
import calendar
from datetime import date, datetime, timedelta
#from django.contrib.auth.decorators import login_required    For login requirements. 
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from courseCalendar.models import *

monthNames = "Jan Feb Mar Apr May Jun Jly Aug Sep Oct Nov Dec"
monthNames = monthNames.split()


#@login_required  This should be uncommented in the future but for now we don't want to     deal with it. Default set to 2013 for now.
def main(request, year="None"):

if year == "None":
    year = time.localtime()[0]
else:
    year = int(year)

currentYear,currentMonth = time.localtime()[:2]
totalList = []

for y in [year]:
    monthList = []
    for n, month in enumerate(monthNames):
        course = current = False
        courses = Course.objects.filter(courseDate__year=y, courseDate__month=n+1)

        if courses:
            course = True
        if y==currentYear and n+1 == currentMonth:
            current = True
        monthList.append(dict(n=n+1, name=month, course=course, current=current))
    totalList.append((y,monthList))

#return render_to_response("courseCalendar/Templates/main.html", dict(years=totalList, user=request.user, year=year, reminders=reminders(request)))   <-- Later in the build
return render_to_response("main.html", dict(years=totalList, user=request.user, year=year))





def month(request, year=1, month=1, change="None"):


if year == "None":
    year = time.localtime()[0]
else:
    year = int(year)


if month == "None":
    month = time.localtime()[1]
else:
    month = int(month)

if change in ("next", "prev"):
    todaysDate, mdelta = date(year, month, 15), timedelta(days=31)
    if change == "next":
        mod = mdelta
    elif change == "prev":
        mod = -mdelta
    year, month = (todaysDate+mod).timertuple()[:2]


cal = calendar.Calendar()
month_days = cal.itermonthdays(year, month)
nyear, nmonth, nday = time.localtime()[:3]
lst = [[]]
week = 0


for day in month_days:
    courses = current = False

    if day:
        courses = Course.objects.filter(courseDate__year=year, courseDate__month=month, courseDate__day=day)
        if day == nday and year == nyear and month == nmonth:
            current = True

    lst[week].append((day, courses, current))
    if len(lst[week]) == 7:
        lst.append([])
        week += 1

return render_to_response("month.html", dict(year=year, month=month, user=request.user, month_days=lst, monthNames=monthNames[month-1]))

main.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Need to figure out how to pass the year variable properly in the url arguements. The way it was originally written didn't work  and adding quotes appended a "u" to the areguements-->

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Year View</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
{% load staticfiles %}
<link rel="stylesheet" href="{% static "courseCalendar/css/layout.css" %}" type="text/css" />
</head>

<body>
<div id="wrapper">
    <a href="{% url "courseCalendar.views.main" %}">&lt;&lt; Prev</a>
    <a href="{% url "courseCalendar.views.main" %}">Next &gt;&gt;</a>

    {% for year, months in years %}
        <div class="clear"></div>
        <h4>{{ year }}</h4>
        {% for month in months %}
            <div class=
            {% if month.current %}"month current"{% endif %}
            {% if not month.current %}"month"{% endif %}
            >
                {% if month.entry %}<b>{% endif %}
                <a href="{% url "courseCalendar.views.month" year month "next"">{{ month.name }}</a>
                {% if month.entry %}</b>{% endif %}
            </div>
        {% endfor %}
    {% endfor %}
</div>

</body>
</html>

month.html

<a href="{% url "courseCalendar.views.month" %}">&lt;&lt; Prev</a>
<a href="{% url "courseCalendar.views.month" %}">Next &gt;&gt;</a>

<h4>{{ month }} {{ year }}</h4>

<div class="month">
<table>

<tr>
    <td class="empty">Mon</td>
    <td class="empty">Tue</td>
    <td class="empty">Wed</td>
    <td class="empty">Thu</td>
    <td class="empty">Fri</td>
    <td class="empty">Sat</td>
    <td class="empty">Sun</td>
</tr>

{% for week in month_days %}
    <tr>
    {% for day, courses, current in week %}
        <td class= {% if day == 0 %}"empty"{% endif %}
        {% if day != 0 and not current %}"day"{% endif %}
        {% if day != 0 and current %}"current"{% endif %}
        {% if day != 0 %}"Add day click code here"{% endif %} >

        {% if day != 0 %}
            {{ day }}
            {% for course in courses %}
                <br />
                <b>{{ course.courseCreator }}</b>
            {% endfor %}
        {% endif %}
    {% endfor %}
    </td>
{% endfor %}
</table>

<div class="clear"></div>
</div>

更改為以下內容:

在您的視圖文件中:

def month(request, year=1, month=1, change="None"):

在您的網址文件中:

url(r'^month/(?P<year>\d{4})/(?P<month>\d{2})/(?P<change>\w+)/$', 'courseCalendar.views.month', name="month"),

更改為上述內容后,如果收到錯誤,請在此處發布錯誤消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM