0

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 ?

2 Answers 2

1

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:

https://docs.djangoproject.com/en/dev/ref/class-based-views/generic-editing/#django.views.generic.edit.UpdateView

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I use the form in a management command, I can't use a template
yes, I know update like person.lastname = d['lastname'] but my problem is more general, in the question only need update one field, but in real case I have more fields. I like use form for create objects because I can use methods like clean, clean_, etc.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.