There are two nested formsets and they are related to each other. When I increase the extra field in the second formset, I get the error column cannot be null. I have no problem saving both forms as one.
Here is my error :
Here is my forms :
class UserTaskForm(forms.ModelForm):
class Meta:
model = UserTask
fields = ['user_id','task_types_id','store_house_id','description']
class TaskSourcesForm(forms.ModelForm):
class Meta:
model = TaskSources
fields = ['product_id', 'product_amount']
TaskSourcesFormSet = modelformset_factory(
TaskSources,
fields=('product_id', 'product_amount',),
extra=2,
)
UserTaskFormFormSet = modelformset_factory(
UserTask,
fields=('user_id','task_types_id','store_house_id','description',),
extra=1,
)
here is my views :
@login_required(login_url="login")
def addUserTask(request):
user_task_form = UserTaskFormFormSet(queryset=UserTask.objects.none(),initial=[{'user_id': request.user}])
formset = TaskSourcesFormSet(queryset=TaskSources.objects.none())
if request.method == 'POST':
user_task_form = UserTaskFormFormSet(request.POST)
formset = TaskSourcesFormSet(request.POST)
if user_task_form.is_valid():
for form in user_task_form:
user_task = form.save(commit=False)
user_task.author = request.user
user_task.save()
if formset.is_valid():
for form_data in formset:
task_sources = form_data.save(commit=False)
task_sources.user_task_id = UserTask(id = user_task.id)
task_sources.save()
messages.success(request,"Task added successfully!")
return redirect(".")
context = {
"user_task_form" : user_task_form,
"formset" : formset,
}
return render(request,"user/addtask.html",context)
How to save two model formsets together(relates to each other) in one view? what is the wrong part when i do it?
CodePudding user response:
I suspect the problem comes from empty fields in your formsets forms. You can avoid empty forms with:
for form in user_task_form:
if form.has_changed():
user_task = form.save(commit=False)