[Answered ]-Looking for a easier cleaner way to save ajax POST data to a django model and avoid hardcoding for saving?

2👍

you may want to have a look at ModelForms

👤second

0👍

This method will work, although you have to be careful to add a model field / ajax parameter at the sametime for it to work

Given:

Form1

<form method="post">
  <input name="parameter1" />
  <input name="parameter2" />
  <input name="parameter3" />
</form>

Write javascript code so the data going across the wire looks like this JSON (form serialization
will probably not work)

{ parameter1 : "some data", "parameter2" : "some data", parameter3 : "some data" }

Then, you have a django model that looks like this

class MyModel(models.Model):
    parameter1 = models.StringField()
    parameter2 = models.StringField()
    parameter3 = models.StringField()

You can save/update with code like this:

params = dict(request.POST)

m = MyModel.objects.create(**params)

or

m = MyModel.objects.get(id=ID)
m.update(force_update=False,**params)

If your parameters do not line up the code will fail though.

Leave a comment