【问题标题】:How to pass initial data from url to form foreign key field?如何从 url 传递初始数据以形成外键字段?
【发布时间】:2014-08-02 16:35:41
【问题描述】:

我正在使用 ModelForm。我知道如何传递初始数据,例如: “domain.com/?field=value” 如果字段是 CharField 或类似的想法,但是如果字段是 ForeignKey,如何传递初始数据? "domain.com/?field__foreign=value" ;) 不起作用。

【问题讨论】:

    标签: django django-models django-forms


    【解决方案1】:

    您在 URL 中 ? 后面的内容不是字段,它们是可选参数。然后,您可以在您的视图中使用它们,并根据需要将它们作为字段进行威胁。

    例如:domain.com/?field=myValue

    def yourView(request, field=""): #The field has an ampty string as default if not provided in the URL
      #Now we will retrieve the objects where the field "yourField" has the value given in the url (or empty string if none)
      #In the case of this example, field = myValue
      yourObjects = yourModel.filter(yourField = field)
      #Do anything else you want to do in your view
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-12
      • 2018-03-22
      • 2020-04-19
      • 2020-10-03
      • 2014-09-02
      • 1970-01-01
      • 1970-01-01
      • 2016-05-02
      相关资源
      最近更新 更多