1

There is a 'league_type' field in my form and I want to make it readonly. I used widget.attr['readonly'] = True but it doesn't work.

The model:

class League(models.Model):
  league_types = (
      ('league', 'League'),
      ('knockout', 'Knockout'),
  )
  ....
  season = models.ForeignKey(Season, related_name = "league_season")
  league_type = models.CharField(max_length=10, choices = league_types, default ='league')
  ...

The ModelForm:

class LeagueForm(forms.ModelForm):
   class Meta:
      model = League
      fields = ('title', 'league_type', 'season', 'status')
      widgets = {'season':forms.HiddenInput(),}

view.py:

if League.objects.filter(season = season, league_type = 'knockout').count():
        form = LeagueForm(initial={'season': season, 'league_type': 'league'})
        form.fields['league_type'].widget.attrs['readonly'] = True
else:
        form = LeagueForm(initial={'season': season})

Update:

I cannot use disabled attribute because I'm going to create a form with league_type initial value.

Alireza Navaie
  • 133
  • 3
  • 15
  • 1
    I tink your answer can be found here: https://stackoverflow.com/questions/324477/in-a-django-form-how-do-i-make-a-field-readonly-or-disabled-so-that-it-cannot – Jelmer Oct 26 '17 at 14:48
  • Is the condition being hit? – Rob L Oct 26 '17 at 15:09
  • yes.the condition is True – Alireza Navaie Oct 26 '17 at 15:13
  • Possible duplicate of [In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?](https://stackoverflow.com/questions/324477/in-a-django-form-how-do-i-make-a-field-readonly-or-disabled-so-that-it-cannot) – solarissmoke Oct 27 '17 at 02:59

0 Answers0