1

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)

1
  • You can just retrieve data and create an object based on that. Commented Nov 19, 2021 at 15:27

1 Answer 1

1

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,
                ...,
                ...)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I'm trying your advice and I'm getting this error = NOT NULL constraint failed: app_data.file_uploaded_id. I think I should automatically link the data form to the file form? I've tried this data_form.file_uploaded = request.file_uploaded.file and I'm getting this error 'WSGIRequest' object has no attribute 'file_uploaded'. Thank you again for the helps
How do you show user the values that didn't get imported due to DB Integrity errors?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.