我有一个django应用程序,该应用程序存储有关不同个人资料的信息。我希望能够提供一个可下载的电子表格,并使用相同的网址更新网站上的class-view(ListView)。我还没有完全理解类视图,并且正在努力找出如何结合下面的两个视图功能。
我尝试了这个: views.py
class ProfileList(ListView):
model = Profile
#template_name = 'search.html'
def get(self, request):
return export_profiles(request)
def export_profiles(request):
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="profile_list.csv"'
writer = csv.writer(response)
writer.writerow(['Name','Title','Location','Phone','Email','Company Name','Company Size','Link'])
data = Profile.objects.filter()
for row in data:
rowobj = [row.name,row.title,row.location,row.phone,row.email,row.GetCompany().companyName,row.GetCompany().companySize,row.url]
writer.writerow(rowobj)
#Clean up database
return response
urls.py
urlpatterns = [
path('search/', views.search, name='search'),
path('profiles/', ProfileList.as_view()),
path('accounts/', include('django.contrib.auth.urls')),
url('session_security/', include('session_security.urls')),
]
这可以下载文件,但是仍然没有使用django as_view()函数更新配置文件列表。它只是下载了csv文件而没有错误。
这是我目前拥有的:
views.py
#Post a view of profiles on the website when a search is initiated
class ProfileList(ListView):
model = Profile
template_name = 'search.html'
@login_required
def export_profiles(request):
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="profile_list.csv"'
writer = csv.writer(response)
writer.writerow(['Name','Title','Location','Phone','Email','Company Name','Company Size','Link'])
data = Profile.objects.filter()
for row in data:
rowobj = [row.name,row.title,row.location,row.phone,row.email,row.GetCompany().companyName,row.GetCompany().companySize,row.url]
writer.writerow(rowobj)
return response
urls.py
urlpatterns = [
path('search/', views.search, name='search'),
path('profiles/', views.export_profiles, name='profiles'),
path('accounts/', include('django.contrib.auth.urls')),
url('session_security/', include('session_security.urls')),
]
search.html
<div class="column">
<h3>Profiles</h3>
<font color="red">
<p>The following list does not save after the next search you make! Please save the csv file placed in your browser downloads folder.</p>
</font>
{% for profile in object_list %}
<ul>
<li>Name: {{ profile.name }}</li>
<li>Title: {{ profile.title }}</li>
<li>Location: {{ profile.location }}</li>
<li>Phone: {{ profile.phone }}</li>
<li>Email: {{ profile.email }}</li>
<li>Company Name: {{ profile.GetCompany.companyName }}</li>
<li>Company Size: {{ profile.GetCompany.companySize }}</li>
<li>Link: <a href={{ profile.url }}>{{ profile.url }}</a></li>
</ul>
{% endfor %}
<br />
</div>
我是否想在一个URL下合并django类视图和另一个视图函数?完整的解决方案会很好,但有很多要求。我只是问一些指针和链接,以进一步了解这个问题。