Free-form input for ForeignKey Field on a Django ModelForm

后端 未结 4 471
夕颜
夕颜 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:30

    There are a few problems here.

    Firstly, you have defined a field, not a widget, so you can't use it in the widgets dictionary. You'll need to override the field declaration at the top level of the form.

    Secondly get_or_create returns two values: the object retrieved or created, and a boolean to show whether or not it was created. You really just want to return the first of those values from your to_python method.

    I'm not sure if either of those caused your actual error though. You need to post the actual traceback for us to be sure.

提交回复
热议问题