开发者

django render_to_string not working

I am trying to implement an ajax view to create an object and then return it and insert it into the template. It is almost working except I cannot seem to get render_to_string() to work to render the html to insert. The object is being created and html is being returned and inserted into the template however the variables are not included in the html. My view is below.

def tr_create_xhr(request, person, slug):
if request.method == "POST":
    form = TopicResourceForm(request.POST)
    if form.is_valid():
        try:
            r = Resource.objects.get(url=form.cleaned_data['resource'])
        except Resource.DoesNotExist:
            r = Resource.objects.create(url=form.cleaned_data['resource'], rtype=form.cleaned_data['rtype'])
            r.save()
    obj = form.save(commit=False)
    obj.resource = r
    try:
        topic = Topic.objects.get(person__user=request.user, slug__iexact=slug)
    except Topic.DoesNotExist:
        return Http404
    obj.topic = topic        
    objs = obj.save()
    html = render_to_string('includes/tr_inc.html',{"r":objs, "topic":topic})
    res = {'html':html}
    if request.is_ajax():
        return HttpResponse(simplejson.dumps(res), mimetype="application/json")
    else:
        return HttpResponseRedirect("../..")
return Http404

This is the template "includes/tr_inc.html":

{% load markup %}
{% load people_tags %}



    <li>

        <h5>{{ r.title }}</h5>
        <p><a class="tru" href={{ r.resource.url }}>{{ r.resource.url|sliceit:70 }}</a></p>
        <span class="oc"><p>Added {{ r.added }}{% if r.rt开发者_如何学编程ype %} |<a href={% url resource_type_detail r.rtype.slug %}>{{ r.rtype }}</a>{% endif %}

| <a href="/topics/user/{{ r.topic.person.user }}/{{ r.topic.slug }}/topic-resource/delete/{{ r.id }}/">Delete</a> <a href="/topics/user/{{ r.topic.person.user }}/{{ r.topic.slug }}/topic-resource/edit/{{ r.id }}/">Edit</a>

        {{ r.note|markdown }}</span>
    </li>

The html string that is returned is the template without any variables inserted.


Model method 'save' doesn't return an object. So you 'objs' variable is empty. You should write

html = render_to_string('includes/tr_inc.html',{"r":obj, "topic":topic})


I had exact the same problem today. It is quite easy. Please check the Django document for this method, there is actually a third optional parameter: context_instance=RequestContext(request). Therefore your render_to_string should be like this:

html = render_to_string(
    'includes/tr_inc.html',{"r":obj, "topic":topic},
    context_instance=RequestContext(request))

Then everything should work properly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜