Django - How to make a form for a model's foreign keys?

后端 未结 1 1983
借酒劲吻你
借酒劲吻你 2021-02-05 13:29

Here\'s what I\'m trying to do. I\'m wondering if someone can suggest a good approach:

models.py:

class Color(models.Model):
    name = models.CharField         


        
1条回答
  •  情书的邮戳
    2021-02-05 14:13

    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.

    0 讨论(0)
提交回复
热议问题