Reputation: 786
I'm new to Django. I have client application, that sends POST request to the server to create a new Conference object on the server. Serverside code looks like this:
new_conf.date = request.POST['date']
new_conf.name = request.POST['name']
new_conf.languages = request.POST['languages']
new_conf.is_open = request.POST['is_open']
new_conf.place = request.POST['place']
new_conf.recognition_on = request.POST['recognition_on']
Is there a way to write it shorter? Is it possible to write some general template to use in similar situations?
Upvotes: 2
Views: 67
Reputation: 55448
You can make a ModelForm
form your model, and have it "unpack" the request.POST data into a model instance
# Create a form instance from POST data.
>>> conf_form = ConferenceForm(request.POST)
# Save a new Conference object from the form's data.
>>> new_conf = conf_form.save()
ref. https://docs.djangoproject.com/es/1.9/topics/forms/modelforms/#the-save-method
Or, for a more Python-generic solution, you can make a list of keys you want and use setattr
or set the keys in your dict, like below
for key in ['date', 'name', 'languages', ...]:
setattr(new_conf, key, request.POST[key])
# Or if new_conf is a dict-like obj
new_conf[key] = request.POST[key]
Upvotes: 5