Answer the question
In order to leave comments, you need to log in
How to make spaces invisible when exporting CSV in Django?
The goal is to upload a csv file to django models.
There is a CSV file with 7 columns. And the model has 6 values.
Full name, apartment number, ownership, share, size and cadastral number
Another 1 column is the ID, which I do not output.
models.py
from django.db import models
# Create your models here.
class Citizen(models.Model):
name = models.CharField(max_length = 500)
flat = models.CharField(max_length = 15)
size = models.CharField(max_length = 30)
share = models.CharField(max_length = 30)
doc = models.CharField(max_length = 300)
kadastr = models.CharField(max_length = 300)
def __str__(self):
return self.name
from django.shortcuts import render
from .forms import CsvModelForm
from .models import Csv
import csv
from citizens.models import Citizen
# Create your views here.
def upload_file_view(request):
form = CsvModelForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.save()
form = CsvModelForm()
obj = Csv.objects.get(activated=False)
with open(obj.file_name.path, 'r') as f:
reader = csv.reader(f)
for i, row in enumerate (reader):
if i==0:
pass
else:
row = "".join(row)
row = row.replace(";", " ")
#row = row.replace(" ", "")
row = row.split()
name = row[1]
flat = row[2]
size = row[3]
share = row[4]
doc = row[5]
kadastr = row[6]
Citizen.objects.create(
name = str(name),
flat = str(flat),
size = str(size),
share = str(share),
doc = str(doc),
kadastr = str(kadastr),
)
#print(row)
#print(type(row))
obj.activated = True
obj.save()
return render(request, 'csvs/upload.html', {'form':form})
from django import forms
from .models import Csv
class CsvModelForm(forms.ModelForm):
class Meta:
model = Csv
fields = ('file_name',)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question