NOT NULL constraint failed vol2

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.

Note that I am able to upload excel spreadsheet via Admin portal using import_export module. I can specify the user who is allowed to see the data as well, everything works well from portal. though my custom view gives error.

What does your UploadFileForm look like?


class UploadFileForm(ModelForm):
    class Meta:
        model = Yield_Curve
        fields = ['docfile']

A couple different things.

First, you’ve got six fields in the Yield_Curve model that are defined as not null, and your form / view isn’t assigning values to any of them.

Second, in your view you have:

which shows you saving the form with commit=False, and never updating or fully saving that form. All data submitted through that form is lost.
You then directly create a Yield_Curve object with two fields defined and save it instead.

What you want to do is add the fields to your form for the other fields in the model, save a reference to the instance of the Yield_Curve object created by the call to form.save, modify that instance instead of creating a new one and save it.

1 Like

The file that is supposed to be uploaded contains the data columns corresponding to the Yield_Curve Model fields, I don’t know how to assign each field to the corresponding column of the spreadsheet.

Form does not contain all model fields because Web App then shows all the fields as mandatory fields to be filled.

Would be very helpful if you could show the sample solution code of my issue. Thank you

There really isn’t anything for me to show.

You’ve got at least these three options:

  • Add those fields to the form

  • Process the uploaded file in your view, and extract the data needed to fill those fields

  • Make those fields nullable.

(There might be one or two other options, but nothing else comes to mind right now.)

You need to decide what is to populate those fields and when and how they are to be populated.