Reputation: 108
Let's say I have a model that holds several different charfields.
models.py
class Items(models.Model):
languages = models.Charfield(...)
title = models.Charfield(...)
audio = models.Charfield(...)
The data is saved within each with a delimiter ("||"). I would like to create a form that splits the data then prefills the value with the saved data.
Theoretically:
{'languages': 'English||French||German'}
{'title': '1.1||Red Balloon||Banana'}
{'audio': 'yes||no||yes'}
Would be split to:
{'languages': ['English', 'French', 'German']}
{'title': ['1.1', 'Red Balloon', 'Banana']}
{'audio': ['yes', 'no', 'yes']}
Then each value would auto-populate the value field. Eventually displaying as:
<tr>
<td><input type="text" name="languages[]" value="English"></td>
<td><input type="text" name="title[]" value="1.1"></td>
<td><input type="text" name="audio[]" value="yes"></td>
</tr>
<tr>
<td><input type="text" name="languages[]" value="French"></td>
<td><input type="text" name="title[]" value="Red Balloon"></td>
<td><input type="text" name="audio[]" value="no"></td>
</tr>
...
As each row would have a different amount of 'languages', for example, what is the preferred way to create this type of form. I am using Django 1.11. First question posted, so if I have missed something within this post, would you kindly let me know? I also have searched for information related to this, however I have yet to find a solution. Thanks!
--Edited to reflect that charFields hold the user input. In this example, the inputs 'languages' and 'title' are not consistent enough to use them as multiple-choice fields.
Upvotes: 1
Views: 67
Reputation: 996
Take a look at Django Formsets.
In your case you'd want to first define some sort of ItemForm
:
from django import forms
class ItemForm(forms.Form):
language = forms.CharField()
setting = forms.CharField()
audio = forms.CharField()
In your views.py, you can then define a formset with the initial form data:
from django.forms import formset_factory
from myapp.forms import ItemForm
item = Items.objects.all()[0] # replace this with your actual query
languages = item.languages.split('||')
settings = item.settings.split('||')
audios = item.audio.split('||')
ItemFormSet = formset_factory(ItemForm, extra=len(languages))
formset = ItemFormSet(initial=[
{'language': language,
'setting': setting,
'audio':audio,
} for language, setting, audio in zip(languages, settings, audios)])
Upvotes: 1