22π
β
cd is a dictionary. Also, you might want to fetch the dictionary values from individual forms rather than the formset
if request.method == 'POST':
formset = MemberFormSet(request.POST)
if formset.is_valid():
for f in formset:
cd = f.cleaned_data
first_name = cd.get('first_name')
last_name = cd.get('last_name')
email = cd.get('email')
house = House.objects.get(id = id)
member = Member(first_name = first_name, last_name = last_name, email = email, house = house, created_on = timezone.now())
member.save()
return HttpResponseRedirect(reverse('houses:controlPanel'))
π€karthikr
0π
I think you should be using a model_formsetfactory, or even better, an inlineformset_factory. You are populating models from form data, which is what they are designed for. Get the dirty models from the formset, using commit=False, and add in your House relationship. Something like this:
MemberFormSet = model_formset_factory(Member, extra= members)
if request.method == POST:
formset = MemberFormSet(request.POST)
if formset.is_valid():
house = House.objects.get(id = id)
models = formset.save(commit=False)
for member in models:
member.house = house
member.save()
return render(<your data>)
else:
formset = MemberFormSet()
return render(<your data>)
Note your get() will also throw an exception if the House object doesnβt exist. Just a design consideration.
π€professorDante
- Django or Ruby on Rails
- How to get max value in django ORM
- How to deploy a WordPress site and Django site on the same domain?
Source:stackexchange.com