Django - problem with saving data in Createview with ModelForm to non-default database

20 Views Asked by At

I've got problem with saving data to non-default database.

In models.py I've got:

grid_fs_storage = GridFSStorage(collection='tab_userinquiries', base_url='mydomain.com/userinquiries/',database='mongo_instance')

class DocsUserInquiry(models.Model):
    query_pk = models.CharField(blank=False, null=False, unique=True, max_length=150, primary_key=True)  # auto - calculated
    query_file_md5 = models.CharField(blank=False, null=True, unique=False, max_length=200)  # auto - calculated
    query_file = models.FileField(upload_to='userinquiries',storage=grid_fs_storage,null=True)  # auto from form

In views.py:

class UploadInquiryFileView(CreateView,LoginRequiredMixin):
    model=DocsUserInquiry
    template_name ='new_inquiry.html'
    success_message = "You've added your new Token successfully"
    form_class = UploadInquiryFileForm
    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST, request.FILES)
        if form.is_valid():
            file_name = request.FILES['query_file'].name
            print(f'file...{file_name}')
            q_pk = random_id()
            file_in = self.request.FILES.get('query_file')
            f_md5 = calculate_md5(file_in)            
            form.instance.query_pk = q_pk
            form.instance.query_file_md5 = f_md5
            form.save()
            return HttpResponse(self.success_message)

The problem is every time when I submit form I've got

Exception Type: TypeError
Exception Value:    database must be an instance of Database

I've tried added this to post method:

instance = form.save(commit=False)
instance.save(using='mongo_instance')

but the error is the same.

Any ideas how to resolve this issue?

NOTE: This issue is related only with modelform or when I use custom list of fields in view. When I'm using CreateView without ModelForm but with fields = 'all' and additionally with the logic passed to form_valid method of the view instead of post everything works fine. Then files are added to my mongo db.

1

There are 1 best solutions below

0
data_b77 On

After some tests I've figured out the problem is in gridfs. After making small change in FileField I got expected result.

I had to delete upload_to and storage from this field in models.py. This saves data from my form into mongo but without the file itself. To do that I had to add in post method of my CreateView connection to mongo via MongoClient and save file in such separate way.

Completely don't know what's the issue with gridfs storage pointed directly in the model's FileField.