Let's say I have a Student model, with name and age fields, and I have a page with a DetailView class showing these fields. Let's say that rather than having one "update" button that will take me to a form to update all fields of my model at once, I want a separate button for each field that takes me to a separate page with a form to update it.
I know how I could do this with a separate HTML file and separate UpdateView class for each field, but it seems like there should be a cleaner way.
In the first HTML file I have two buttons:
<a href="{% url 'update_name' pk=student.pk%}">Update name</a>
<a href="{% url 'update_age' pk=student.pk%}">Update age</a>
In the second I have the form:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
Urls:
urlpatterns = [
path('<int:pk', views.StudentDetailView.as_view(), name="detail"),
path('update_name/<int:pk>', views.StudentUpdateView.as_view(), name="update_name"),
path('update_age/<int:pk>', views.StudentUpdateView.as_view(), name="update_age"),
]
Views:
class StudentUpdateView(UpdateView):
model = models.Student
template_name = 'update_student.html'
I suppose I'm looking for some sort of if statement that I can put in my view, like:
if condition:
fields = ("name",)
elif condition2:
fields = ("age",)
Hopefully this makes sense! Thank you for any help :)
CodePudding user response:
The simplest way to do this is to override the fields
in your urls.py file.
urlpatterns = [
path('<int:pk', views.StudentDetailView.as_view(), name="detail"),
path('update_name/<int:pk>', views.StudentUpdateView.as_view(fields=['name']), name="update_name"),
path('update_age/<int:pk>', views.StudentUpdateView.as_view(fields=['age']), name="update_age"),
]
View.as_view
accepts keyword arguments, which are used to override the classes attributes for that occurrence.