How to save an html file in django?

Question:

I have a view that forms the html template

class CvView(AuthorizedMixin, View):

    def get(self, request, employee_id, format_):
        employee = get_object_or_404(Employee, pk=employee_id)
        user = request.user
        content_type, data = Cv(employee, format_, user).get()
        print(type(data))

        if isinstance(data, BytesIO):
            return FileResponse(
                data, as_attachment=True, filename=f'cv.{format_}',
                content_type=content_type)
        return HttpResponse(data, content_type=content_type)

This view has a data variable. This variable contains the body of the html template. If I’m printed in a console print(data) I get

<!DOCTYPE html>
<html lang="en">
<head>
.....
</head>
<body>
.....
</body>

The type of values is <class 'django.utils.safestring.SafeText'>

I’m interested in the question: can I get an html file from this variable and save it on disk? How can I do this?

Asked By: Jekson

||

Answers:

Tried this?

with open('template.html', 'w+') as output:
    output.write(str(data))
Answered By: Kshitij Saxena
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.