3

I would like to have the slug input field be set to read only but can't seem to utilize "Field.disabled" properly. How can I do that in a simple Django form?

This is my model

class Article(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField()
    body = models.TextField()
    thumb = models.ImageField(default='default.png', blank=True)

This is my forms.py

class CreateArticle(forms.ModelForm):
    class Meta:
        model = models.Article
        fields = ['title', 'body', 'slug', 'thumb']
bgardne7
  • 91
  • 1
  • 11
  • Does this answer your question? [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) – Foon Feb 08 '21 at 17:45
  • This appears to be a duplicate of https://stackoverflow.com/questions/324477/in-a-django-form-how-do-i-make-a-field-readonly-or-disabled-so-that-it-cannot (and it also sounds like field.disabled may not be exactly what you want if you want it to be readonly) – Foon Feb 08 '21 at 17:46
  • No, it doesn't. It is a chain of answers that leads back to the Django documentation. Was hoping for an answer that was adapted to my specific situation. – bgardne7 Feb 08 '21 at 19:03
  • That was it! Thank you so much! – bgardne7 Feb 10 '21 at 18:56

1 Answers1

6

You can disable your slug field the __init__ method:

class CreateArticle(forms.ModelForm):
    class Meta:
        model = models.Article
        fields = ['title', 'body', 'slug', 'thumb']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["slug"].disabled = True
        # Or to set READONLY
        self.fields["slug"].widget.attrs["readonly"] = True
NKSM
  • 5,422
  • 4
  • 25
  • 38