How to pass initial parameter to django's ModelForm instance?

前端 未结 4 1661
伪装坚强ぢ
伪装坚强ぢ 2021-01-31 05:01

The particular case I have is like this:

I have a Transaction model, with fields: from, to (both are ForeignKeys to auth.Use

4条回答
  •  自闭症患者
    2021-01-31 05:28

    Use the following method (hopefully it's clear enough):

    class BackupForm(ModelForm):
        """Form for adding and editing backups."""
    
        def __init__(self, *args, **kwargs):
            systemid = kwargs.pop('systemid')
            super(BackupForm, self).__init__(*args, **kwargs)
            self.fields['units'] = forms.ModelMultipleChoiceField(
                    required=False,
                    queryset=Unit.objects.filter(system__id=systemid),
                    widget=forms.SelectMultiple(attrs={'title': _("Add unit")}))
    
        class Meta:
            model = Backup
            exclude = ('system',)
    

    Create forms like this:

    form_backup = BackupForm(request.POST,
                             instance=Backup,
                             systemid=system.id)
    form_backup = BackupForm(initial=form_backup_defaults,
                             systemid=system.id)
    

    Hope that helps! Let me know if you need me to explain more in depth.

提交回复
热议问题