fmakawa
fmakawa

Reputation: 350

Create Django Model Instance using POST method in another Python Script

So I have a django app with some models which I can manipulate via admin and also through a client facing site, like add instances etc. However, I would like to try something a little different from that. I have a Python script that uses POST and JSON objects based on those self same models and I would like to be able to run it, connect to my django app server via a port and create new instances of my models (essentially without using Admin or my client page). Any ideas how I go about this?

Upvotes: 1

Views: 412

Answers (1)

Will Keeling
Will Keeling

Reputation: 23014

If what the script does is simple, it may be easiest just to create a view which receives the JSON, processes it, and returns a JsonResponse.

e.g.

def create_object(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        # Do something with the data - e.g. create a model instance
        MyModel.objects.create(**data)
        return JsonResponse({'status': 'created'})

Alternatively, if the script does more complicated things or if you intended to expand it in future, you may be best to expose your site via a REST API using something such as Django Rest Framework.

With Django Rest Framework, you can fairly rapidly build CRUD based APIs around your models using components such as ModelViewSets and ModelSerializers and expose them over REST with minimal code.

Upvotes: 2

Related Questions