Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you access a Django Model "property" from it's ModelForm?

Tags:

I have a Django model class with a non-model-field property, ex:

def _get(self):     return "something" description = property(_get) 

I'm using the model class with in a ModelForm / ModelFormset. Is there any way to access the property from the form / formset? If not, what's best practice for including extra "display" data in a django formset?

like image 453
bsk Avatar asked Sep 29 '10 18:09

bsk


People also ask

How can I have multiple models in a single Django Modelform?

You can just show both forms in the template inside of one <form> html element. Then just process the forms separately in the view. You'll still be able to use form.

Is there a list field for Django models?

Mine is simpler to implement, and you can pass a list, dict, or anything that can be converted into json. In Django 1.10 and above, there's a new ArrayField field you can use.

What is @property in Django model?

What is @property in Django? Here is how I understand it: @property is a decorator for methods in a class that gets the value in the method. But, as I understand it, I can just call the method like normal and it will get it.


1 Answers

If your ModelForm was initialized with an instance of a Model, then you can access it through the instance attribute. From the ModelForm docs:

Also, a model form instance bound to a model object will contain a self.instance attribute that gives model form methods access to that specific model instance.

like image 125
ars Avatar answered Sep 22 '22 17:09

ars