Free-form input for ForeignKey Field on a Django ModelForm

后端 未结 4 469
夕颜
夕颜 2021-02-03 09:52

I have two models related by a foreign key:

# models.py    
class TestSource(models.Model):
  name        = models.CharField(max_length=100)

class TestModel(mod         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-03 10:32

    Something like this should work:

    class TestForm(ModelForm):
      attribution = forms.CharField(max_length=100)
    
      def save(self, commit=True):
          attribution_name = self.cleaned_data['attribution']
          attribution = TestSource.objects.get_or_create(name=attribution_name)[0]  # returns (instance, )
          self.instance.attribution = attribution
    
          return super(TestForm, self).save(commit)
    
      class Meta:
        model=TestModel
        exclude = ('attribution')
    

提交回复
热议问题