[Django]-Django IntegrityError; NOT NULL constraint failed

4👍

Try changing the view:

form = AudioFileForm(request.POST, request.FILES)
if form.is_valid():
    audio_file = form.save(commit=False) // This will not hit the database, and no IntegrityError will be raised
    audio_file.uploader = request.user  // Tack on the user, 
    audio_file.save()
    return HttpResponseRedirect(
        reverse_lazy('home_audio',kwargs={'pk':audio_file.pk}) // Use reverse lazy to prevent circular import issues.
    )
else:
    return HttpResponse(form.errors)

Also you could fix some issues with the model:

from django.conf import settings
from django.db import models

class AudioFile(models.Model):
    name = models.CharField(max_length=100) // If the field is not allowed to be blank, the default blank does not make sense.
    audio_file = models.FileField(upload_to="audio_files") // Without this parameter file field does not work.
    uploader = models.ForeignKey(settings.AUTH_USER_MODEL) // This should reference the user model declared in your settings file.

    def __unicode__(self):
        return self.name   

Leave a comment