0

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

除了标识符,我使用表单传递所有内容。标识符来自 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 方法的部分。

感谢您在高级的帮助!

4

1 回答 1

11

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

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)
于 2013-10-02T18:53:00.877 回答