''CustomUser' object has no attribute 'get'

I'm trying to auto-assign a ModelForm field to be a ForeignKey from the Model that the ModelForm is based off of. The Model includes a ForeignKey that references a CustomUser.

What I'd like to do is auto-assign the ModelForm field so that a logged-in user can submit the form as save the data to the database. I keep getting this error: 'CustomUser' object has no attribute 'get'. I don't understand what is throwing this error. I have pointed the settings to my CustomUser and registered the models in the admin files for each app. Additionally, both Models show up in the admin section of my project, but when I save the form for a logged in user I get that error and it doesn't save to the database.

Code Below for Reference:

class CustomUserManager(BaseUserManager):

    def create_user(self, email, password=None):
        if not email:
            raise ValueError('Account must have an email address')
    
        user = self.model(
            email = self.normalize_email(email),     
            )
    
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password):
        user = self.create_user(
            email = self.normalize_email(email),
            password = password,)

        user.is_admin = True
        user.is_staff = True
        user.is_active = True
        user.is_superuser = True
        user.save(using = self._db)
        return user

class CustomUser(AbstractBaseUser, PermissionsMixin):

    email = models.EmailField(max_length = 100, unique = True)
    first_name = models.CharField(max_length = 50, verbose_name='first name')
    last_name = models.CharField(max_length = 50, verbose_name='last name')
    date_joined = models.DateTimeField(auto_now_add = True, verbose_name='joined')
    last_login = models.DateTimeField(auto_now = True, verbose_name='last login')
    is_active = models.BooleanField(default = True)
    is_admin = models.BooleanField(default=False)
    is_staff = models.BooleanField(default = False)
    is_superuser = models.BooleanField(default=False)

    objects = CustomUserManager()

    USERNAME_FIELD = 'email'
    REQIURED_FIELDS = []

    def get_user_email(self):
        return self.email

    def get_user_name(self):
        return str(self.first_name) + str(self.last_name)

    def has_perm(self, perm, obj = None):
        return self.is_admin

    def has_module_perms(self, app_label):
        return True

Model:

class FacilityInfo(models.Model):
    email = models.ForeignKey(get_user_model(), on_delete = models.CASCADE)
    num_facilities = models.PositiveBigIntegerField()

    num_one = models.URLField(null = True)
    num_two = models.URLField(null = True)
    num_one_name = models.CharField(max_length = 50, null = True)
    num_two_name = models.CharField(max_length = 50, null = True)
    ess_login = models.CharField(max_length= 200, null = True)
    ess_pw = models.CharField(max_length= 200, null = True)

Model Form:

class FacilitySetup(forms.ModelForm):

    class Meta:
        model = FacilityInfo
        fields = ('ess_login','ess_pw','num_one','num_one_name','num_two','num_two_name')

    ess_login = forms.CharField(widget=forms.TextInput(
        attrs={
            "placeholder":"Easy Storage Username",
            "class" : "form-control"
        }
    ))

    ess_pw = forms.CharField(widget=forms.TextInput(
        attrs={
            "placeholder":"Easy Storage Password",
            "class" : "form-control"
        }
    ))   

    num_facilities = forms.IntegerField(help_text = "# of Facilities")

    num_one = forms.URLField(widget = forms.URLInput(
        attrs={
            "placeholder":'Facility 1 URL',
            'class': "form-control"
        }
    ))

    num_one_name = forms.CharField(widget=forms.TextInput(
        attrs={
            "placeholder":"Facility 1 Name",
            "class" : "form-control"
        }
    ))

    num_two = forms.URLField(widget = forms.URLInput(
        attrs={
            "placeholder":'Facility 2 URL',
            'class': "form-control"
        }
    ))

    num_two_name = forms.CharField(widget=forms.TextInput(
        attrs={
            "placeholder":"Facility 2 Name",
            "class" : "form-control"
        }
    ))

View:

@login_required(login_url="/login/")
def facility_info(request):
    msg = None
    success = False

    if request.method == 'POST':
        form = FacilitySetup(request.user, request.POST)
        if form.is_valid():
            obj = form.save(commit=False) # Return an object without saving to the DB
            obj.email = request.user  # Add an author field which will contain current user's id
            obj.save()

            msg = 'Facility Info Succesfully Saved'
            success = True

        else:
            msg = "Fields are not valid"

    else:
        form = FacilitySetup()

    return render(request, "facilities/settings.html",{"form": form, "msg":msg, "success":success})

Traceback Error:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/facilities

Django Version: 3.2.11
Python Version: 3.9.7
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'accounts.apps.AccountsConfig',
 'home.apps.HomeConfig',
 'facilities.apps.FacilitiesConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "/Users/jack/Desktop/storageapp/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/Users/jack/Desktop/storageapp/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/jack/Desktop/storageapp/lib/python3.9/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/Users/jack/Desktop/storageapp/storageapp/facilities/views.py", line 26, in facility_info
    if form.is_valid():
  File "/Users/jack/Desktop/storageapp/lib/python3.9/site-packages/django/forms/forms.py", line 175, in is_valid
    return self.is_bound and not self.errors
  File "/Users/jack/Desktop/storageapp/lib/python3.9/site-packages/django/forms/forms.py", line 170, in errors
    self.full_clean()
  File "/Users/jack/Desktop/storageapp/lib/python3.9/site-packages/django/forms/forms.py", line 372, in full_clean
    self._clean_fields()
  File "/Users/jack/Desktop/storageapp/lib/python3.9/site-packages/django/forms/forms.py", line 384, in _clean_fields
    value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
  File "/Users/jack/Desktop/storageapp/lib/python3.9/site-packages/django/forms/widgets.py", line 263, in value_from_datadict
    return data.get(name)
  File "/Users/jack/Desktop/storageapp/lib/python3.9/site-packages/django/utils/functional.py", line 247, in inner
    return func(self._wrapped, *args)

Exception Type: AttributeError at /facilities
Exception Value: 'CustomUser' object has no attribute 'get'


Solution 1:[1]

form = FacilitySetup(request.user, request.POST)

You are passing request.user to your form, as well as request post. The FacilitySetup signature only indicated one argument is required, so I suspect it is treating your user as posted form results. I can't see that your form is using request.user at all, so try removing request.user from that line.

I also see that your list of fields in your Model Form does not include num_facilities. As this field not listed in the model as able to be null or blank, the creation may fail when it tries to save. Try:

fields = ('ess_login','ess_pw','num_facilities', 'num_one','num_one_name','num_two','num_two_name')

to add it to your form.

The missing field should be brought up as an error in your page template. Make sure you include something like:

{% for error in form.non_field_errors %}
    {{error}}
{% endfor %}

to see if that provides any insight.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1