Django 'ManagementForm data is missing or has been tampered with' when saving modelForms with foreign key link

StackOverflow https://stackoverflow.com/questions/18022792

  •  21-06-2022
  •  | 
  •  

Question

I am rather new to Django so this may be an easy question. I have 2 modelForms where there is a ForeignKey to another. My main goal is to save Indicators with a link to Disease (FK), such that for a particular disease, you can have multiple indicators.

With the code below, I get an error when I hit submit that says 'ManagementForm data is missing or has been tampered with'. Also, the code in views.py does not seem to be validating at the 3rd 'if' statement where there is a return HttpResponseRedirect. However, when I check my database, the values from the form have been written. Any ideas on why the error has been raised? and how to fix it?

My code is below:

models.py

#Table for Disease
class Disease(models.Model):
    disease = models.CharField(max_length=300)

#Tables for Indicators
class Indicator(models.Model):
    relevantdisease = models.ForeignKey(Disease)       
    indicator = models.CharField(max_length=300)

forms.py

class DiseaseForm(forms.ModelForm):
    class Meta:
      model = Disease

class IndicatorForm(forms.ModelForm):
    class Meta:
      model = Indicator

DiseaseFormSet = inlineformset_factory(Disease, 
    Indicator,
    can_delete=False,
    form=DiseaseForm)

views.py

def drui(request):

    if request.method == "POST":

       indicatorForm  = IndicatorForm(request.POST)

       if indicatorForm.is_valid():
          new_indicator = indicatorForm.save()
          diseaseInlineFormSet = DiseaseFormSet(request.POST, request.FILES,   instance=new_indicator)

          if diseaseInlineFormSet.is_valid():
             diseaseInlineFormset.save()
             return HttpResponseRedirect('some_url.html')

    else:
       indicatorForm = IndicatorForm()
       diseaseInlineFormSet = DiseaseFormSet()

    return render_to_response("drui.html", {'indicatorForm': indicatorForm,  'diseaseInlineFormSet': diseaseInlineFormSet},context_instance=RequestContext(request))   

template.html

 <form class="disease_form" action="{% url drui %}" method="post">{% csrf_token %}
  {{ indicatorForm.as_table }}
 <input type="submit" name="submit" value="Submit" class="button">
 </form>
Was it helpful?

Solution

You have neither diseaseFormSet nor diseaseFormSet's management form in your template, yet you try to instantiate the formset. Formsets require the hidden management form which tells django how many forms are in the set.

Insert this into your HTML

{{ diseaseFormSet.as_table }} 
{{ diseaseFormSet.management_form }}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top