Ara Sivaneswaran
Ara Sivaneswaran

Reputation: 375

Django form instance is missing a field

So I have a problem. I have a model form:

class TeamForm(forms.ModelForm):

class Meta:
    model = Team
    fields = ['name','category','association','division','gender','logo','season']

def __init__(self, *args, **kwargs):
    self.user = kwargs.pop('user')
    super(TeamForm, self).__init__(*args, **kwargs)
    instance = getattr(self, 'instance', None)

    utils = CPUtils()
    season_utils = SeasonUtils()

    if instance and instance.pk is None:
        self.fields['division'].initial = 1
        self.fields['season'].initial = season_utils.getCurrentSeason().id

        if user_role != 'admin':
            self.fields['division'].widget.attrs['disabled'] = True
            self.fields['division'].required = False

            self.fields['season'].widget.attrs['disabled'] = True
            self.fields['season'].required = False

So I am setting the initial of the form for the field season. On my form, it is showing just fine.

So now in my clean method, I want to run some validation and I need to get the instance season.

In my clean method:

    if cleaned_data.get('season') is None:
        cleaned_data['season'] = self.instance.season

But it says that self.instance.season: DoesNotExist: Team has no season.

I have been trying to figure this out for a while now and I have no idea what's going on...

EDIT: Here my model:

name = models.CharField(max_length=25,verbose_name=_("name"))
slug = AutoSlugField(unique=True,populate_from='name')
season = models.ForeignKey(Season,verbose_name=_("season"),blank=False)
association = models.ForeignKey(Association,blank=False,null=True,verbose_name=_("association"),on_delete=models.SET_NULL)
category = models.ForeignKey(Category,verbose_name=_("category"),blank=False,null=True,default=1,on_delete=models.SET_NULL)
division = models.ForeignKey(Division,verbose_name=_("division"),blank=False,null=True,default=1,on_delete=models.SET_NULL)

Also, the instance does not have season only during create and not during update...

Thanks, Ara

Upvotes: 1

Views: 2990

Answers (1)

Aaron Lelevier
Aaron Lelevier

Reputation: 20770

The reason it says:

self.instance.season: DoesNotExist

Is that you are accessing self. Self here is actually the Form, and you are asking the Form for an attribute called instance, and then asking the instance attribute if it has a season attribute. The Form doesn't have this attribute.

What you really want to do is get the Model instance based on the Season ID, not the Form instance. The Form instance only holds the data temporarily while you clean it before you use the Model to save it to the database.

If you are trying to clean() the season, then you would want to access it this way if Season is an ID in your Form:

class TeamForm(forms.ModelForm): 

    # form logic here

    def clean(self):
        cleaned_data = super(TeamForm, self).clean()

        # now get the Season Object from the cleaned_data dictionary 
        #   if 'season' == season_id
        try:
            season_id = cleaned_data['season']
            season = Season.object.get(pk=season_id)
        except KeyError:
            # season id does not exist, so do something here
            pass

Upvotes: 1

Related Questions