我想根據 {% url %} 標簽中傳遞的 url 引數在 django createView 類中預填充(初始)某個表單欄位。我不知道如何在 createView 類的 get_initial(self) 方法中選擇傳遞的 url 引數。當我對某些值進行硬編碼時,它就起作用了。
html是這樣的:
{% for object in model.objects_set.all %}
{% subobject in objectmodel.subobjects_set.all%}
<a href="{% url 'url_name' object.id %}">Create SubObject</a>
{% endfor %}
{% endfor %}
而 views.py 就是這樣(我錯過了 ??? 部分):
class SubObjectCreateView(generic.CreateView):
model = SubObject
...
def get_initial(self):
return {'object': ???}
urls.py 就像:
path('subobject/<int:something>', views.SubObjectCreateView.as_view(), name='url_name')
uj5u.com熱心網友回復:
您可以訪問 url 引數
print(self.kwargs)
所以,我建議你只列印 self.kwargs 看看你有什么。
在那之后,你可以像這樣使用那個 kwargs
class SubObjectCreateView(generic.CreateView):
model = SubObject
...
def get_initial(self):
my_param = self.kwargs["something"]
return {'object': my_param}
uj5u.com熱心網友回復:
可以通過kwargs屬性訪問 url 引數,因此您可以撰寫:
class SubObjectCreateView(generic.CreateView):
model = SubObject
...
def get_initial(self):
return {'object': self.kwargs['something']} # Replace 'something' with the name of the url parameter
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/358920.html
上一篇:如何將std::array傳遞給可以接受std::vector的函式模板
下一篇:如何檢查變數是否可以寫入流
