Let's say I have the model Project
. The model Project
has > 100 fields.
I can create new Projects
from the front-End using forms.
When I want to edit/update some field of a Project
in the back-end I've been doing something like this (truncated):
def edit_project(request):
if request.method == 'POST':
project_to_edit = Project.objects.get(pk=request.POST['project_id'])
project_to_edit.description = request.POST['description']
project_to_edit.name = request.POST['name']
#repeat the same process for each field...(>50)
project_to_edit.save()
return redirect('project_page/')
return redirect('index')
The problem is that new fields are constantly being added to the Projects
model.
Is there a dynamic/ pythonic way to update each field in the model without having to do it 'manually' for each field and save lines of code?
You can update fields dynamically like that:
def edit_project(request):
if request.method == 'POST':
project_to_edit = Project.objects.get(pk=request.POST['project_id'])
for field in self.fields:
project_to_edit.description = request.POST[field]
project_to_edit.name = request.POST[field]
#repeat the same process for each field...(>50)
project_to_edit.save()
return redirect('project_page/')
return redirect('index')
PS You should use form.cleaned_data to access your form data and not directly the submitted data. Modelform would solve your issues https://docs.djangoproject.com/en/4.0/topics/forms/modelforms/
I think this is the way to go.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.