rfj001
rfj001

Reputation: 8498

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

I am trying to render_to_response to return a rendered response of my view to an ajax call, but I am getting the following error that I don't really understand...

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()!

I don't understand where this error is coming from. I am calling request_to_response as per instructed in the django documentation. Here is my view:

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

Has anyone encountered an error like this before, or have any idea where it is coming from? On the line right before the call to reverse the parameters for reverse are

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

Template I am trying to render is:

<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>

and urls.py is

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'
    ),

Additionally, here is the ajax request:

<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>

Upvotes: 8

Views: 12151

Answers (1)

dgel
dgel

Reputation: 16796

Exactly what the error is telling you:

Use either keyword arguments:

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

Or positional arguments:

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

Upvotes: 19

Related Questions