pythondjangodjango-1.7ajax-upload

User Specific Uploads Django 1.7


im getting this error "NOT NULL constraint failed: myfiles_document.user_id" what im trying to do is attach files to user ForeignKey so user can only see what they upload im using this app django-file-form here the code for the project

model.py

class Example2(models.Model):
    title = models.CharField(max_length=255)

class ExampleFile(models.Model):
    fs = FileSystemStorage(location=settings.MEDIA_ROOT)
    input_file = models.FileField(max_length=255, upload_to='uploads/%Y.%m.%d' , storage=fs)
    user = models.ForeignKey('auth.User')


    def get_upload_path(self,filename):
        return "static/uploads/"+str(self.user.id)+"/"+filename

forms.py

class BaseForm(FileFormMixin, django_bootstrap3_form.BootstrapForm):
    title = django_bootstrap3_form.CharField()


class MultipleFileExampleForm(BaseForm):
    input_file = MultipleUploadedFileField()

def save(self):
    example = Example2.objects.create(
        title=self.cleaned_data['title']
    )

    for f in self.cleaned_data['input_file']:
        ExampleFile.objects.create(
            input_file=f
        )

    self.delete_temporary_files()

views.py

 class BaseFormView(generic.FormView):
    template_name = 'example_form.html'

 def get_success_url(self):
    return reverse('example_success')

 def form_valid(self, form):
    form.save()
    return super(BaseFormView, self).form_valid(form)    

class ExampleSuccessView(generic.TemplateView):
    template_name = 'success.html'

class MultipleExampleView(LoginRequiredMixin, BaseFormView):
    form_class = forms.MultipleFileExampleForm

Solution

  • Your foreign key will not be automatically set to the current user unless you do it manually. That's why you are getting the not-null constraint error. Try modifying your form_valid method like this:

    def form_valid(self, form):
        form.instance.user = self.request.user
        ...
    

    Read Django's documentation on models and request.user for details.