Hello,
I am trying to create a project where all users have opportunity to upload the data to the web app and see only their uploaded files. Although, I have a problem in uploading the file. it gives me integrity error NOT NULL constraint failed.
this is how the forms.py looks like:
from .models import Yield_Curve
from django.forms import ModelForm
class UploadFileForm(ModelForm):
class Meta:
model = Yield_Curve
fields = ['docfile']
def handle_uploaded_file(f):
with open('data/yield_curve.xlsx', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
Model.py:
from django.db import models
from datetime import datetime
from django.contrib.auth.models import User
class Yield_Curve(models.Model):
title = models.CharField(max_length=(100))
Date = models.DateField(default=datetime.now())
beta1 = models.FloatField()
beta2 = models.FloatField()
beta3 = models.FloatField()
tau = models.FloatField()
docfile = models.FileField(upload_to='data/', default="data/")
user = models.ForeignKey(User , on_delete=models.CASCADE)
def __str__(self):
return self.title
views.py:
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
form.save(commit=False)
newdoc = Yield_Curve(docfile = request.FILES['docfile'], user=request.user)
newdoc.save()
else:
form = UploadFileForm() # A empty, unbound form
data = Yield_Curve.objects.filter(user=request.user)
return render(request = request,
template_name='main/data.html',
context= {"Yield": data, "form": form})
Template.py:
{% extends 'main/header.html' %}
{% block content %}
<form method="POST" enctype= "multipart/form-data">
{% csrf_token %}
<br>
{{form.as_p}}
<br>
<button style="background-color:#FFD166; color:#000000" class="btn btn-outline-info" type="submit">Upload</button>
<br>
<table class="table table-hover">
<thead>
<tr>
<th>Date</th>
<th>beta1</th>
<th>beta2</th>
<th>beta3</th>
<th>tau</th>
<th></th>
</tr>
</thead>
<tbody>
{%for par in Yield%}
<tr>
<td>{{par.Date}} </td>
<td>{{par.beta1}} </td>
<td>{{par.beta2}} </td>
<td>{{par.beta3}} </td>
<td>{{par.tau}} </td>
</tr>
{%endfor%}
</tbody>
</table>
</form>
{% endblock %}
Thank you in advance.