Django 1.6:TypeError render_to_string() 收到多个 'context_instance' 关键字参数值

0 投票
1 回答
731 浏览
提问于 2025-04-18 09:51

我正在尝试在我的一个视图中传递一个字典,以便在模板中使用,但我遇到了以下错误

Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
  114.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "views.py" in showDocProfile
  179.     return render(request,'meddy1/docprofile.html',d,{'doctor': profile, 'UGC': UserContent.objects.all(), 'average': average})
File "/Library/Python/2.7/site-packages/django/shortcuts/__init__.py" in render
  53.     return HttpResponse(loader.render_to_string(*args, **kwargs),

Exception Type: TypeError at /docprofile/3/
Exception Value: render_to_string() got multiple values for keyword argument 'context_instance'

这是我的 views.py 文件

def showDocProfile(request, id):
    d = getVariables(request)
    profile = Doctor.objects.get(id=id)

    a = []
    count = 0
    for e in UserContent.objects.filter(doctor_id=id):
        a.append(e.time)
        count = count + 1

    if count == 0:
        count = 1
        average=sum(a)/float(count)

    else:
        average=sum(a)/float(count)    


    if request.user.is_authenticated():
        user = request.user
        ds = DoctorSeeker.objects.get(user=user)
        d['doctorseeker'] = ds

        doctorLiked = Like.objects.filter(doctor_id=profile.id,user_id=user.id)

        d['my_doctor'] = profile.id == request.user.id

        d['username'] = user.username

        if doctorLiked:
            d['liked'] = True
        else:
            d['liked'] = False

    return render(request,'meddy1/docprofile.html',d,{'doctor': profile, 'UGC': UserContent.objects.all(), 'average': average})

这是我想要展示的模板

    {% if logged_in and not liked %}
  <a class="btn btn-danger" href="/project/{{project.id}}/likeProject">I like This!</a>
{% else %}
  <button disabled class="btn btn-danger">Already Liked</button>

我不太确定在我的视图中该怎么改才能让这个工作。

1 个回答

1

你传入的参数太多了;你把d当作模板字典传入,然后又传了一个不同的字典作为第四个参数;这就意味着这个字典被当作context_instance参数传入了,这里就出错了。

d和那个额外的字典合并,只传入一个字典:

d.update({'doctor': profile, 'UGC': UserContent.objects.all(), 'average': average})
return render(request, 'meddy1/docprofile.html', d)

撰写回答