I have the following models:
# Group for Key/Value pairs
class Group(models.Model):
name = models.TextField(unique=True)
def __unicode__(self):
return self.name
class Meta:
verbose_name = 'Group'
verbose_name_plural = 'Groups'
# Key is the key/name for a Value
class Key(models.Model):
name = models.TextField(unique=True)
def __unicode__(self):
return self.name
class Meta:
verbose_name = 'Key'
verbose_name_plural = 'Keys'
# Value is the value/content of a key
class Value(models.Model):
value = models.TextField()
def __unicode__(self):
return '%s' % self.value
class Meta:
verbose_name = 'Value'
verbose_name_plural = 'Values'
class Key_Value(models.Model):
group = models.ForeignKey(Group)
key = models.ForeignKey(Key)
value = models.ForeignKey(Value)
def __unicode__(self):
return '%s = %s' % (self.key.name, self.value.value)
class Meta:
verbose_name = 'Key/Value Paar'
verbose_name_plural = 'Key/Value Paare'
Now I pass the form to the template:
def exampleview(request):
key_value_form = Key_Value_Form(request.POST)
return render_to_response(
'edit.html', {
'key_value_form': key_value_form,
})
Now lets look at possible data
KEY/VALUE PARIRS:
key = TEST 1
value = TEST 1
group = TESTGROUP 1
key = TEST 2
value = TEST 2
group = TESTGROUP 2
Now I changed the default widgets for the Key/Value Table entries to select widgets.
Here’s what I want to do:
SELECT GROUP [+] [-]
--> [Now choose Key/Value pair belonging to group] [+] [-]
at the start you always get two selects one for the group and one for the key/value pair.
if you press the + at the GROUP a new group select button should appear along with a KEY/Value Pair select, if you press the + at the Key/Value select a new key/value select box should appear.
I have two problems:
ONE: I don’t know how the check in the template should look like and
TWO: How I can implement those + – Buttons
Any Help is appreciated. It would be cool if this would be possible without javascript but I don’t have very high hopes in that direction
You need to build the form on the fly. Suppose you had a definition of a group form built in a dictionary from a view in your view handler (containing group model foreign keys and number of actual keys in them):
Note that you can (and should) rewrite a class
Key_Value_Formto inherit from forms.BaseForm and put the make_groupkeys_form(descriptor) code in its__init__(request, descriptor)member. You will also need to do write your ownis_valid()to enumerate through select fields and make sure the choices are correct when the user submits the form and overrideclean()to attempt to validate individual user’s choices.Finally, consider going through this dynamic forms read. It will guide you step by step in how to create dynamic forms in django.