如何访问用户在通用 View 类中传递的对象?
在模板中,当用户单击链接时:
<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.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')
我知道如何在基于普通函数的类中执行此操作,或者即使我从头开始重写基于类的 View ,但我不想这样做。
最佳答案
class UpdatePeon(generic.UpdateView):
if item['attr1'] == "Attribute1":
model = model1
form = model1Form
else:
...
您不能像这样将代码放入类主体中。它在模块加载时运行,然后您才能访问请求
。
您应该重写特定的方法。例如,您可以覆盖 get_form_class
来更改 View 使用的表单类。在 View 内,您可以使用 self.object
访问正在更新的对象。
class UpdatePeon(generic.UpdateView):
def get_form_class(self):
if self.object.pk == 1:
return MyForm
else:
return OtherForm
您可能会发现 ccbv 网站对于探索 update view methods 很有用。 .
关于python - Django UpdateView 泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50504441/