So lets say I have these classes in my models.py
:
class Result(models.Model):
grade = models.CharField(max_length=10)
checked = models.BooleanField(blank=False, default=False)
checker = models.ForeignKey(User, on_delete=models.CASCADE)
class User(models.Model):
name = models.CharField(max_length=10)
And lets say i have a model form in my forms.py
:
class EnterResult(forms.ModelForm):
class Meta:
model = Result
exclude = ['checked']
I know to pass an instance of a form in views.py
you have to:
result = Result.objects.get(pk=pk)
form = EnterResult(instance=result)
return render(request, ...)
Now how do i make checker a read-only input when the instance that is passed has it's field checked = True
. I feel like it has something to do with overriding the ___init___(self, *args, **kwargs)
.
Yes, overriding __init__
for your form is the thing to do.
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
instance = getattr(self, 'instance', None)
if instance and instance.checked:
self.fields["checker"].disabled = True
https://docs.djangoproject.com/en/3.0/ref/forms/fields/#disabled
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.