Search code examples
djangodjango-modelsdjango-formsdjango-templatesdjango-widget

change field type in django forms


I have a model for a group that has two fields: leader and description.

models.py

class Group(models.Model):
   leader = models.ForeignKey(User, on_delete=models.CASCADE)
   description = models.TextField()

forms.py

class GroupForm(forms.ModelForm):

   class Meta:
      model = Group
      fields = ('leader', 'description')

My issue is that I want to change the field type for leader. Right now the default is a drop down/select with all the available Users in my database. I don't want Users to be able to make Groups in other Users' names. I want instead for the leader field to be a TextInput field and use javascript to change the leader value to whatever the Users.username value is.

So, the I added a widget, but now there's more problems:

forms.py

class GroupForm(forms.ModelForm):

   class Meta:
      model = Group
      fields = ('leader', 'description')

   widgets = {
      'leader': forms.TextInput(attrs={'id': 'leader', 'type': 'hidden', 'value': ''})
   }

My goal was to use a script tag on my django template to getElementById('leader') and change it's value to user.username all the while keeping it hidden from the current user.

However I keep hitting snags, the main one being I can't seem to change the field type for leader from a select to a TextInput, so every time I try and access the leader.value I get undefined.

Any help would help. Thanks.


Solution

  • widgets option should belong to form Meta, not to form class body (docs):

    class GroupForm(forms.ModelForm):
        class Meta:
            model = Group
            fields = ('leader', 'description')
    
            widgets = {
                'leader': forms.TextInput(attrs={'id': 'leader', 'type': 'hidden'})
            }
    

    I'm not sure that value key in widget attrs will work, this is at least very odd. If you do it to get blank string, you don't have to: default input.value is '', not undefined.