Show modal only if there is an active session

0

When someone registers your name and email I create a session and render the page with the name of who registered, but I can not understand how I do it so that the time I render the page again appears a modal .

views.py:

from django.shortcuts import render, redirect
from .models import *
from registrations.models import Group

def index(request):
    form = NewsletterForm(request.POST or None)
    group = Group.objects.filter(active=True).first()
    show_modal = False
    content = {'show_modal': show_modal, 'group': group, 'form': form}

    if not group:
        show_modal = True
        content = {'show_modal': show_modal, 'form': form}
        return render(request, 'index.html', content)


    if form.is_valid():
        contact = form.save()
        request.session['contact_id'] = contact.id
        request.session.set_expiry(100)

        if 'contact_id' in request.session:
            show_modal_contact = True
            content = {'contact': contact, 'show_modal': show_modal, 'group': group, 'show_modal_contact': show_modal_contact}
            return render(request, 'index.html', content)

        content = {'contact': contact, 'show_modal': show_modal, 'group': group, 'show_modal_contact': show_modal_contact}
        return render(request, 'index.html', content)

    return render(request, 'index.html', content)

Modal that I want to appear when saving and rendering the page again:

<!-- Modal Contato -->
{% if show_modal_contact %}
    <script type="text/javascript">
    setTimeout(function(){

        $(window).load(function(){        
            $('#modal_contato').modal('show');
        });

    }, 1000)
    </script>
{% endif %}

{% if show_modal_contact %}
<div id="modal_contato" class="modal fade in" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-body">
                <div class="row">
                    <div class="col-xs-12 col-sm-12 col-md-12">
                        <div class="text-center bottom-border">
                            <img class="img-modal" src="{% static 'images/ilustra3.png' %}" />
                        </div>
                        <p class="text-modal text-center">Pronto, iremos te avisar assim que abrirem novas turmas</p>
                        <div class="text-center">
                            <a id="close_modal" class="btn btn-primary btn-estacao">Voltar para Estação Hack Teens</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endif %}

I even read something about AJAX and such, but I could not put it into practice, can you guys give me any more help?

    
asked by anonymous 19.09.2018 / 16:04

1 answer

0

Well, seeing that the way I was trying I was not getting succesful, I solved the problem using ajax myself, follow the code.

views.py:

from django.shortcuts import render, redirect
from .models import *
from django.http import JsonResponse
import json
from registrations.models import Group

def index(request):
    form = ContactForm()
    group = Group.objects.filter(active=True).first()
    show_modal = False
    content = {'show_modal': show_modal, 'group': group, 'form': form}

    if not group:
        show_modal = True
        content = {'show_modal': show_modal, 'form': form}
        return render(request, 'index.html', content)

    return render(request, 'index.html', content)

def contact(request):
    data = json.loads(request.body)
    form = ContactForm(data)

    if form.is_valid():
        data = form.cleaned_data
        contact = Contact.objects.filter(email=data['email']).first()

        if contact:
            return JsonResponse({'contactRegistered': 'O e-mail já esta cadastrado'}, status=400)

        print(data['email']) 
        contact = form.save()   
        return JsonResponse({'success': True})

    return JsonResponse(form.errors, status=400)

main.js:

const formModal = document.querySelector('#modal_contato');
const modalButton = document.querySelector('#formPorDentro button');
const modalCloseButtons = document.querySelectorAll('#modal_contato button');

modalButton.onclick = showModal;

for(let button of modalCloseButtons){
    button.onclick = dismissModal;
}

window.onclick = function(event) {
    if (event.target === formModal) {
        dismissModal();
    }
}

function showModal(){
    formModal.style.display = 'flex';
    setTimeout(() => formModal.style.opacity = 1, 100);
}

function dismissModal(){
    formModal.style.opacity = 0;
    setTimeout(() => formModal.style.display = 'none', 1000);
}

function submitForm(){
    let inputs = document.querySelectorAll('#formPorDentro input');
    let data = {};
    let csrfToken;

    for(let input of inputs){
        if(input.type === 'text'){
            data[input.name] = input.value;
        }

        if(input.name === 'csrfmiddlewaretoken'){
            csrfToken = input.value;
        }
    }

    toogleVisibleModalContainer('#loading')

    fetch('/registrado', {
        method: 'POST',
        headers:{
          'Content-type': 'application/json',
          'X-CSRFToken': csrfToken
        },
        body: JSON.stringify(data)
      })
      .then(formSubmitSuccess)
      .catch(treatErrorResponse);
}

function formSubmitSuccess(response){
    if(response.status === 400){

        response.json().then(treatErrorResponse);
        return;
    }
      
    if(response.status === 200){
        response.json().then(treatSuccessResponse);
        return;
    }
      
      throw 'Invalid response from server';
}

function treatErrorResponse(data){
    let errors = Object.keys(data);
    let contactAlreadyRegistered = document.querySelector('#error');

    if(errors.indexOf('contactRegistered') > -1){
        contactAlreadyRegistered.style.display = 'block';
    }

    toogleVisibleModalContainer('#error');
}

function treatSuccessResponse(){
    toogleVisibleModalContainer('#success');
}

function toogleVisibleModalContainer(containerClass = ''){
    let containers = document.querySelectorAll('#modal_contato .modal-content');
    let activeContainer = document.querySelector('#modal_contato .modal-content${containerClass}');

    for(let container of containers){
        container.style.display = 'none';
    }

    activeContainer.style.display = 'block';

}

const sendButton = document.querySelector('#formPorDentro button');

sendButton.onclick = validateForm;

function validateForm(){
    if(validateContact()){
        showModal();
    }
}

function validateContact(){
    let contactEmail = document.querySelector('[name=email]');
    let contactName = document.querySelector('[name=name]');
    
    if(contactEmail.value == ''){
        contactEmail.classList.add('invalid');
    } if (contactName.value == ''){
        contactName.classList.add('invalid');
    } if (contactEmail.value != ''){
        contactEmail.classList.remove('invalid');
    } if (contactName.value != ''){
        contactName.classList.remove('invalid');
    } if(contactEmail.value != '' && contactName.value != ''){        
        submitForm();
        return true;
    }

    return false;
}

index.html:

<!-- Modal Contato -->
    <div id="modal_contato" class="modal fade in" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content" id="loading">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-xs-12 col-sm-12 col-md-12">
                            <div class="text-center bottom-border">
                                <img class="img-modal" src="{% static 'images/loading.gif' %}" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-content" id="success">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-xs-12 col-sm-12 col-md-12">
                            <div class="text-center bottom-border">
                                <img class="img-modal" src="{% static 'images/ilustra3.png' %}" />
                            </div>
                            <p class="text-modal text-center">Pronto, iremos te avisar assim que abrirem novas turmas!!!</p>
                            <div class="text-center">
                                <button type="button" class="btn btn-primary btn-estacao">Voltar para Estação Hack Teens</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-content" id="error">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-xs-12 col-sm-12 col-md-12">
                            <div class="text-center bottom-border">
                                <img class="img-modal" src="{% static 'images/ilustra3.png' %}" />
                            </div>
                            <p class="text-modal text-center">Já existe alguém cadastrado com esse e-mail</p>
                            <div class="text-center">
                                <button type="button" class="btn btn-primary btn-estacao">Voltar para Estação Hack Teens</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

That way I can do what I need.

    
20.09.2018 / 22:13