For example, in the case of an app that registers store information, I think that the prefecture of that store may be set.
I've left it in this article as a reminder so that you can use this feature at any time.
models.py
class Pref(models.Model):
code = models.CharField(max_length=2)
name = models.CharField(max_length=4)
def __str__(self):
return str(self.name)
views.py
def upload(request):
if 'csv' in request.FILES:
form_data = TextIOWrapper(request.FILES['csv'].file, encoding='shift_jis')
csv_file = csv.reader(form_data)
for line in csv_file:
pref, created = Pref.objects.get_or_create(code=line[0])
pref.code = line[0]
pref.name = line[1]
pref.save()
return render(request, 'pref/upload.html')
else:
return render(request, 'pref/upload.html')
that's all.
Recommended Posts