Django - unique_together选项,在表单中使用覆盖保存方法

时间:2013-02-11 16:03:05

标签: django django-models django-forms

当用户在表单中保存数据而不是使用django admin时,我想使用unique_together选项。

models.py:

from django.db import models
from django.contrib.auth.models import User

class ezApp(models.Model):
    name = models.SlugField(max_length=50, unique=True )
    date_created = models.DateTimeField('date created', auto_now_add=True)
    date_updated = models.DateTimeField('date updated', auto_now=True)
    created_by = models.ForeignKey(User)
    in_use = models.BooleanField()

    class Meta:
        unique_together = (('name', 'created_by'),)

forms.py

from django.forms import ModelForm
from django.forms.models import BaseModelFormSet
from ezApp.models import *

class BaseEzAppFormSet(BaseModelFormSet):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(BaseEzAppFormSet, self).__init__(*args, **kwargs)

    def save_new(self, form, commit=True):
        obj = form.save(commit=False)
        obj.created_by = self.user
        if commit:
             obj.save()
        return obj

views.py:

from django.shortcuts import *
from ezApp.models import *
from django.forms.models import modelformset_factory
from django.http import HttpResponseServerError
from ezApp.forms import *

def createEzAppInstance(request):
    if request.method == 'POST':
            ezAppFormSet = modelformset_factory(ezApp, extra=1, fields=('name'), formset=BaseEzAppFormSet)
            formset = ezAppFormSet(request.POST, request.FILES, user=request.user)
            if formset.is_valid():
                formset.save()

        return render_to_response("ezApp/manage_new_ezApp.html", {'formset': formset, 'title': "New App"}, context_instance=RequestContext(request))
else:
    error_msg = u"You are not logged in"
    return HttpResponseServerError(error_msg)

在模型的Meta中使用unique_together,验证仅在django admin中有效,但在我使用表单保存新数据时则不行。

1 个答案:

答案 0 :(得分:0)

正如msc指出的那样,你需要覆盖保存方法,而不是自己编写。

def save(self, *args, **kwargs):
    obj = super(BaseEzAppFormSet, self).save(form, *args, commit=False, **kwargs)
    obj.created_by = self.user
    obj.save()
    return obj

您的视图中似乎没有调用save_new()方法。