我有2个型号:
class Case(models.Model):
Priority = (
('Blocker', 'Blocker'),
('High', 'High'),
('Medium', 'Medium'),
('Low', 'Low'),
)
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=200)
image = models.URLField(blank=True)
requirements = models.URLField(blank=True)
priority = models.CharField(max_length=10, choices=Priority)
description = models.CharField(max_length=200)
step = models.TextField()
modified = models.DateTimeField(editable=False)
user = models.ForeignKey(User, editable=False)
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.modified = datetime.datetime.today()
super(Case, self).save(*args, **kwargs)
def __unicode__(self):
return self.name
return self.description
class Suite (models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=200)
features = models.TextField()
modified = models.DateTimeField(editable=False, null=True)
cases = models.ManyToManyField(Case, null=True)
user = models.ForeignKey(User, editable=False)
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.modified = datetime.datetime.today()
super(Suite, self).save(*args, **kwargs)
def __unicode__(self):
return self.name
return self.description
当我想创建套件或案例时,它可以正常工作:
def addCase(request):
c = {}
c.update(csrf(request))
user = auth.get_user(request)
if request.method == 'POST':
form = AddCase(data = request.POST)
if form.is_valid():
form.save()
else:
form = AddCase()
return render_to_response('1.html', {
'form': form,
'js': c.items(),
'host' : request.get_host(),
'user' : user
})
def addSuite(request):
c = {}
c.update(csrf(request))
user = auth.get_user(request)
if request.method == 'POST': # If the form has been submitted...
form = AddSuite(data = request.POST)
if form.is_valid():
form.save()
else:
form = AddSuite()
return render_to_response('2.html', {
'form': form,
'js': c.items(),
'host' : request.get_host(),
'user' : user
})
但是当我想编辑这些时,我会使用下一个视图:
def editSuite (request, suite_id):
suite = Suite.objects.get(id=suite_id)
name = suite.name
features = suite.features
cases = suite.cases
c = {}
c.update(csrf(request))
if request.method == 'POST': # If the form has been submitted...
form = EditSuite(data = request.POST)
if form.is_valid():
suite = Suite(
id = suite_id,
name = form.cleaned_data['name'],
features = form.cleaned_data['features'],
cases = request.POST.getlist('cases')
)
suite.save()
# form.save()
else:
form = EditSuite(instance = suite)
return render_to_response('editsuite.html', {
'form': form,
'suite': suite,
'cases' : request.POST.getlist('cases')
})
所以,我需要知道如何保存已编辑的套件。添加工作正常,在管理面板中工作正常,但当我尝试编辑套件时,我收到很多不同的错误。关键时刻 - 管理员运作良好。 谢谢
答案 0 :(得分:0)
好的,我的不好。要编辑m2m模型表单,您应该使用类似这样的
form = EditSuite(request.POST, instance = suite)
if form.is_valid():
obj = form.save(commit=False)
obj.user = request.user
cases = request.POST.getlist('cases')
obj.save()
form.save_m2m()