Search code examples
python-3.xdjangoformsdjango-models

How to use Field.disabled in Django


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']

Solution

  • 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