问题
How can I access the object passed by the user inside a generic view class?
In template, when the user clicks the link:
<td><a href="{% url 'update_peon' pk=item.pk %}"><button class="btn btn-warning">Edit</button></a></td>
this goes to urls.py:
url(r'^update_peon/(?P<pk>\d+)$', views.UpdatePeon.as_view(), name='update_peon'),
and my view:
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')
I would like to access the item.attr1
or at least item.pk
inside the class so I could change the model and form accordingly, something like:
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')
I know how to do it in a normal function based class or even if I rewrite a class based view from scratch but I don't want to do that.
回答1:
class UpdatePeon(generic.UpdateView):
if item['attr1'] == "Attribute1":
model = model1
form = model1Form
else:
...
You can't put code in the class body like this. It runs when the module is loaded, before you have access to the request
.
You should override a specific method. For example you can override get_form_class
to change the form class used by the view. Inside the view, you can access the object being updated with self.object
.
class UpdatePeon(generic.UpdateView):
def get_form_class(self):
if self.object.pk == 1:
return MyForm
else:
return OtherForm
You may find the ccbv website useful for exploring the update view methods.
来源:https://stackoverflow.com/questions/50504441/django-updateview-generic-class