from django.views.generic.edit import CreateView
from .models import Contact, Files
from .forms import ContactForm
from django import http
import pdb # pdb.set_trace()
class AjaxableResponseMixin:
"""
Mixin to add AJAX support to a form.
Must be used with an object-based FormView (e.g. CreateView)
"""
def form_invalid(self, form):
response = super().form_invalid(form)
if self.request.is_ajax():
return http.JsonResponse(form.errors, status=400)
else:
return response
def form_valid(self, form):
# We make sure to call the parent's form_valid() method because
# it might do some processing (in the case of CreateView, it will
# call form.save() for example).
response = super().form_valid(form)
if self.request.is_ajax():
data = {
'pk': self.object.pk,
}
return http.JsonResponse(data)
else:
return response
class ContactView(AjaxableResponseMixin, CreateView):
model = Contact
fields = ('name', 'phone', 'email', 'body')
# class ContactView(FormView):
# form_class = ContactForm
# template_name = 'contact/contact.html'
# success_url = '#' # адрес страницы успеха отправки формы
# def post(self, request, *args, **kwargs):
# pdb.set_trace()
# form_class = self.get_form_class()
# form = self.get_form(form_class)
# files = request.FILES.getlist('files')
# if form.is_valid():
# id = form.save().pk
# contact = Contact.objects.get(pk=id)
# if files:
# for f in files:
# fl = Files(contact=contact, file = f)
# fl.save()
# data = {'message': 'Сообщение успешно отправлено.'}
# return http.JsonResponse(data) #self.form_valid(form)
# else:
# return self.form_invalid(form)
class ContactSent(CreateView):
pass
function ajaxPOST(url, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4) {
callback(request.responseText);
}
};
request.open("POST", url, true);
request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
request.send();
}
function send(obj) {
url = obj.action;
ajaxPOST(url, function(data) {
alert(data);
});
return false;
}
<form class="tile contact" action="{% url 'contact_form' %}" method="POST" onsubmit="send(this)" enctype="multipart/form-data">
{% csrf_token %}
<p> <input type="text" name="name" placeholder="Ваше имя" maxlength="50" class="form-control" id="id_name"></p>
<p> <input type="text" name="phone" placeholder="Номер телефона. Обязательно" maxlength="50" class="form-control" required id="id_phone"></p>
<p> <input type="text" name="email" placeholder="email" maxlength="50" class="form-control" id="id_email"></p>
<p> <textarea name="body" cols="40" rows="10" placeholder="Текст сообщения. Обязательно" class="form-control" required id="id_body">
</textarea></p>
<p> <input type="file" name="files" multiple class="form-control" id="id_files"></p>
<button class="btn" type="submit">Отправить</button>
</form>