我正在努力将“外部”参数传递给我的自定义清理方法。
除了标识符,我使用表单传递所有内容。标识符来自 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 方法的部分。
感谢您在高级的帮助!