I have two forms:
class FarmerForm(forms.ModelForm):
class Meta:
model = Farmer
fields = ‘all’
widgets = {
‘farmerName’: forms.TextInput(attrs={‘class’: ‘form-control’}),
‘dob’: forms.DateInput(attrs={‘class’: ‘form-control’, ‘type’: ‘date’}),
‘gender’: forms.Select(attrs={‘class’: ‘form-control’}),
‘phone’: forms.TextInput(attrs={‘class’: ‘form-control’, ‘type’: ‘tel’}),
‘email’: forms.EmailInput(attrs={‘class’: ‘form-control’}),
}
class FarmForm(forms.ModelForm):
farmer = forms.ModelChoiceField(queryset=Farmer.objects.all(), widget=forms.HiddenInput())
class Meta:
model = Farm
fields = '__all__'
widgets = {
'farmName': forms.TextInput(attrs={'class': 'form-control'}),
'farmSize': forms.NumberInput(attrs={'class': 'form-control', 'type': 'number'}),
'landUnit': forms.Select(attrs={'class': 'form-control'}),
'methodOfAcquisition': forms.Select(attrs={'class': 'form-control'}),
}
I have a view for saving new instances of FarmerFom and FarmForm and storing them in respective Farmer and Farm tables in the database. These forms are linked and neither one can be submitted without the other. However, neither the FarmerForm nor the FarmForm are saved when I click save button.
Could someone help me identify the issue in my view?
def farm_setup_farmer_view(request):
if request.method == 'POST':
farmer_form = FarmerForm(request.POST)
farm_form = FarmForm(request.POST)
if farmer_form.is_valid() and farm_form.is_valid():
with transaction.atomic():
farmer_instance = farmer_form.save()
farm_instance = farm_form.save(commit=False)
farm_instance.farmer = farmer_instance
farm_instance.save()
# Optionally, you can add a success message using Django messages framework
# messages.success(request, 'Farmer details saved successfully.')
return redirect('list_farmers_view') # Redirect to the 'farm_setup_farm' URL
else:
farmer_form = FarmerForm()
farm_form = FarmForm()
print(f"FarmerForm errors: {farmer_form.errors}")
print(f"FarmForm errors: {farm_form.errors}")
return render(request, 'farm_setup_farmer.html', {'farmer_form': farmer_form, 'farm_form': farm_form})
This is