Commit 16 Wordbucket : add import function
Commits on Mar 30, 2018
/templates/detail.html
- เพิ่มปุ่มกดเลือกไฟล์ในเครื่องของ user โชว์ชื่อไฟล์ และปุ่มกด upload เพื่อใช้ function import_csv()
| @@ -39,6 +39,11 @@ <h2>{{ word }}</h2> |
| | <br> |
| | {% if user.is_authenticated %} |
| | <a href="{% url 'wordbucket:export' word.id %}">export</a><br><br> |
| | + <form action="{% url 'wordbucket:import' word.id %}" method="post" enctype="multipart/form-data"> |
| | + {% csrf_token %} |
| | + <input type="file" name="csv_file" /> |
| | + <input type="submit" value="Upload" /> |
| | + </form> |
| | {% endif %} |
| | <a href="{% url 'wordbucket:home' %}">HOME</a> |
| | </body> |
views.py
- os, codecs, TextIOWrapper เพื่อ TextIOWrapper ไฟล์ csv ที่ได้รับ post มาอ่านแล้วจึงแยก row ที่จำเป็นและสร้าง explanation ตามไฟล์ csv ที่เข้ามา
| @@ -3,9 +3,9 @@ |
| | from django.contrib.auth import login, authenticate |
| | from django.contrib.auth.forms import UserCreationForm |
| | from wordbucket.models import Word, Explanation, Like_and_dislike |
| | -import string |
| | -import csv |
| | +import string, csv, os, codecs |
| | from django.http import HttpResponse |
| | +from io import TextIOWrapper |
| | |
| | def home_page(request): |
| | d_message = "" |
| @@ -129,5 +129,13 @@ def export_csv(request, word_id): |
| | writer.writerows(output) |
| | return response |
| | |
| | -def import_csv(request, explanation_id): |
| | - pass |
| | +def import_csv(request, word_id): |
| | + word_ = Word.objects.get(id=word_id) |
| | + if request.POST and request.FILES: |
| | + csvfile = TextIOWrapper(request.FILES['csv_file'], encoding=request.encoding) |
| | + reader = csv.reader(csvfile) |
| | + next(reader) |
| | + for row in reader: |
| | + explanation_ = Explanation.objects.create(explanation_text=row[1], word=word_) |
| | + Like_and_dislike.objects.create(votes_like = 0, votes_dislike = 0, explanation = explanation_) |
| | + return HttpResponseRedirect(reverse('wordbucket:detail', args=(word_id,))) |
ไม่มีความคิดเห็น:
แสดงความคิดเห็น