![](/img/trans.png)
[英]Modelformset in django generic CreateView and UpdateView
[英]Django UpdateView generic class
如何在通用視圖類中訪問用戶傳遞的對象?
在模板中,當用戶單擊鏈接時:
<td><a href="{% url 'update_peon' pk=item.pk %}"><button class="btn btn-warning">Edit</button></a></td>
轉到urls.py:
url(r'^update_peon/(?P<pk>\d+)$', views.UpdatePeon.as_view(), name='update_peon'),
和我的看法:
class UpdatePeon(generic.UpdateView):
login_required = True
template_name = 'appform/Peons/peon_form.html'
model = Person
form_class = PersonForm
success_url = reverse_lazy('view_peons')
我想訪問item.pk
內部的item.attr1
或至少item.pk
,以便可以相應地更改模型和形式,例如:
class UpdatePeon(generic.UpdateView):
login_required = True
template_name = 'appform/Peons/peon_form.html'
if item['attr1'] == "Attribute1":
model = model1
form = model1Form
else:
etc
success_url = reverse_lazy('view_peons')
我知道如何在基於普通函數的類中做到這一點,即使我從頭開始重寫基於類的視圖,但我也不想這樣做。
class UpdatePeon(generic.UpdateView):
if item['attr1'] == "Attribute1":
model = model1
form = model1Form
else:
...
您不能像這樣將代碼放入類主體中。 它會在模塊加載時運行,然后才能訪問request
。
您應該覆蓋特定的方法。 例如,您可以重寫get_form_class
來更改視圖使用的表單類。 在視圖內部,您可以訪問使用self.object
更新的對象。
class UpdatePeon(generic.UpdateView):
def get_form_class(self):
if self.object.pk == 1:
return MyForm
else:
return OtherForm
您可能會發現ccbv網站對於探索更新視圖方法很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.