我有以下问题。一旦我尝试保存已编辑的对象(详情如下),我就会收到错误消息:
MultiValueDictKeyError at /apps/edit/1/
"Key 'application2server_set-0-id' not found in <QueryDict: {u'application2server_set-MAX_NUM_FORMS': [u''], u'name': [u'application1'], u'repository': [u'1'], u'application2server_set-INITIAL_FORMS': [u'2'], u'application2server_set-TOTAL_FORMS': [u'5'], u'csrfmiddlewaretoken': [u'bmEPdLCloNHKR0qUmwdhdmQ4aDKHV2CT'], u'servers': [u'1', u'2']}>"
以下是使用的模型和形式:
class Server(models.Model):
host = models.CharField(max_length=100)
user = models.CharField(max_length=20)
root_directory = models.CharField(max_length=200)
class Repository(models.Model):
host = models.CharField(max_length=100)
user = models.CharField(max_length=20)
class Application(models.Model):
name = models.CharField(max_length=100)
repository = models.ForeignKey(Repository)
servers = models.ManyToManyField(Server, through='Application2Server', null=True, blank=True)
class Application2Server(models.Model):
application = models.ForeignKey(Application)
server = models.ForeignKey(Server)
tag = models.CharField(max_length=100)
deployment_date = models.DateTimeField(auto_now=True, blank=True)
class ServerForm(ModelForm):
class Meta:
model = Server
class RepositoryForm(ModelForm):
class Meta:
model = Repository
class ApplicationForm(ModelForm):
class Meta:
model = Application
class Application2ServerForm(ModelForm):
class Meta:
model = Application2Server
exclude = ('application', 'server', 'tag')
用于保存日期的视图:
def app_edit(request, id):
application = get_object_or_404(Application, pk=id)
Application2ServerFormSet = inlineformset_factory(Application, Application2Server)
if request.method == 'POST':
form = ApplicationForm(request.POST, instance=application)
formset = Application2ServerFormSet(request.POST, instance=application)
if form.is_valid() and formset.is_valid():
saved_application = form.save()
formset.save()
return HttpResponseRedirect(reverse(
'proj.views.app_show',
args=(saved_application.pk,)
))
else:
form = ApplicationForm(instance=application)
formset = Application2ServerFormSet(instance=application)
return render(request, 'app_edit.html', {'form': form, 'formset': formset})
和模板来生成 HTML 和表单本身:
<h1>App edit view</h1>
{% extends "base.html" %}
{% block container %}
<form method="post">{% csrf_token %}
<table>
{{ formset.management_form }}
{{ form.as_table }}
<tr><th></th><td><input type="submit" value="Save changes" /></td></tr>
</table>
</form>
{% endblock %}
任何帮助都感激不尽!谢谢!