Ember Server Side Form validation with Django

In previous post (Ember Server Side Form validation with Mirage), I’ve looked at just the Ember.js side. In this article, I’ll connect it with Django so that we have an actual backend that’s returning our errors. It builds on top of previous Ember.js code. There are also full Github repositories at the end.

Lets start with Django. We’ll be using Django Rest Framework to generate server side Django.

We have a basic models.py:

<br />
from __future__ import unicode_literals<br />
from django.db import models</p>
<p>class Registration(models.Model):<br />
    GENDER_CHOICES = (<br />
        ('male', 'Male'),<br />
        ('female', 'Female'),<br />
        ('unspecified', 'Unspecified')<br />
<p>    firstname = models.CharField(max_length=100)<br />
    lastname = models.CharField(max_length=100)<br />
    submitted = models.DateTimeField(auto_now_add=True)<br />

and an API in views.py:

<br />
from rest_framework import viewsets<br />
from rest_framework.response import Response<br />
from rest_framework import status</p>
<p>from .models import Registration<br />
from .serializers import RegistrationSerializer</p>
<p>class RegistrationViewSet(viewsets.ViewSet):<br />
    def create(self, request):<br />
        serializer = RegistrationSerializer(data=request.data)<br />
        if serializer.is_valid():<br />
            serializer.save()<br />
            return Response(serializer.data, status=status.HTTP_201_CREATED)<br />
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)<br />

One thing to note – we return 400 Error code, instead of 422 that we mocked with Mirage. That is because Ember Django Adapter wraps 400 error to make it compatible with JSON API specification.

All of our business logic of API validation happens in serializers.py:

<br />
from rest_framework import serializers</p>
<p>from . models import Registration</p>
<p>class RegistrationSerializer(serializers.ModelSerializer):<br />
    class Meta:<br />
        model = Registration<br />
        fields = ('id', 'firstname', 'lastname')</p>
<p>    def validate_firstname(self, value):<br />
    	if 'john' not in value.lower():<br />
    		raise serializers.ValidationError('First name must be John')<br />
    	return value</p>
<p>    def validate_lastname(self, value):</p>
<p>    	if 'smith' in value.lower():<br />
    		raise serializers.ValidationError(&quot;Last name can't be Smith&quot;)<br />
    	return value</p>
<p>    def validate(self, data):<br />
    	if data['firstname'] == 'John' and data['lastname'] == 'Doe':<br />
    		raise serializers.ValidationError(&quot;Please enter a more original name&quot;)<br />

With server side in place, we can extend the previous example Ember.js app. We’ll be using Ember Django Adapter to make things easier.

First of, we need to turn of ember-cli-mirage in config/environment.js. We also set the development URL and API namespace at the same time.

<br />
  if (environment === 'development') {<br />
    ENV.APP.API_HOST = 'http://localhost:8000';<br />
    ENV.APP.API_NAMESPACE = 'api';</p>
<p>    ENV['ember-cli-mirage'] = {<br />
      enabled: false<br />
    };<br />
  }<br />

Another source of problems is that DS.RESTAdapter pluralises api endpoints. So instead of /api/registration/ it posts to /api/registrations/. To make it stop doing that we can define ‘registration’ as uncountable:
(ember generate drf-adapter application)

<br />
import DRFAdapter from './drf';<br />
import Inflector from 'ember-inflector';</p>
<p>const inflector = Inflector.inflector;<br />
<p>export default DRFAdapter.extend({});<br />

Controller is still the same:

<br />
import Ember from 'ember';</p>
<p>export default Ember.Controller.extend({<br />
  actions: {<br />
    save() {<br />
      var model = this.get('model');</p>
<p>      model.save().then((registration) =&gt; {<br />
        // it's a mock, we don't do anything<br />
      }).catch((adapterError) =&gt; {<br />
        // we just need to catch error<br />
      });<br />
    }<br />
  }<br />
});<br />

The main improvement is that template error handling now also displays non-field errors (via model.errors.base):

<br />
{{#each model.errors.base as |error|}}<br />
  &lt;span class=&quot;errors&quot;&gt;{{error.message}}&lt;/span&gt;<br />
<p>&lt;form&gt;<br />
  &lt;p&gt;<br />
    &lt;label&gt;First name: {{input value=model.firstname}}&lt;/label&gt;<br />
    {{#each model.errors.firstname as |error|}}<br />
      &lt;span class=&quot;errors&quot;&gt;{{error.message}}&lt;/span&gt;<br />
    {{/each}}<br />
  &lt;/p&gt;<br />
  &lt;p&gt;<br />
    &lt;label&gt;Last name:<br />
      {{input value=model.lastname}}<br />
    &lt;/label&gt;<br />
    {{#each model.errors.lastname as |error|}}<br />
      &lt;span class=&quot;errors&quot;&gt;{{error.message}}&lt;/span&gt;<br />
    {{/each}}<br />
  &lt;/p&gt;<br />
  &lt;button {{action 'save'}}&gt;Save&lt;/button&gt;<br />
&lt;/form&gt;<br />

With this in place, form validation errors now work correctly. If server side form validation passes, it also writes data into Data Store.

Ember.js code is in ‘django-api’ branch at https://github.com/ember-examples/server-side-validation-mirage/tree/django-api
Django code is at https://github.com/ember-examples/django-drf-serializer-validations