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?
Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With