问题描述:

I am building a mobile app using ionic.

For normal django site, we generate context in view and send that to template and the template displays html using multiple ways like form.as_p or form.field etc.

What about this ionic mobile app ?

网友答案:

Django Forms not very helpful for mobile clients

Django forms are not going to be very helpful for this. Your ionic app needs to have its own form that live independently from the Django app (which is remote vis-a-vis your Django deployment)

Mobile clients communicate through HTTP

Under the hood what usually happens is your ionic app will communicate, using HTTP, with your Django app. This can be e.g. over a JSON REST API.

I suggest you build up a REST API on Django, e.g. with Django REST Framework because it is very close to Django's design and idioms. So you get quick support for familiar things like models and validators.

Ionic is AngularJS/Angular2 based, so you can use a host of REST facilities to communicate with your server when your form is posted.

Generating forms dynamically on the client side using HTTP OPTIONS

If you, for some reason, need to autogenerate the forms on client side (e.g. you are religious about DRY, or you have many forms that follow some patterns etc), you can use the OPTIONS HTTP verb to get metadata about the form and its fields

e.g. a client-side form could parse this data structure to build the form

"actions": {
    "POST": {
        "note": {
            "type": "string",
            "required": false,
            "read_only": false,
            "label": "title",
            "max_length": 100
        }
    }
}

You can do this with some libraries, you just have to transform the schema format a little bit, either with a custom DRF metadata generator, or some manipulation on the JS side.

网友答案:

I typically use Django-rest-framework (DRF) to build out the api in Django. DRF provides serializers that allow you to validate the incoming request data, much like you would with Django forms.

To answer your question fully though:

You build out your html form with the appropriate fields, then POST the data to your api endpoint (which is an API view), then validate the incoming request data with a serializer.

相关阅读:
Top