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

醉酒当歌 提交于 2019-12-06 19:47:26

问题


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>

回答1:


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 }}


来源:https://stackoverflow.com/questions/18022792/django-managementform-data-is-missing-or-has-been-tampered-with-when-saving-mo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!