Reputation: 10888
I'm trying to render_to_string
a partial in my DetailView, in order to send the rendered html back through json for ajax to pick up.
My views.py look like this:
class ProfileDetails(DetailView):
model = UserProfile
def get_object(self, queryset=None):
response_data = {}
response_data['content'] = render_to_string("profile/userprofile_detail/content.html", self.get_context_data())
if request.is_ajax():
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
)
else:
return get_object_or_404(
UserProfile,
user__username=self.kwargs['username'],
)
This does not work, because I just get this attribute error:
'ProfileDetails' object has no attribute 'object'
I did search online on how to do this, but for my situation where I also need to use custom url parameters, this does not suffice.
How can I make this work with how I have it currently set up? My only goal here is sending the rendered partial to ajax, but I need to actually render it first.
Upvotes: 0
Views: 598
Reputation: 1542
I don't think you're overriding the get_object() method correctly. Your implementation can return an HttpResponse object which the DetailView doesn't seem to be able to and display properly. Even if it could serialize the HttpResponse object, your code is trying to display the field/values of the HttpResponse object you're constructing, when what you really want is for the view to return the HttpResponse object itself. What you want to do is remove all the ajax detection, serialization, and response generation logic in the get_object method and move it into an override of the view's get() method something to the effect of:
def get(self, request, *arg, **kwargs):
if request.is_ajax():
# Generate and return your HttpResponse object here
return super(ProfileDetails, self).get(request, *args, **kwargs)
The return value of the get method is supposed to be an HttpResponse object which the base View class knows how to handle. I encourage you to review the documentation for class-based views to get a better understanding of how they process requests/responses.
Upvotes: 1