21👍
✅
I don’t think you want to use a ModelForm here. It will never be valid without some hackery, since you won’t have found or created the dog object before calling is_valid()
.
Instead, I’d just use a regular form, and then override the save method of DogRequest to find or create the dog.
Update: Responding to the followup question in the comment, I haven’t tested this, but something like it should work.
class DogRequestForm(forms.Form):
id = forms.IntegerField(required=False, widget=forms.HiddenInput())
color = forms.ModelChoiceField(queryset=Color.objects.all())
speed = forms.ModelChoiceField(queryset=Speed.objects.all())
and then when you create an instance of this form for your edit view you need to instantiate it with something like this:
data = {
'id': dog_request_id,
'color': dog_color,
'speed': dog_speed,
}
form = DogRequestForm(data)
where you populate the current dog_request_id
, dog_color
and dog_speed
from your existing DogRequest
object.
Source:stackexchange.com