Reputation: 24764
in django 1.6, I have a model with
class Person(models.Model):
name = models.CharField(max_length=200)
lastname = name = models.CharField(max_length=200)
and a form
class EventPerson(ModelForm):
class Meta:
model = Event
fields = ['name', 'lastname']
if I create a object with
p = Person.object.create(name='John')
and I have a dictionary
d = {'lastname':'Smith'}
how I can update the object with the dictionary and the form ?
Upvotes: 0
Views: 2793
Reputation: 2882
If your model doesn't have inherited attributes you can use:
p.__dict__.update(d)
p.save()
You can use this in the form's __init__
also
Upvotes: 1
Reputation: 20780
The easiest way to do that with the least code would be with the class based UpdateView
.
Here is the link to the Django Docs:
A views.py code sample would be:
from django.views.generic.edit import UpdateView
from myapp.models import Person
class PersonUpdate(UpdateView):
model = Person
fields = ['name', 'lastname']
template_name_suffix = '_update_form'
Then just add the form in your template. By default the template name will be person_update_form.html
The template code just looks like:
<form action="" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
This will also automatically populate the form with any initial form data from the Person
object that you are trying to update.
Edit:
To update an object based on a dict of the object you want to:
get the object
person = Person.object.get(name='John')
update it
# if this is the new lastname
d = {'lastname':'Smith'}
# then access the dict and update it
person.lastname = d['lastname']
save the object
person.save()
You don't need to use the form if you are not using a template.
Upvotes: 1