I posted a similar question a while earlier, but this one is different. I have a model structure of related classes like:
class Question(models.Model):
ques_type = models.SmallIntegerField(default=TYPE1, Choices= CHOICE_TYPES)
class MathQuestion(Question):
//Need to change default value of ques_type here
// Ex: ques_type = models.SmallIntegerField(default=TYPE2, Choices= CHOICE_TYPES)
I want to change the default value of ques_type in the derived class. How should i accomplish this?
First, in this use of inheritance it is (at least according to my tests) not possible to change the default of the field in the child class. MathQuestion and Question share the same field here, changing the default in the child class affects the field in the parent class.
Now if what only differs between MathQuestion and Question is the behaviour (so, MathQuestion doesn't add any fields besides those defined in Question), then you could make it a proxy model. That way, no database table is created for MathQuestion.
from django.db import models
class Question(models.Model):
ques_type = models.SmallIntegerField(default=2)
class MathQuestion(Question):
def __init__(self, *args, **kwargs):
self._meta.get_field('ques_type').default = 3
super(MathQuestion, self).__init__(*args, **kwargs)
class Meta:
proxy = True
Test:
In [1]: from bar.models import *
In [2]: a=Question.objects.create()
In [3]: a.ques_type
Out[3]: 2
In [4]: b=MathQuestion.objects.create()
In [5]: b.ques_type
Out[5]: 3
Examples above are for proxy models. If you need to change default for model inherited from non-abstract base model you can do following:
from django.db import models
class Base(models.Model):
field_name = models.CharField(...)
class Child(Base):
def __init__(self, *args, **kwargs):
kwargs['field_name'] = kwargs.get('field_name') or 'default value'
super().__init__(*args, **kwargs)
Which will set default if it wasn't passed directly on Model(...) or Model.objects.create(...).
This is easy to do using a closure.
from django.db import models
# You start here, but the default of 2 is not what you really want.
class Question(models.Model):
ques_type = models.SmallIntegerField(default=2)
class MathQuestion(Question):
def __init__(self, *args, **kwargs):
self._meta.get_field('ques_type').default = 3
super(MathQuestion, self).__init__(*args, **kwargs)
class Meta:
proxy = True
The closure allows you to define it how you like it.
from django.db import models
def mkQuestion(cl_default=2):
class i_Question(models.Model):
ques_type = models.SmallIntegerField(default=cl_default)
class i_MathQuestion(i_Question):
def __init__(self, *args, **kwargs):
super(MathQuestion, self).__init__(*args, **kwargs)
return i_MATHQUESTION
MathQuestion = mkQuestion()
MathQuestionDef3 = mkQuestion(3)
# Now feel free to instantiate away.
Use a Form or ModelForm, on which you can override the field. For models, set the default value in it's __init__ method like so:
class Question(models.Model):
ques_type = models.SmallIntegerField(default=2)
class MathQuestion(Question):
def __init__(self, *args, **kwargs):
super(MathQuestion, self).__init__(*args, **kwargs)
self.ques_type = 3
class Meta:
proxy = True
Note that this has to be done after calling the parent class init.
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/
Related
Different proxy models should be different in type.
If I query those models I the right ones.
I am trying to save a default type field in a proxy model.
I don't want to set it everytime in the view.
This does not work. The type field is always "TYPE1".
models.py:
class MyModel(models.Model):
class ModelType(models.TextChoices):
TYPE1 = 'TYPE1', _('TYPE1')
TYPE2 = 'TYPE2', _('TYPE2')
type = models.CharField(max_length=100, choices=ModelType.choices, default='TYPE1')
class Type2Manager(models.Manager):
def get_queryset(self):
return super(Type2Manager, self).get_queryset().filter(type='TYPE2')
def save(self, *args, **kwargs):
kwargs.update({'type': 'TYPE2'})
return super(Type2Manager, self).save(*args, **kwargs)
class Type2ProxyModel(MyModel):
class Meta:
proxy = True
objects = Type2Manager()
views.py:
def create_type2_model(request):
form = Type2Form(request.POST, initial={})
f = form.save(commit=False)
f.save()
forms.py:
class Type2Form(ModelForm):
class Meta:
model = Type2ProxyModel
Update 25.02.2020 12:18:
I found out that this sets the correct type. But I don't know how to use create() in a ModelForm.
class Type2Manager(models.Manager):
...
def create(self, **kwargs):
kwargs.update({'type': 'TYPE2'})
return super(Type2Manager, self).create(**kwargs)
Type2ProxyModel.objects.create()
A model manager operates on a "table-level". When you create an object via a form it uses the model objects and not the model manager and thus you'd need to override the save of your proxy model. If I modify your Type2ProxyModel to this it works:
class Type2ProxyModel(MyModel):
class Meta:
proxy = True
objects = Type2Manager()
def save(self, *args, **kwargs):
self.type = 'TYPE2'
return super(Type2ProxyModel, self).save(*args, **kwargs)
I have this ModelForm:
class Event(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(Event, self).__init__(*args, **kwargs)
##Here make some changes such as:
self.helper = FormHelper()
self.helper.form_method = 'POST'
##Many settings here which **i don't want to rewrite in 10 child classes**
class Meta:
model = Event
exclude = something...
widgets = some settings here also.
And this child ModelForm:
class UpgradedEvent(Event):
def __init__(self, *args, **kwargs):
super(UpgradedEvent,self).__init__(*args,**kwargs)
class Meta(Event.Meta):
model = UpgradedEvent
UpgradedEvent is a child of Event model but has some extra fields.
How can i inherit all the settings from the Event FORM into UpgradedEvent FORM?
When running the above code, it renders the Event form. Is there a way to inherit only the settings inside __init__ ?
EDIT
Check out the answer, it works great but keep in mind:
you need to create another instance of FormHelper in your child class, otherwise it won't work. So child class should look something like:
class UpgradedEvent(Event):
def __init__(self, *args, **kwargs):
super(UpgradedEvent,self).__init__(*args,**kwargs)
self.helper = FormHelper()
class Meta(Event.Meta):
model = UpgradedEvent
You can obtain the fields the Meta above, and extend the lists, etc.:
class UpgradedEventForm(EventForm):
def __init__(self, *args, **kwargs):
super(UpgradedEventForm,self).__init__(*args,**kwargs)
# some extra settings
# ...
# for example
self.fields['extra_field'].initial = 'initial value of extra field'
class Meta(EventForm.Meta):
model = UpgradedEvent
exclude = EventForm.Meta.exclude + ['extra_exclude1', 'extra_exclude2']
fields = EventForm.Meta.fields + ['extra_field']
So by using inheritance, we can add extra procedures to the __init__ function by performing some extra actions after the super(UpgradedEventForm, self) call, and wwe can access the attributes of our parent, and extend these.
Note that you better name your forms with a Form suffix, since now your models clash with your forms. As a result, your Form seems to have as model a reference to the Form itself. By using proper "nomenclature", you avoid a lot of mistakes.
Create FormWithSettings which will hold common settings for you form classes and inherit it
class FormWithSettings(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(FormWithSettings, self).__init__(*args, **kwargs)
##Here make some changes such as:
self.helper = FormHelper()
self.helper.form_method = 'POST'
##Many settings here which **i don't want to rewrite in 10 child classes**
class Meta:
exclude = something...
widgets = some settings here also.
class EventForm(FormWithSettings):
def __init__(self, *args, **kwargs):
super(EventForm, self).__init__(*args,**kwargs)
class Meta(FormWithSettings.Meta):
model = Event
class UpgradedEventForm(FormWithSettings):
def __init__(self, *args, **kwargs):
super(UpgradedEventForm, self).__init__(*args,**kwargs)
class Meta(FormWithSettings.Meta):
model = UpgradedEvent
I am creating my form in Form.py like this:
class pdftabelModelForm(forms.ModelForm):
class Meta:
model = pdftabel_tool_
fields = ['apn', 'owner_name']
apn = forms.ModelChoiceField(queryset= Field.objects.values_list('name', flat=True), empty_label="(Choose field)")
owner_name = forms.ModelChoiceField(queryset= Field.objects.values_list('name', flat=True), empty_label="(Choose field)")
But due to some reasons like 'self' is not available in form.py. I can only access it in views.py. So I want to make it like
class FieldForm(ModelForm):
class Meta:
model = pdftabel_tool_
fields = (
'apn',
'owner_name',)
How can I make these fields as dropdown like I did in my forms.py?
Why are you set on doing it in views.py? forms.py is the appropriate place to do this.
Instead of redefining your fields, you should use the form's __init__ method to override the querysets for your fields, like so:
class pdftabelModelForm(forms.ModelForm):
class Meta:
model = pdftabel_tool_
fields = ['apn', 'owner_name']
def __init__(self, *args, **kwargs):
super(pdftabelModelForm, self).__init__(*args, **kwargs)
self.fields['apn'].queryset = X
self.fields['owner_name'].queryset = X
EDIT: if you need to pass extra parameters to your form, update the init method to this:
def __init__(self, *args, **kwargs):
self.layer_id = self.kwargs.pop('layer_id')
super(pdftabelModelForm, self).__init__(*args, **kwargs)
self.fields['apn'].queryset = X
self.fields['owner_name'].queryset = X
And when you initialize your form from views.py, pass the parameter:
form = pdftableModelForm(layer_id=X)
Folks,
I need to implement a form that may vary a little depending on a variable. My class that subclasses ModelForms looks like this
class ConstantVwModelForm(forms.ModelForm):
#couple attributes
def __init__(self, hasData, *args, **kwargs):
class Meta:
fields = ('xx', 'yy' ..)
I am looking for the very best way to access the variable hasData from the inner class Meta, it would be like
class ConstantVwModelForm(forms.ModelForm):
#couple attributes
def __init__(self, hasData, *args, **kwargs):
class Meta:
if hasData:
fields = ('xx', 'yy', ..)
else:
fields = ('hh', ..)
Any help is highly appreciated
You shouldn't do that and there's no way to achieve this. You can delete field on the fly in your __init__ function explicitly:
class ConstantVwModelForm(forms.ModelForm):
#couple attributes
def __init__(self, hasData, *args, **kwargs):
if hasData:
del self.fields['hh']
else:
del self.fields['xx']
del self.fields['yy']
class Meta:
model = ConstantVwModel
I have a custom model fields, that can have 'chain' argument.
from django.db import models
class ChainField(object):
def __init__(self, *args, **kwargs):
chain = kwargs.get('chain', False)
if chain:
self.chain = chain
del kwargs['chain']
super(self.__class__.__mro__[2], self).__init__(*args, **kwargs)
class DateTimeField(ChainField, models.DateTimeField):
pass
And now the question: how I can automatically pass 'chain' argument of model field to widget class when initializing ModelForm? I neen that in html it become 'class="chainxxx"' attribute of form field.
Override __init__ of the ModelForm like this:
class MyClass(ModelForm):
def __init__(self, *args, **kwargs):
super(MyClass, self).__init__(*args, **kwargs)
chain_value = self.fields['name_of_the_field'].chain
self.fields['name_of_the_field'].widget = CustomWidget(chain=chain_value)