Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A platform independent django form serializer

License

NotificationsYou must be signed in to change notification settings

WiserTogether/django-remote-forms

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

60 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

A package that allows you to serialize django forms, including fields and widgets into Pythondictionary for easy conversion into JSON and expose over API

Please go through mydjangocon US 2012 talkto understand the problem sphere, motivations, challenges and implementation of Remote Forms

Sample Implementation

If you don't mind digging around a little bit to learn about different the components that might benecessary for an implementation of django-remote-forms, check outdjango Remote Admindjango-remote-admin

Usage

Minimal Example

fromdjango_remote_forms.formsimportRemoteFormform=LoginForm()remote_form=RemoteForm(form)remote_form_dict=remote_form.as_dict()

Upon converting the dictionary into JSON, it looks like this:

{"is_bound":false,"non_field_errors": [],"errors": {},"title":"LoginForm","fields": {"username": {"title":"CharField","required":true,"label":"Username","initial":null,"help_text":"This is your django username","error_messages": {"required":"This field is required.","invalid":"Enter a valid value."            },"widget": {"title":"TextInput","is_hidden":false,"needs_multipart_form":false,"is_localized":false,"is_required":true,"attrs": {"maxlength":"30"                },"input_type":"text"            },"min_length":6,"max_length":30        },"password": {"title":"CharField","required":true,"label":"Password","initial":null,"help_text":"","error_messages": {"required":"This field is required.","invalid":"Enter a valid value."            },"widget": {"title":"PasswordInput","is_hidden":false,"needs_multipart_form":false,"is_localized":false,"is_required":true,"attrs": {"maxlength":"128"                },"input_type":"password"            },"min_length":6,"max_length":128        }    },"label_suffix":":","prefix":null,"csrfmiddlewaretoken":"2M3MDgfzBmkmBrJ9U0MuYUdy8vgeCCgw","data": {"username":null,"password":null    }}

An API endpoint serving remote forms

fromdjango.core.serializers.jsonimportsimplejsonasjson,DjangoJSONEncoderfromdjango.httpimportHttpResponsefromdjango.middleware.csrfimportCsrfViewMiddlewarefromdjango.views.decorators.csrfimportcsrf_exemptfromdjango_remote_forms.formsimportRemoteFormfrommy_awesome_project.formsimportMyAwesomeForm@csrf_exemptdefmy_ajax_view(request):csrf_middleware=CsrfViewMiddleware()response_data= {}ifrequest.method=='GET':# Get form definitionform=MyAwesomeForm()elifrequest.raw_post_data:request.POST=json.loads(request.raw_post_data)# Process request for CSRFcsrf_middleware.process_view(request,None,None,None)form_data=request.POST.get('data', {})form=MyAwesomeForm(form_data)ifform.is_valid():form.save()remote_form=RemoteForm(form)# Errors in response_data['non_field_errors'] and response_data['errors']response_data.update(remote_form.as_dict())response=HttpResponse(json.dumps(response_data,cls=DjangoJSONEncoder),mimetype="application/json"    )# Process response for CSRFcsrf_middleware.process_response(request,response)returnresponse

djangocon Proposal

This is a bit lengthy. But if you want to know more about my motivations behind developing django-remote-formsthen read on.

In our quest to modularize the architecture of web applications, we create self-containing backendsystems that provide web APIs for programmatic interactions. This gives us the flexibility toseparate different system components. A system with multiple backend components e.g. user profileengine, content engine, community engine, analytics engine may have a single frontend applicationthat fetches data from all of these components using respective web APIs.

With the increased availability of powerful JavaScript frameworks, such frontend applications areoften purely JS based to decrease application footprint, increase deployment flexibility andseparate presentation from data. The separation is very rewarding from a software engineeringstandpoint but imposes several limitations on system design. Using django to construct the API forarbitrary consumers comes with the limitation of not being able to utilize the powerful django formsubsystem to drive forms on these consumers. But is there a way to overcome this restriction?

This is not a trivial problem to solve and there are only a few assumptions we can make about theweb API consumer. It can be a native mobile or desktop - application or browser. We advocate thatweb APIs should provide sufficient information about 'forms' so that they can be faithfullyreproduced at the consumer end.

Even in a API backend built using django, forms are essential for accepting, filtering, processingand saving data. The django form subsystem provides many useful features to accomplish these tasks.At the same time it facilitates the process of rendering the form elements in a browserenvironment. The concepts of form fields combined with widgets can go a long way in streamliningthe interface to interact with data.

We propose an architecture to serialize information about django forms (to JSON) in a frameworkindependent fashion so that it can be consumed by any frontend application that renders HTML. Suchinformation includes but is not limited to basic form configurations, security tokens (ifnecessary), rendering metadata and error handling instructions. We lovingly name this architecturedjango-remote-forms.

At WiserTogether, we are in the process of building a component based architecture that strictlyprovides data endpoints for frontend applications to consume. We are working towards developingour frontend application for web browsers using backbone.js as MVC and handlebars as the templatingengine. django-remote-forms helps us streamline our data input interface with the django formsliving at the API backend.

About

A platform independent django form serializer

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors8

Languages


[8]ページ先頭

©2009-2025 Movatter.jp