Как мне обновить общий вид классов? - PullRequest
0 голосов
/ 10 июля 2019

У меня есть приложение django, которое хранит информацию о разных профилях людей. Я хочу иметь возможность предоставить загружаемую электронную таблицу и обновить представление класса (ListView) на веб-сайте, используя тот же URL-адрес. Я еще не полностью понимаю представления классов, и я изо всех сил пытаюсь понять, как объединить две функции представления ниже.

Я попробовал это: 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>

Прав ли я, пытаясь объединить представление класса django и другую функцию представления под одним URL? Полное решение было бы неплохо, но очень много просить. Я просто прошу несколько указателей и ссылок для дальнейшего изучения этой проблемы.

...