The sentences may be awkward, because a translator was used.
I created a website created by Django the “설표의 장고(https://django.seolpyo.com).”
I’m improving the code in my project…
I have a question about modelform.
My project has field a and field b that field b converts the contents of field a.
Therefore, when field a is changed, field b must be saved together, or
If field a doesn’t change, I don’t want field b to be updated either.
Currently, I am using a form instead modelform, because I think modelform is not provide update_fields.
It looks like the modelform simply uses the save method and doesn’t pass any arg. Is there something I’m missing?
I would also appreciate any advice on my work methods.
Welcome @white-seolpyo !
It would help if you were a lot more specific about the situation you’re facing, including the code you’re already using along with sample data showing exactly what it is you’re trying to achieve.
In the general case, there’s no need to. All the data needed to process a model form is in the form or is available from the form.
Also, be aware that a ModelForm
is a Form
- just with some functionality added. Everything you do with a Form
can also be done with a ModelForm
.
field a and filed b is textfield.
but, field a save markdown text, field b save html text(convert field a).
what means that “In the general case, there’s no need to.”??
I believe that you might want to use pre-save signal to auto update field b if field a is changed.
Or you can use overriding save method in model class.
By that, you can guarantee that not only the form save trigger model save, but also API update/create would trigger field b update too.
Hope this help.
i’m sorry.
i told that modelform.save(), but you told seems like model.save()…
is work in modelform??
https://github.com/django/django/blob/main/django/forms/models.py
yes, form.save()
will execute model.savel()
.
Check this here /django/forms/models.py
Could you please write an example of passing the changed_field of the form?
It looks like the project decides which fields to update when it implements the view…
I don’t know how to use this.
Is it correct to use it in views.py?
As I can see from /django/forms/models.py
, the changed data is in form.changed_data
. You can set a breakpoint()
inside the function form.save()
to check.
elif form.has_changed():
self.changed_objects.append((obj, form.changed_data))
saved_instances.append(self.save_existing(form, obj, commit=commit))
if not commit:
self.saved_forms.append(form)
Oh… I guess I didn’t understand the save_existing_objects part.
Thanks for letting me know.
Please do not post images of code, templates, or other textual information here.
Copy / paste the text into the body of your post, surrounded between lines of three backtick - ` characters. This means you’ll have a line of ```, then the code (or template, etc), then another line of ```. This allows you to post the code and force the forum software to keep it properly formatted.
1 Like