Reputation: 699
I am struggeling with passing an "external" parameter to my custom clean method.
Except of the identifier, I pass everything using the form. The identifier comes from the URL. I need to use the identifier in addition to the form stuff.
Here is my code:
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
VIEW:
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)
...
So I am missing the part where I can add the identifier to the clean method.
Thanks for the help in advanced!
Upvotes: 0
Views: 4637
Reputation: 599610
You need to pass it in from the view when you instantiate the form. The usual pattern is like this:
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...
and in the view:
if request.method == "POST":
entryForm = EntryForm(data=request.POST, identifier=identifier)
Upvotes: 11