I’m creating a text file response with Django. I’m implementing it the normal way with a template file.
def create_file(request):
... create context ...
result = render_to_string('template.txt', context_dict)
response = HttpResponse(result, mimetype='text/plain')
response['Content-Disposition'] = 'attachment; filename=file.txt'
return response
The text file response is unique though, in that each character in the file must be positioned exactly. So every character in the file, including whitespaces is placed deliberately. This presents a problem for lines with variables on them that have unspecified length. So lets say we have 2 variables that are strings and are on the same line in the template.
{{variable1}} {{variable2}}
And variable2 must appear in column 5 of the text file. How can I specify an exact position for variable2 if I don’t know how many spaces variable1 takes up? Alternatively, am I just going about this totally wrong? Might it be easier to ditch the template altogether and create the text response entirely in the view?
As you suggested, I would do this in the view.
For the example you gave, you can use
string.ljustto left justify a string, padding with spaces as needed.Alternatively, as Elf and ΤΖΩΤΖΙΟΥ pointed out in the comments, you can use
%-formattingUsing
.4to truncatevariable1to 4 characters: