簡體   English   中英

如何將結果返回到 html django

[英]how to return result to html django

我想讓文本文件包含b'Y\xf5\x11m' (它是加密的結果) 我希望可以使用 html 下載txt文件。

但是當我返回它時出現下一個錯誤:

'int' object has no attribute 'get'

這是代碼:

def create_file(f):
    with open("file.txt", 'w') as file:
        download = file.write(str(f))
        print(download)
        return download

我這樣稱呼那個函數:

#in views
def homepage(request):
    form = AudioForm()
    if request.method == "POST":
        form = AudioForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            last_audio = Audio_store.objects.all().last()
            plaintext = Audio_store.objects.all().values_list('password').last()
            key = Audio_store.objects.all().values_list('key').last()
            pt = plaintext[0]
            ky = key[0]
            print(pt)
            print(ky)
            context={'form':form, 'last_audio':last_audio}
            enc = encrypt(ky, pt)
            print(enc)
            download = create_file(enc)
            print(download)
            return render(request, "homepage.html", context)

    context={'form':form}
    return render(request, "homepage.html", context=context)

#in urls
path("create_file", views.create_file, name="create_file"),

#in html
<a href="{% url 'create_file' %}">

錯誤

你定義 function create_file,這個 function:

def create_file(f):
    with open("file.txt", 'w') as file:
        return file.write(str(f))

這個 function 獲取任何信息作為參數並將其寫入文件。

之后定義 url:

path("create_file", views.create_file, name="create_file"),

這意味着:您可以查看 function 'create_file',它將request作為第一個調用參數並返回HtmlResponseObject

我在您的代碼中看不到任何視圖,它獲取request並將文件作為HtmlResponseObject.body回。

我只能想象:

在路徑中:

path("create_file", views.FileView.as_view(), name="create_file"),

在views.py中:

class FileView(View):

    def get(self, request, *args, **kwargs):
        return HttpResponse(create_file('here your text to write in file'), content_type='text/plain', headers={'Content-Disposition': 'filename=file.txt'})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM