Implement CSV import
This commit is contained in:
parent
8f762e2f92
commit
7ffb5338ac
11
README.md
11
README.md
|
@ -7,6 +7,17 @@ Yes, the infamous todo app.
|
|||
- Django
|
||||
- djangorestframework
|
||||
|
||||
## Importing from CSV
|
||||
|
||||
You can import from CSV with first line indicating name and deadline date, and
|
||||
subsequent lines indicating todo item name and status. For example:
|
||||
|
||||
```csv
|
||||
Today list,2021-11-11
|
||||
First item,1
|
||||
Second item,0
|
||||
Third item,0
|
||||
```
|
||||
|
||||
## Copying
|
||||
|
||||
|
|
|
@ -0,0 +1,4 @@
|
|||
Today list,2021-11-11
|
||||
First item,1
|
||||
Second item,0
|
||||
Third item,0
|
|
|
@ -19,6 +19,7 @@
|
|||
|
||||
<!-- MAIN CONTENT -->
|
||||
<main>
|
||||
<a href="{% url 'import' %}">Import CSV</a>
|
||||
{% block body %}
|
||||
{% endblock %}
|
||||
</main>
|
||||
|
|
|
@ -0,0 +1,12 @@
|
|||
{% extends 'base.html' %}
|
||||
|
||||
{% block body %}
|
||||
|
||||
<form method="post" action="{% url 'import' %}" enctype="multipart/form-data">
|
||||
{% csrf_token %}
|
||||
<label for="file">Upload CSV file</label><br>
|
||||
<input type="file" name="file" id="file" accept="text/csv"><br>
|
||||
<input type="submit" value="Import">
|
||||
</form>
|
||||
|
||||
{% endblock %}
|
|
@ -7,4 +7,5 @@ urlpatterns = [
|
|||
path('<int:list_id>', views.view_list, name='todo'),
|
||||
path('create', views.create_list, name='create_list'),
|
||||
path('<int:list_id>/create', views.create_item, name='create_item'),
|
||||
path('import', views.import_csv, name='import'),
|
||||
]
|
||||
|
|
|
@ -1,4 +1,8 @@
|
|||
import csv
|
||||
|
||||
from datetime import date
|
||||
from io import StringIO
|
||||
|
||||
import requests
|
||||
|
||||
from django.shortcuts import redirect, render
|
||||
|
@ -74,3 +78,30 @@ def create_item(request, list_id):
|
|||
'parent': list_id
|
||||
})
|
||||
return redirect('todo', list_id)
|
||||
|
||||
|
||||
def import_csv(request):
|
||||
"""View for importing CSV."""
|
||||
if request.method == 'GET':
|
||||
return render(request, 'import.html')
|
||||
fname = request.FILES['file']
|
||||
f = fname.read().decode('utf-8')
|
||||
f = StringIO(f)
|
||||
reader = csv.reader(f, delimiter=',', lineterminator='\n')
|
||||
reader = list(reader)
|
||||
name, valid_date = tuple(reader.pop(0))
|
||||
print(name, valid_date)
|
||||
endpoint = API_BASE % '/lists/'
|
||||
response = requests.post(endpoint, json={
|
||||
'name': name,
|
||||
'valid_until': valid_date
|
||||
})
|
||||
list_id = response.json()['id']
|
||||
for row in reader:
|
||||
endpoint = API_BASE % '/items/'
|
||||
name, valid_date = tuple(row)
|
||||
response = requests.post(endpoint, json={
|
||||
'name': name,
|
||||
'parent': list_id
|
||||
})
|
||||
return redirect('todo', list_id)
|
||||
|
|
Loading…
Reference in New Issue