Django:无法下载生成文件

时间:2018-07-18 06:52:46

标签: python django download django-templates httpresponse

我正在尝试生成一个文本文件,并从模板中的链接下载该文件,但是单击链接后没有任何反应。

这是我在模板中的链接。

<a href="{% url 'download' %}"><h2>{{ fname }} {{ lname }}</h2></a>

这是我的观点

def report_generate(request):
    f = open("test.txt", "w+")
    for i in range(10):
        f.write("This is line %d\r\n" % (i + 1))

    response = HttpResponse(f.read(), content_type='text/plain')
    filename = "guru99.txt"
    response['Content-Disposition'] = 'attachment; filename="%s"' % filename
    return response

这是我的urls.py

urlpatterns = [
path('admin/', admin.site.urls),
path('', qrview.index),
path('forms/new_profile', formsview.profile_create, name="aaa"),    # test
path('forms/new_course', formsview.course_create, name="ddd"),      # test
path('forms/edit_course', formsview.course_edit, name="edit_course"),   
path('report/', reportview.report, name="report"),
path('report/', reportview.report_generate, name="download"),
#path('admin/', admin.site.urls),
#path('admin/', admin.site.urls),

]

3 个答案:

答案 0 :(得分:6)

由于您的情况import { Component, ViewChild } from '@angular/core'; import { Nav, Platform, AlertController } from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { TranslateService } from '@ngx-translate/core'; import { Storage } from '@ionic/storage'; import { Network } from '@ionic-native/network'; import { ClientsListPage } from '../pages/clients/list'; import { JobsListPage } from '../pages/jobs/list'; import { SplashPage } from '../pages/splash/splash'; import { StatusPage } from '../pages/status/status'; import { LoginPage } from '../pages/login/login'; @Component({ templateUrl: 'app.html' }) export class MyApp { @ViewChild(Nav) nav: Nav; rootPage: any = SplashPage; pages: Array<{title: string, component: any}>; constructor( private translate: TranslateService, public platform: Platform, public network: Network, public statusBar: StatusBar, public splashScreen: SplashScreen, public storage: Storage, public alertCtrl: AlertController ) { this.initializeApp(); this.initTranslate(); // used for an example of ngFor and navigation this.pages = [ { title: 'STATUS', component: StatusPage }, { title: 'JOBS', component: JobsListPage }, { title: 'CLIENTS', component: ClientsListPage } ]; } initializeApp() { this.platform.ready().then(() => { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. this.statusBar.styleDefault(); this.splashScreen.hide(); this.listenConnection(); }).catch(error => console.log(JSON.stringify(error))) } initTranslate() { // Set the default language for translation strings, and the current language. this.translate.setDefaultLang('de'); } openPage(page) { // Reset the content nav to have just this page // we wouldn't want the back button to show in this scenario this.nav.setRoot(page.component); } logoutClicked() { let confirmation = this.alertCtrl.create({ title: 'Sind Sie sicher?', message: 'Sind Sie sicher, dass Sie sich abmelden möchten? Alle nicht synchronisierten Daten gehen dadurch verloren.', buttons: [ { text: 'Abbrechen', handler: () => { console.log('Disagree clicked'); } }, { text: 'Abmelden', handler: () => { this.storage.clear().then( () => this.nav.setRoot(LoginPage) ) } } ] }); confirmation.present(); } private listenConnection(): void { console.log(JSON.stringify(this.network.type)) let disconnectSubscription = this.network.onDisconnect().subscribe(() => { let alert = this.alertCtrl.create({title: 'Connection', message: 'Network has been disconnected', buttons: ['OK']}) alert.present() }); disconnectSubscription.unsubscribe(); let connectSubscription = this.network.onConnect().subscribe(() => { let alert = this.alertCtrl.create({title: 'Connection', message: 'Network has been connected', buttons: ['OK']}) alert.present() }) connectSubscription.unsubscribe(); } } 返回一个空字符串,因此您必须手动将指针移至文件开头,以便在写入后读取内容

f.read()

答案 1 :(得分:0)

urls.py

  url(r'^(?P<filename>(test.txt))$',
    home_files, name='home-files')

views.py

def server_text_file(request, filename):
    return render(request, filename, {}, content_type="text/plain")

然后您将{.1}文件夹中的test.txt文件保存下来。

答案 2 :(得分:0)

我解决了我的问题。似乎我的urls.py由于名称错误。

在修复此问题之前,reportview.report和reportview.report_generate具有相同的路由。

path('report/', reportview.report, name="report"),
path('report/', reportview.report_generate, name="download"),

这是新的urls.py

urlpatterns = [
path('admin/', admin.site.urls),
path('', qrview.index),
path('forms/new_profile', formsview.profile_create, name="aaa"),    # test
path('forms/new_course', formsview.course_create, name="ddd"),      # test
path('forms/edit_course', formsview.course_edit, name="edit_course"),   # test
path('report/', reportview.report, name="report"),
path('report/download', reportview.report_generate, name="download"),

]

即使是现在,我仍然对实际发生的事情感到困惑?我认为当我单击链接时,它将转到reportview.report_generate中的代码并生成文本文件并下载。