1

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

模型.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'),)

表格.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

视图.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 内部有效,但在我使用表单保存新数据时无效。

4

1 回答 1

0

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

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() 方法从未在您的视图中被调用过。

于 2013-02-11T17:03:27.197 回答