Python/Django: Populating Model Form Fields with values from Imported JSON file
Python/Django: Populating Model Form Fields with values from Imported JSON file
I have a model form that saves all form field inputs to the backend database as one entry. I also have a JSON file that contains multiple JSON objects whose fields corresponds to the model form field. This JSON file is being uploaded via FileField in the model. Ultimately, I want to be able to upload a JSON file with the multiple JSON objects into my model form and populate the fields with the corresponding values from the uploaded JSON file. Each JSON object will be a single entry to my database and they can have null values for at least one field. Ideally, I would like to be able to choose which JSON object (from the uploaded JSON file) gets loaded to my model form fields to eventually be saved in my database. How would I go about implementing this?
2 Answers
2
You could use the django rest framework. It will provide a post function and serializers.
You'll wind up with some stuff like this:
# the model
class Book(Model):
title = TextField()
author = TextField()
# the serializer
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
# the view
class BookView(generics.ListCreateApiView):
queryset = Book.objects.all()
serializer_class = BookSerializer
see the tutorial for more details:
http://www.django-rest-framework.org/tutorial/1-serialization/#tutorial-1-serialization
Then you can post your data to the database
data = [{'title': 'Moby Dick', 'author': 'Herman Melville'},
{'title': 'A Game of Thrones', 'author': 'George R. R. Martin'}]
for d in data:
r = requests.post('django_api_url/book/', d)
r.raise_for_status()
# the new record is returned if successful
print(r.json())
To unpack a JSON string into a Django model, you can use the Python Standard Library json
package to convert it into a dict
and then unpack it into the object as keyword arguments using **
:
json
dict
**
>>> from user.models import User
>>> import json
>>> some_json = '{"username": "cole","password": "testing123"}'
>>> User(**json.loads(some_json))
<User: cole>
>>> User(**json.loads(some_json)).username
'cole'
>>> User(**json.loads(some_json)).password
'testing123'
By the way, there's a nice StackOverflow answer about **
here.
**
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
docs.python.org/3/tutorial/…
– Ignacio Vazquez-Abrams
Jun 29 at 23:50