Follow up question: creating and linking two new models at once
I am trying to create and handle form elements, not created in a model, to define if the user wants to create a second (other) model instance. So far adding the field works but when I try to handle the checkbox and create a model I have not found a way to access the variable. My assumption is I have to handle it in the model class save function?!
I was able to add a checkbox and show it (testing atm so some weird names and colors) with the following code:
forms.py:
class EntityModelForm(ContextModelForm):
addSomething = forms.BooleanField(
label = 'test',
widget = forms.CheckboxInput(
)
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["addSomething"] = forms.BooleanField()
self.fields["addSomething"].label = 'my fantastic label'
self.fields["addSomething"].help_text = 'my helptext for the fantastic label'
self.fields["addSomething"].required = False
class Meta:
model = Entity
fields = "__all__"
the init part based upon: this post
the template part:
{% load i18n %}
<hr>
<div class="data-element-group">
<label for="{{ form.addSomething.id_for_label }}">{{ form.addSomething.label }}</label>
{{ form.addSomething }}
<div class="errors">
{{ form.addSomething.errors }}
</div>
{{ form.addSomething.help_text }}
</div>
And the visual result (with some fantastic css):
(sass available on request )
when pressing save with the models.py code:
def save(self, *args, **kwargs):
if self.addSomething:
pass
resulting in
AttributeError at .....
object has no attribute 'addSomething'
logical because addSomething is only defined in the forms.py
and
do_it = self.form.addSomething
print('yes'+str(do_it) )
return super(Entity, self).save(*args, **kwargs)
resulting in:
AttributeError ..... object has no attribute 'form'`
logical and when using from .forms import *
it was even worse and did not compile.
Does anybody know how to get the variable and see if it is checked so I can handle it to create another (different) model instance