How to edit m2m in Django via ModelForm

2019-09-01 04:09发布

I have 2 models:

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

When I want to create suite or case it works fine:

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

But when I want to edit these, I use next views:

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

So, I need to know how to save edited suite. Adding works fine, in admin panel works ok, but when I tried to edit suite, I receive a lot of different errors. The key moment - in admin works well. Thank you

1条回答
劳资没心,怎么记你
2楼-- · 2019-09-01 04:41

Ok, there was my bad. To edit m2m model forms you should use something like this

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()
查看更多
登录 后发表回答