Update django-angular dependency and improve example form (WIP).

This commit is contained in:
Christopher Charbonneau Wells 2017-08-15 14:07:06 -04:00
parent 2247d5f9e6
commit ee3b6d8988
6 changed files with 106 additions and 12 deletions

2
Pipfile.lock generated
View File

@ -16,7 +16,7 @@
"version": "==1.11.4"
},
"django-angular": {
"version": "==1.0.2"
"version": "==1.1"
},
"django-filter": {
"version": "==1.0.4"

View File

@ -7,7 +7,7 @@ from django.contrib import admin
from core import views
urlpatterns = [
url(r'^baby/new/$', views.BabyFormView.as_view(), name='baby_new'),
url(r'^baby/add/$', views.BabyFormView.as_view(), name='baby_add'),
url(r'^admin/', admin.site.urls),
url(r'', include('api.urls')),

View File

@ -1,12 +1,16 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.forms import fields, widgets
from django.core.exceptions import ValidationError
from django.forms import widgets
from djng.forms import fields, NgModelFormMixin, NgFormValidationMixin
from djng.styling.bootstrap3.forms import Bootstrap3Form
class BabyForm(Bootstrap3Form):
class BabyForm(NgModelFormMixin, NgFormValidationMixin, Bootstrap3Form):
use_required_attribute = False
scope_prefix = 'subscribe_data'
form_name = 'baby_new'
first_name = fields.CharField(
label='First name',
@ -22,3 +26,11 @@ class BabyForm(Bootstrap3Form):
label='Date of birth',
widget=widgets.DateInput(attrs={'validate-date': '^(\d{4})-(\d{1,2})-(\d{1,2})$'}),
help_text='Allowed date format: yyyy-mm-dd')
def clean(self):
if self.cleaned_data.get(
'first_name') == 'John' and self.cleaned_data.get(
'last_name') == 'Doe':
raise ValidationError(
'The full name "John Doe" is rejected by the server.')
return super(BabyForm, self).clean()

View File

@ -1,9 +1,37 @@
<script type="text/javascript">
angular.module('djangular-demo', ['djng.forms']);
</script>
{% extends "base.html" %}
<form method="post" action="babyblotter" validate>
{% block title %}Add Baby Form{% endblock %}
{% block head %}
<script type="text/javascript">
angular.module('baby-add', ['djng.forms']).config(function($httpProvider) {
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
$httpProvider.defaults.headers.common['X-CSRFToken'] = '{{ csrf_token }}';
});
angular.module('baby-add').controller('BabyNewForm', ['$scope', '$http', '$window', 'djangoForm',
function($scope, $http, $window, djangoForm) {
$scope.submit = function() {
if ($scope.subscribe_data) {
$http.post(".", $scope.subscribe_data).then(function(response) {
if (!djangoForm.setErrors($scope.my_form, response.data.errors)) {
// on successful post, redirect onto success page
$window.location.href = response.data.success_url;
}
}, function() {
console.error('An error occurred during submission');
});
}
return false;
};
}]);
</script>
{% endblock %}
{% block content %}
<form name="{{ form.form_name }}" method="post" action="." novalidate ng-controller="BabyNewForm">
{% csrf_token %}
{{ form.as_div }}
<button type="submit" class="btn btn-primary">Subscribe</button>
</form>
<button type="submit" ng-disabled="{{ form.form_name }}.$invalid" class="btn btn-primary">Submit via Post</button>
<button type="button" ng-disabled="{{ form.form_name }}.$invalid" ng-click="submit()" class="btn btn-primary">Submit via Ajax</button>
</form>
{% endblock %}

40
core/templates/base.html Normal file
View File

@ -0,0 +1,40 @@
{% load static djng_tags %}
<!doctype html>
<html lang="en">
<head>
<title>{% block form_title %}Baby Blotter{% endblock %}</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css" />
<link href="{% static 'djng/css/styles.css' %}" rel="stylesheet" />
<link href="{% static 'djng/css/bootstrap3.css' %}" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.11/angular.js"></script>
</head>
<body>
<header class="navbar navbar-static-top navbar-inverse">
<div class="container">
<div class="row">
<div class="col-xs-12">
<h1 class="navbar-brand">Baby Blotter<small style="margin-left: 3em;">Tracking literal shit.</small></h1>
</div>
</div>
</div>
</header>
<div class="container">
<div class="row">
<nav class="col-md-3" style="margin-top: 65px;" role="navigation">
<ul class="nav nav-pills nav-stacked">
<li>
<a href="{% url 'baby_add' %}">Add Baby</a>
</li>
</ul>
</nav>
<main class="col-md-9">
{% block content %}{% endblock %}
</main>
</div>
</div>
</body>
</html>

View File

@ -1,8 +1,12 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from django.http import HttpResponse
from django.core.urlresolvers import reverse_lazy
from django.views.generic.edit import FormView
from django.utils.encoding import force_text
from core.forms import BabyForm
@ -11,3 +15,13 @@ class BabyFormView(FormView):
template_name = 'baby-form.html'
form_class = BabyForm
success_url = reverse_lazy('form_data_valid')
def post(self, request, **kwargs):
if request.is_ajax():
return self.ajax(request)
return super(BabyFormView, self).post(request, **kwargs)
def ajax(self, request):
form = self.form_class(data=json.loads(request.body))
response_data = {'errors': form.errors, 'success_url': force_text(self.success_url)}
return HttpResponse(json.dumps(response_data), content_type="application/json")