Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I disable a model field in a django form

I have a model like this:

class MyModel(models.Model):
    REGULAR = 1
    PREMIUM = 2
    STATUS_CHOICES = ((REGULAR, "regular"), (PREMIUM, "premium"))
    name = models.CharField(max_length=30)
    status = models.IntegerField(choices = STATUS_CHOICES, default = REGULAR)

class MyForm(forms.ModelForm):
    class Meta:
        model = models.MyModel

In a view I initialize one field and try to make it non-editable:

myform = MyForm(initial = {'status': requested_status})
myform.fields['status'].editable = False

But the user can still change that field.

What's the real way to accomplish what I'm after?

like image 549
jammon Avatar asked Feb 09 '11 13:02

jammon


People also ask

How do you exclude a specific field from a model form?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

How do you make a field non editable in Django?

django-forms Using Model Form Making fields not editable disabled attribute: The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won't be editable by users.

How do you make a field readonly in Django?

Setting readonly on a widget only makes the input in the browser read-only. Adding a clean_sku which returns instance. sku ensures the field value will not change on form level. This way you can use model's (unmodified save) and avoid getting the field required error.

How do you remove this field is required Django?

If yes try to disable this behavior, set the novalidate attribute on the form tag As <form action="{% url 'new_page' %}", method="POST" novalidate> in your html file. At you model, the setting title/content = CharField(null=True, blank=True) doesn´t work? At your model-form have you tried setting title/content = forms.


2 Answers

Step 1: Disable the frontend widget

Use the HTML readonly attribute:
http://www.w3schools.com/tags/att_input_readonly.asp

Or disabled attribute:
http://www.w3.org/TR/html401/interact/forms.html#adef-disabled

You can inject arbitrary HTML key value pairs via the widget attrs property:

myform.fields['status'].widget.attrs['readonly'] = True # text input
myform.fields['status'].widget.attrs['disabled'] = True # radio / checkbox

Step 2: Ensure the field is effectively disabled on backend

Override your clean method for your field so that regardless of POST input (somebody can fake a POST, edit the raw HTML, etc.) you get the field value that already exists.

def clean_status(self):
    # when field is cleaned, we always return the existing model field.
    return self.instance.status
like image 96
Yuji 'Tomita' Tomita Avatar answered Oct 19 '22 00:10

Yuji 'Tomita' Tomita


From django 1.9:

from django.forms import Textarea

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = '__all__'
        widgets = {'my_field_in_my_model': Textarea(attrs={'cols':80,'rows':1}),}             

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['my_field_in_my_model'].disabled = True
like image 25
xleon Avatar answered Oct 19 '22 02:10

xleon