I've this two models:
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)
With File model it should be uploaded a csv file and then the information in the file should be saved in the Dataset model. After that I'd like to show some chart to my user so I need my File and Dataset models linked. This is my view:
VIEWS
def file_upload(request):
data = None
if request.method == 'POST':
form = FileForm(request.POST, request.FILES)
raw_file= request.FILES
if form.is_valid():
form.instance.user = request.user.profile
form.instance.filename = raw_file['file_upload'].name
form.save()
data = request.FILES['file_upload']
data = pd.read_csv(data, header=0, encoding="UTF-8")
data_form.instance.user = request.user.profile
Dataset.objects.create(
name_user_A = data.iloc[0,1],
name_user_B = data.iloc[1,1],
[...]
)
return redirect('upload_file')
else:
return redirect('home')
else:
form = FileForm()
context = {
'data': data,
'form': form,
}
return render(request, 'upload_file.html', context)
When I try to access the Dataset database in the admin area I get this error: 'NoneType' object has no attribute 'user'
.
I cannot also access the html page with results and the chart because I'm getting this error: Dataset matching query does not exist.
These are the view and the url code on how I'm reaching the html page
def results(request, id):
results = File.objects.filter(user=request.user.profile).filter(pk=id)
context = {
'results': results
}
return render(request, 'results.html', context)
urlpatterns = [
path('chart/<id>', views.results, name="file"),
]
Can someone kindly help me and explain to me how can I fix my code? Thank you
