djangomongodbdjongo

Cannot use ArrayField from Djongo Models


I'm trying to make an app with Django using MongoDB as my database engine, so I'm using Djongo as ORM. In my models, I have defined a Client class, which is intended to contain an array of Profiles (authorized people to login in name of client).

In the Djongo Documentation, it says one can use the ArrayField class in models in order to store an array to the database. The point is that I followed the example in the documentation (even I tried to copy without changing anything) and it isn't working. When running the view, I always get this error:

"Value: Profile object (None) must be an instance of <class 'list'>"

I have the following models.py:

from django import forms
from djongo import models

class Profile(models.Model):
    _id=models.ObjectIdField()

    fname = models.CharField(max_length=25)
    lname = models.CharField(max_length=50)
    email = models.EmailField()
    password = models.CharField(max_length=16)

    class Meta:
        abstract=True

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields =(
            'fname', 'lname', 'email', 'password',
        )

class Client(models.Model): #informacion del cliente
    _id = models.ObjectIdField()
    name = models.CharField(max_length=256)
    authorized = models.ArrayField(
        model_container=Profile,
        model_form_class=ProfileForm
    )

    objects = models.DjongoManager()

class ClientForm(forms.ModelForm):
    class Meta:
        model = Client
        fields = (
            'name', 'authorized'
        )

I have a form that uses ClientForm, and the view renders properly. However, when submitting the form I get the error I said at the beginning. I'm searched the whole internet and didn't get any idea of what is causing this problem.


Solution

  • I have bumped into a similar error a couple of days ago, I was trying to store an object (in your case it's Profile) directly to the ArrayField, I was trying to do something like:

    client = Client.object.first()
    client.authorized = {
    
        'fname': form.validated_data['first name'],
        'last': form.validated_data['last name'],
        'email': form.validated_data['email'],
        'password': form.validated_data['Password'],
    }
    client.save()
    

    the right way to do it is:

    client = Client.object.first()
        client.authorized = [{
        
            'fname': form.validated_data['first name'],
            'last': form.validated_data['last name'],
            'email': form.validated_data['email'],
            'password': form.validated_data['Password'],
        }]
        client.save()
    

    you'll need to store it as a list object by wrapping it around []

    that's how I was able to solve it in my case, I think yours is similar, try the above solution, and if it doesn't work, maybe you should share more details like your views.py