简体   繁体   中英

Django: Import data from uploaded excel file

I'm trying to create an app to import thanks to an uploaded.csv file data to my database. This is where I've managed to arrive by myself: my file is uploaded without problems and I can pass the information from the file to the variable first_row and second row. My problem now is how I can save the information in the database. My views code:

VIEWS

@login_required
def file_upload(request):
    data = None

    if request.method == 'POST':
        file_form = FileForm(request.POST, request.FILES)
        data_form = DatasetForm(request.POST, request.FILES)
        raw_file= request.FILES
        if file_form.is_valid() or data_form.is_valid():       
            data = request.FILES['file_upload']             
            data = pd.read_csv(data, header=0, encoding="UTF-8")                   
            first_row = data.iloc[[0]]
            second_row = data.iloc[[1]] 
                            
            file_form.instance.user = request.user.profile    
            file_form.instance.filename = raw_file['file_upload'].name            
            file_form.save() 
            return redirect('upload_file')
        else:
            return redirect('home')
    else:
        form = FileForm()  
 
    context = {              
               'data': data,
               'second_row': second_row,
               'file_form': file_form,                             
               'message': message,         
               }
    return render(request, 'upload_file.html', context)

These are how my data and models looks: DATA

        code  tot sd     
name_1  aa    3    1
name_2  bb    7    2

MODEL

class File(models.Model): 
    user = models.ForeignKey(Profile, on_delete=models.CASCADE)   
    filename = models.CharField(max_length=250)   
    file_upload = models.FileField(upload_to=path)
    upload_date  = models.DateField(default=datetime.now)   

    def __str__(self):        
        return self.user.name + 'file'

class Dataset(models.Model):    
    user = models.ForeignKey(Profile, on_delete=models.CASCADE)
    file_uploaded = models.OneToOneField(File, on_delete=models.CASCADE)

    name_user_A = models.CharField(max_length=250)
    code_user_A = models.PositiveIntegerField(null=True)
    total_user_A = models.PositiveIntegerField(null=True)
    sd_user_A = models.PositiveIntegerField(null=True)

    name_user_B = models.CharField(max_length=250)
    code_user_B = models.PositiveIntegerField(null=True)
    total_user_B = models.PositiveIntegerField(null=True)
    sd_user_B = models.PositiveIntegerField(null=True)

FORMS

class FileForm(forms.ModelForm):
    class Meta:
        model = File
        fields = '__all__'


class DatasetForm(forms.ModelForm):
    class Meta:
        model = Dataset
        fields = '__all__'

Basicaly I need to save the first row in the field for user_A and the second row for the user_B. Only the model File is compiled by the user, while Dataset should be filled automatically from the information in the file. How can I do this? Thank you all, PS(I had to do some change to make it shorter and more understandable, there could be some typo but it's acutally works)

If you import your Dataset model you can create a new object based on the data you've already got from the file.

for example:

#import your model
from . models import Dataset


@login_required
def file_upload(request):
    data = None

    if request.method == 'POST':
        file_form = FileForm(request.POST, request.FILES)
        data_form = DatasetForm(request.POST, request.FILES)
        raw_file= request.FILES
        if file_form.is_valid() or data_form.is_valid():       
            data = request.FILES['file_upload']             
            data = pd.read_csv(data, header=0, encoding="UTF-8")                   
            first_row = data.iloc[[0]]
            second_row = data.iloc[[1]] 

            # create new dataset object
            Dataset.objects.create(
                name_user_A=first_row,
                name_user_B=second_row,
                ...,
                ...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM