I want to create a project an I need to upload an csv file to an user, but from some reason, it's not loading correctly (is uploading for the first created user, and I try do to this from others accounts).
In my view, I have something like this:
def FileViewUpload(request):
form = CsvFileForm(request.POST, request.FILES)
print(request.user)
userId = request.user.id
print(userId)
print(request.user.email)
if form.is_valid():
form.save()
form = CsvFileForm()
obj= CsvFileModel.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:
date = row[0]
user = AccountUser.objects.get(contact_user = userId)
print(user)
ContactUser.objects.create(
date=date,
message= row[1]
user=user,
)
obj.activated=True
obj.save()
return render(request, 'uploadFile.html', {
'importFile': form
})
For this lines:
print(request.user)
print(userId)
print(request.user.email)
it display the good thing, the correct id and email for that specific user. But when I press the button for upload, it's loading in the field for the first user created.
The problem, I think that is in this line: user = AccountUser.objects.get(contact_user = userId), but I don't know why, if in the beginning, at the first prints, it's show me correctly.
The model for ContactUser:
class ContactUser(models.Model):
user = models.ForeignKey(AccountUser, related_name='contact_user', on_delete=models.CASCADE)
date = models.CharField()
message = models.CharField()
def __str__(self):
return f"{self.user}"
Edit - short update
I think that I can not access in this meaner the user that was created. I delete all the migrations, I run the commands for migrations and create the user. When I want to import the document, it gives me this AccountUser matching query does not exist, but in the AcccountUser, I can see the registration of the user, and with the print commands that was mentioned above, I see that the id is 1, and the user email. I tried to wrote the next command user=AccountUser.objects.filter(contact_user = userId) and it gives me this Cannot assign "<QuerySet []>": "ContactUser.user" must be a "AccountUser" instance.