如何将数据传递给Django中的clean方法

时间:2013-10-02 18:41:55

标签: django django-models django-forms

我正在将“外部”参数传递给我的自定义清理方法。

除了标识符,我使用表单传递所有内容。标识符来自URL。 除了表单之外,我还需要使用标识符。

这是我的代码:

class Entry(models.Model):
    identifier = models.ForeignKey(Offer)
    name = models.CharField(max_length=64)
    description = models.TextField()


class EntryForm(ModelForm):
    class Meta:
        model = Entry

    def clean(self):
        try:
            Entry.objects.get(
                identifier=THIS IS WHAT I NEED TO FILL,
                description=self.cleaned_data['description'],
                name=self.cleaned_data['name'])
        raise forms.ValidationError(_(u'We already have an entry with the same credentials!'))
    except Entry.DoesNotExist:
        pass
    return self.cleaned_data

查看:

def addEntry(request, identifier):

    entry = get_object_or_404(Entry, pk=identifier)

    if request.method == "POST":
        entryForm = EntryForm(data=request.POST)
        if entryForm.is_valid():
            entry = entryForm.save(commit=False)
            entry.identifier = identifier
            entry.save()
        else:
            entryForm = EntryForm(data=request.POST)
...

所以我错过了可以将标识符添加到clean方法的部分。

感谢先进的帮助!

1 个答案:

答案 0 :(得分:8)

实例化表单时,需要从视图中传入它。通常的模式是这样的:

class EntryForm(ModelForm):
    def __init__(self, *args, **kwargs):
        self.identifier = kwargs.pop('identifier', None)
        super(EntryForm, self).__init__(*args, **kwargs)

    def clean(self):
        try:
            Entry.objects.get(
                identifier=self.identifier...

并在视图中:

if request.method == "POST":
    entryForm = EntryForm(data=request.POST, identifier=identifier)