Commit 4aa77254 authored by Ale's avatar Ale

feat: Add form handling

parent 63d23904
......@@ -5,14 +5,20 @@ from rest_framework import routers
# app
from . import views
router = routers.DefaultRouter()
router.register(r'testimonies', views.TestimonyViewSet)
urlpatterns = [
# Tracks
# Testimonies
path(
'',
include(router.urls)
),
# Create a new testimony
path(
'report',
views.create_testimony,
name='create_testimony'
)
]
# python
#import json
#
# django
#from django.http import HttpResponse, JsonResponse
from rest_framework import viewsets
from django.views.decorators.csrf import csrf_protect
from django.http import HttpResponse, JsonResponse
from django.contrib import messages
from django.core.mail import send_mail
# project
from apps.map import models
from .serializers import TestimonySerializer
from apps.map.forms import TestimonyForm
class TestimonyViewSet(viewsets.ModelViewSet):
queryset = models.Testimony.objects.filter(published=True).order_by('name')
serializer_class = TestimonySerializer
# TODO: move into the viewset
@csrf_protect
def create_testimony(request):
""" Creates a Clip object. """
if request.method == 'POST' and request.is_ajax:
data = request.POST
form = TestimonyForm(
data,
files=request.FILES
)
if form.is_valid():
new_testimony = form.save()
else:
return HttpResponse(
form.errors.as_json(),
content_type="application/json",
status=400
)
send_mail(
'Hay un nuevo testimonio en Patio108',
'',
'no-reply@patio108.es',
['contacta@patio108.es'],
fail_silently=False,
)
messages.success(request, "Gracias por tu testimonio, se publicará en cuanto lo revisemos!")
return HttpResponse(status=200)
return HttpResponse(status=403)
......@@ -17,10 +17,10 @@ from adminsortable.models import SortableMixin
from . import validators, utils
from django.conf import settings
validate_image_size = validators.ImageSizeValidator({
'min_width' : 480,
'min_height' : 480,
'max_width' : 1920,
validate_image_size = validators.ImageSizeValidator({
'min_width' : 480,
'min_height' : 480,
'max_width' : 1920,
'max_height' : 1280 })
validate_image_type = validators.ImageTypeValidator(["jpeg", "png"])
validate_file_type = validators.FileTypeValidator()
......@@ -28,26 +28,26 @@ images_path = utils.RenameImage("images/")
files_path = utils.RenameFile("attachments/")
class Image(SortableMixin):
""" Images """
image_file = models.ImageField(
_('Archivo de imagen'),
blank=False,
validators=[validate_image_size, validate_image_type],
upload_to=images_path
)
caption = models.CharField(
_('Texto alternativo/Pie de foto'),
max_length=200,
blank=False,
null=True
class Image(SortableMixin):
""" Images """
image_file = models.ImageField(
_('Archivo de imagen'),
blank=False,
validators=[validate_image_size, validate_image_type],
upload_to=images_path
)
caption = models.CharField(
_('Texto alternativo/Pie de foto'),
max_length=200,
blank=False,
null=True
)
content_type = models.ForeignKey(
ContentType,
on_delete=models.CASCADE
)
object_id = models.PositiveIntegerField()
object_id = models.PositiveIntegerField()
source_content = GenericForeignKey(
'content_type',
'object_id'
......@@ -72,7 +72,7 @@ class Image(SortableMixin):
verbose_name = _('imagen')
verbose_name_plural = _('imágenes')
ordering = ['order']
def __str__(self):
return self.image_file.name
......@@ -255,7 +255,7 @@ class Publishable(models.Model):
published = models.BooleanField(
_('Published'),
blank=True,
default=True,
default=False,
)
owner = models.ForeignKey(
User,
......
......@@ -735,6 +735,22 @@ select:hover {
cursor: pointer;
color: #fc160f; }
.site-messages {
position: fixed;
width: 400px;
left: calc(50% - 200px);
top: 50px;
z-index: 50000; }
.site-message--success {
background-color: #43AD36;
color: white;
padding: 1.6rem;
transition: opacity 0.2s ease; }
.site-message--success:hover {
cursor: pointer;
opacity: 0.5; }
.modal {
position: fixed;
z-index: 150000; }
......
This diff is collapsed.
......@@ -22,4 +22,30 @@ document.addEventListener('DOMContentLoaded', function(){
});
})
});
document.querySelectorAll('.site-message').forEach( function(i){
i.addEventListener('click', function(e){
i.remove();
});
});
var form = document.querySelector('form');
if(form) form.addEventListener('submit', function(e){
e.preventDefault();
console.log("submitting");
var data = new FormData(form);
jQuery.ajax({
type : form.method,
url : form.action,
data : data,
processData: false,
contentType: false,
success : function(response)
{
location.reload();
},
error : function(response)
{
console.log('error: ' + response);
},
});
});
});
.site-messages
position: fixed
width: 400px
left: calc(50% - 200px)
top: 50px
z-index: 50000
.site-message--success
background-color: $green
color: white
padding: $m
transition: opacity .2s ease
&:hover
cursor: pointer
opacity: .5
......@@ -30,8 +30,17 @@
{# header #}
<header class="region-header">
<div class="region-messages">
<ul class="site-messages">
{% for message in messages %}
<li class="site-message {% if message.tags %}site-message--{{ message.tags }}{% endif %}">
<span class="site-message__close">×</span>
{{ message|safe }}
</li>
{% endfor %}
</ul>
</div>
</header>
</div>
{# content #}
<main class="region-content">
......
{# Default form #}
{% load i18n static %}
<form action="{{ action }}" enctype="multipart/form-data" method="post" class="form {% if modifier %}form--{{ modifier }}{% endif %}">
<form action="{{ action }}" enctype="multipart/form-data" method="POST" class="form {% if modifier %}form--{{ modifier }}{% endif %}">
{% csrf_token %}
{% include 'forms/form-errors.html' with form=form %}
{% for field in form %}
......
......@@ -95,7 +95,8 @@
Cuéntanos tu historia
</h2>
<div class="modal__body half">
{% include 'forms/form.html' with form=form %}
{% url 'create_testimony' as api_endpoint %}
{% include 'forms/form.html' with form=form action=api_endpoint %}
</div>
</div>
</div>
......@@ -112,6 +113,7 @@
<script type="text/javascript" src="{% static '/map/js/dist/map.min.js' %}"></script>
{% endif %}
{% if form %}
<script type="text/javascript" src="{% static '/admin/js/vendor/jquery/jquery.min.js' %}"></script>
{% leaflet_js plugins="forms" %}
{{ form.media }}
{% endif %}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment