I have a django web app where I want users to upload their data in the form of csv. I have created a function and a page where the user uploads csv, and I have appended the user to the model, but I want that user to be the foreign key for each of the files. From what I see, the data is being entered in the database just fine but I do not think it is properly connected with a foreign key because on analyzing the database it says there are no foreign keys connected, and just the value is being entered with no relation what so ever.

Here is my function:

def upload_batch(request):
    template_name = 'classroom/teachers/upload.html'
    prompt = {'order':'Order of csv should be first_name, last_name, email, ip_address, message'}
    if request.method == "GET":
        return render(request,template_name,prompt)

    csv_file = request.FILES['file']
    data_set = csv_file.read().decode('UTF-8')
    io_string = io.StringIO(data_set)
    next(io_string)


    uploaded_by = request.user


    for column in csv.reader(io_string,delimiter=',',quotechar='|'):
        _, created = ItemBatch.objects.update_or_create(
            name = column[0],
            pid = column[1],
            quantity = column[2],
            length = column[3],
            width = column[4],
            height = column[5],
            volume = column[6],
            weight = column[7],
            uploaded_by = uploaded_by
        )


    context = {}
    return render(request,template_name,context)

Here is my model:

# item upload
class ItemBatch(models.Model):

    # uploaded_by = models.ForeignKey(Teacher, on_delete=models.CASCADE, related_name='uploaded_by')

    uploaded_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='uploaded_by')

    name = models.CharField(max_length=30)
    pid = models.CharField(max_length=30)
    quantity = models.CharField(max_length=30)
    length = models.CharField(max_length=100, blank=True)
    width = models.CharField(max_length=100, blank=True)
    height = models.CharField(max_length=100, blank=True)
    volume = models.CharField(max_length=100, blank=True)
    weight = models.CharField(max_length=100, blank=True)

    def __str__ (self):
        return self.name

UPDATE: Here is a screenshot of the model in my database.As you can see, the uploaded_by is not being shown as a foreign key, just like it is being shown in this other working model.

My model in database: 1

Foreign key tab is empty. 1

My other working model with FK. 3

1 Answers

0
NKay On

The code and the model looks fine. Did you make some changes to the model in the past (and ran makemigrations, migrate)? According to your screenshots there is no foreign key constraint on that table, which is strange since it seems to get populated correctly. Did you refresh/synchronize the schema in the tool?