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.rtype %} |<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