django表格未按预期更新

时间:2017-07-11 03:33:00

标签: django django-models django-forms

这是我的模特:

class Browser(models.Model):
    profile_name = models.CharField(max_length=400)
    browser_type = (
        ('fr', 'Firefox'),
        ('ch', 'Chrome'),
        ('op', 'Opera'),
        ('ot', 'Other'),
    )
    browser_name = models.CharField(choices=browser_type, max_length=2)
    device_name = models.CharField(max_length=400)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)


class Bookmark(models.Model):
    browser = models.ForeignKey(Browser, on_delete=models.CASCADE, null=True, blank=True)
    title = models.TextField()
    url = models.TextField()
    iv = models.TextField()
    salt = models.TextField()
    iteration = models.IntegerField(default=1500)
    tags = TaggableManager()

我只想更新某些字段,所以这里是modelform

class BookmarkFormEdit(ModelForm):
    class Meta:
        model = Browser
        exclude = ('tags', 'browser_name', 'device_name', 'profile_name')

但我的问题是,值未按预期更新。以下是观点:

def bookmark_edit(request, pk=None):
    if request.method == 'POST':
        bookmark = Bookmark.objects.get(pk=pk)
        frm = BookmarkFormEdit(request.POST, instance=bookmark)
        print(request.POST.get('iteration')) // printing correct value from front-end
        if frm.is_valid():
            x = frm.save()
            print(x.iteration) // not saving the new value !
            return JsonResponse({'status': 'created'})
        else:
            return JsonResponse({'error': frm.errors})
    return render(request, 'bookmark_edit.html', {'pk': pk})

1 个答案:

答案 0 :(得分:1)

表单中的model定义不正确。您应该使用Bookmark模型而不是Browser

class BookmarkFormEdit(ModelForm):
    class Meta:
        model = Bookmark

您可能需要为此模型定义要包含/排除的字段。