ValueError:不要在调用reverse()时混用* args和** kwargs!

时间:2014-10-23 21:22:01

标签: python django django-views

我正在尝试render_to_response将我的视图的渲染响应返回给ajax调用,但是我收到以下错误,我并不理解......

Internal Server Error: /schedules/calendar/2014/10/1/
Traceback (most recent call last):
  File "/blahblahblah/django/core/handlers/base.py", line 111, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/blahblahblah/schedules/views.py", line 229, in month_view
    return render_to_string(template, data)
  File "/blahblahblah/django/template/loader.py", line 172, in render_to_string
    return t.render(Context(dictionary))
  File "/blahblahblah/django/template/base.py", line 148, in render
    return self._render(context)
  File "/blahblahblah/django/template/base.py", line 142, in _render
    return self.nodelist.render(context)
  File "/blahblahblah/django/template/base.py", line 844, in render
    bit = self.render_node(node, context)
  File "/blahblahblah/django/template/debug.py", line 80, in render_node
    return node.render(context)
  File "/blahblahblah/django/template/defaulttags.py", line 444, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=context.current_app)
  File "/blahblahblah/django/core/urlresolvers.py", line 546, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
  File "/blahblahblah/django/core/urlresolvers.py", line 405, in _reverse_with_prefix
    raise ValueError("Don't mix *args and **kwargs in call to reverse()!")

ValueError: Don't mix *args and **kwargs in call to reverse()!

我不明白这个错误的来源。我按照django文档中的说明调用request_to_response。以下是我的观点:

def month_view(
    request, 
    year, 
    month, 
    template='monthly_view.html',
    user_id=None,
    queryset=None
):
    year, month = int(year), int(month)
    cal         = calendar.monthcalendar(year, month)
    dtstart     = datetime(year, month, 1)
    last_day    = max(cal[-1])
    dtend       = datetime(year, month, last_day)

    if user_id:
        profile = get_object_or_404(UserProfile, pk=user_id)
        queryset = profile.occurrence_set
    queryset = queryset._clone() if queryset else Occurrence.objects.select_related()
    occurrences = queryset.filter(start_time__year=year, start_time__month=month)

    def start_day(o):
        return o.start_time.day

    by_day = dict([(dt, list(o)) for dt,o in itertools.groupby(occurrences, start_day)])
    data = {
        'today':      datetime.now(),
        'calendar':   [[(d, by_day.get(d, [])) for d in row] for row in cal], 
        'this_month': dtstart,
        'next_month': dtstart + timedelta(days=+last_day),
        'last_month': dtstart + timedelta(days=-1),
    }

    if request.is_ajax():
        my_html = render_to_string('monthly_view.html', data)
        return HttpResponse(json.dumps(my_html), content_type="application/json")
    else:
        raise Http404

之前有没有人遇到这样的错误,或者知道它来自哪里? 在调用反向参数之前的行上是

  

View_name:schedule:monthly-view Args:[2014,9] kwargs:   { 'user_pk':   ''}

我想渲染的模板是:

<h4>
    <a href="{% url 'schedules:monthly-view' last_month.year last_month.month user_pk=object.profile.pk %}" 
        title="Last Month">&larr;</a>
    {{ this_month|date:"F" }}
    <a title="View {{ this_month.year}}" href='#'>
        {{ this_month|date:"Y" }}</a>
    <a href="{% url 'schedules:monthly-view' next_month.year next_month.month user_pk=object.profile.pk %}" 
       title="Next Month">&rarr;</a>
</h4>
<table class="month-view">
    <thead>
        <tr>
            <th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th>
        </tr>
    </thead>
    <tbody>
        {% for row in calendar %}
        <tr>
            {% for day,items in row  %}
            <td{% ifequal day today.day  %} class="today"{% endifequal %}>
            {% if day %}
                <div class="day-ordinal">
                    <a href="{% url 'schedules:daily-view' this_month.year this_month.month day user_pk=object.profile.pk %}">{{ day }}</a>
                </div>
                {% if items %}
                <ul>
                    {% for item in items %}
                    <li>
                        <a href="{{ item.get_absolute_url }}">
                            <span class="event-times">{{ item.start_time|time }}</span>
                            {{ item.title }}</a>
                    </li>
                    {% endfor %}
                </ul>
                {% endif %}
            {% endif %}
            </td>
            {% endfor %}
        </tr>
        {% endfor %}
    </tbody>
</table>

和urls.py是

from django.conf.urls import patterns, url

from .views import (
    CreateSessionView, CreateListingsView, SessionsListView,
    month_view, day_view, today_view

)

urlpatterns = patterns('',
    url(
        r'^(?:calendar/)?$', 
        today_view, 
        name='today'
    ),
    url(
        r'^calendar/(?P<year>\d{4})/(?P<month>0?[1-9]|1[012])/(?P<user_pk>\d+)/$', 
        month_view, 
        name='monthly-view'
    ),

    url(
        r'^calendar/(?P<year>\d{4})/(?P<month>0?[1-9]|1[012])/(?P<day>[0-3]?\d)/(?P<user_pk>\d+)/$', 
        day_view, 
        name='daily-view'
    ),

此外,这是ajax请求:

<script>

    function update_calendar(url) {
        console.log("Calling url " + url)
        $.ajax({
            type: 'GET',
            dataType: 'json',
            url: url,
            success: function(data, status, xhr) {
                console.log('success')
                console.log(data);
                $('#schedule').html(data)
            },
            error: function() {
                console.log('Something went wrong');
            }
        });
    }

    $(document).ready(function() {

        // Initially set up calendar for current month
        var today = new Date();
        var year = today.getFullYear();
        var month = today.getMonth()+1;
        var user_pk = {{ object.profile.pk }};
        var url = '../schedules/calendar/'+year+'/'+month+'/'+user_id+'/';

        // EDIT JUST ADDED THIS LINE HERE AND AM GETTING THE ERROR HERE NOW
        url = "{% url 'schedules:monthly-view' year month user_pk=user_pk %}"

        update_calendar(url);

        $('#schedule > a').click(function(event) {
            var url = $(this).attr('href');
            update_calendar(url);
        });
    });
</script>

1 个答案:

答案 0 :(得分:9)

错误告诉你的是什么:

使用任一关键字参数:

{% url 'schedules:monthly-view' year=last_month.year month=last_month.month user_pk=object.profile.pk %}

或位置参数:

{% url 'schedules:monthly-view' last_month.year last_month.month object.profile.pk %}
相关问题