Skip to content

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:

from __future__ import unicode_literals
from django.db import models

class Registration(models.Model):
    GENDER_CHOICES = (
        ('male', 'Male'),
        ('female', 'Female'),
        ('unspecified', 'Unspecified')
    )

    firstname = models.CharField(max_length=100)
    lastname = models.CharField(max_length=100)
    submitted = models.DateTimeField(auto_now_add=True)

and an API in views.py:

from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework import status

from .models import Registration
from .serializers import RegistrationSerializer

class RegistrationViewSet(viewsets.ViewSet):
    def create(self, request):
        serializer = RegistrationSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

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:

from rest_framework import serializers

from . models import Registration

class RegistrationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Registration
        fields = ('id', 'firstname', 'lastname')
   
    def validate_firstname(self, value):
    	if 'john' not in value.lower():
    		raise serializers.ValidationError('First name must be John')
    	return value

    def validate_lastname(self, value):

    	if 'smith' in value.lower():
    		raise serializers.ValidationError("Last name can't be Smith")
    	return value

    def validate(self, data):
    	if data['firstname'] == 'John' and data['lastname'] == 'Doe':
    		raise serializers.ValidationError("Please enter a more original name")

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.

  if (environment === 'development') {
    ENV.APP.API_HOST = 'http://localhost:8000';
    ENV.APP.API_NAMESPACE = 'api';

    ENV['ember-cli-mirage'] = {
      enabled: false
    };
  }

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)

import DRFAdapter from './drf';
import Inflector from 'ember-inflector';

const inflector = Inflector.inflector;
inflector.uncountable('registration');

export default DRFAdapter.extend({});

Controller is still the same:

import Ember from 'ember';

export default Ember.Controller.extend({
  actions: {
    save() {
      var model = this.get('model');

      model.save().then((registration) => {
        // it's a mock, we don't do anything
      }).catch((adapterError) => {
        // we just need to catch error
      });
    }
  }
});

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

{{#each model.errors.base as |error|}}
  <span class="errors">{{error.message}}</span>
{{/each}}

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

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