Reputation: 309
I have looked at some examples but none of them have worked for me.
What i have is List of Locations and the user has the choice to add them to a group. First step is he gives the group a name. And then he can choose from the locations which are already in the database, to add them to the group name.
To put it simple i want to loop 3 form elements for each location, and attach initial values for each location, so it can be stored inside a group.
This is what i want to see:
<form>
<input type="text" label="group_name">
First Location
<input type="hidden" value="street_name">
<input type="hidden" value="location_name">
<input type="checkbutton">
Second location
<input type="hidden" value="street_name2">
<input type="hidden" value="location_name2">
<input type="checkbutton">
and so on
<input type="submit" value="Create this Group">
</form>
I have tried it like this:
Froms.py is currently missing the check input for True and False. FORMS.py:
class GroupAddForm(forms.ModelForm):
groupname = forms.CharField(label='',widget=forms.HiddenInput(attrs={'rows': '4', 'class': 'form-control'}))
page_name = forms.CharField(label='' ,widget=forms.HiddenInput(attrs={'rows': '4', 'class': 'form-control'}))
page_street = forms.CharField(label='' ,widget=forms.HiddenInput(attrs={'rows': '4', 'class': 'form-control'}))
class Meta:
model = GroupManagement
fields = ['groupname', 'page_name', 'page_street']
VIEW:
def page_groups(request):
email =request.user.email
locationdata = LocationData.objects.filter(email=email).values_list(
'id',
'name',
'street',
'postal_code',
'tel',
'website',
'description',
'fb_page_id'
)
form = []
for items in locationdata:
name = items[1]
form = GroupAddForm(request.POST or None, initial={"page_name": name})
print(form)
context = {
'locationdata': locationdata,
'form': form,
}
return render(request, 'page_groups.html', context)
OR in the Template:
<form method="POST" action=""> {% csrf_token %}
{% for items in locationdata %}
{{items.1}}
{{form.fields.page_name.value|default:items.1}}
{{form}}
{% endfor %}
</form>
Inside the View only the last element is attached to the form. The initial Value inside the Template doesn't work at all.
Upvotes: 0
Views: 57
Reputation: 309
Fixed it myself.
for items in locationdata:
name = items[1]
form = GroupAddForm(request.POST or None, initial={"page_name": name})
forms.append(form)
<form method="POST" action=""> {% csrf_token %}
{% for items in forms %}
{{items}}
{% endfor %}
</form>
Upvotes: 1