Show modal only if there is an active session

Asked

Viewed 97 times

0

When someone registers their name and email I create a session and I rescan the page with the name of who signed up, but I’m not able to understand how I do so that the time I rescan the page appears a modal.

py views.:

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 I want to appear when you save and render 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 in practice, will you be able to give me more this help?

  • Wouldn’t have to have the class in in modal for it to get already open? type class="modal fade in"

  • then @fernandosavio the problem that this modal can only be "open" when the person signs up after I use the command contact = form.save()&#xA; request.session['contact_id'] = contact.id&#xA; request.session.set_expiry(100) basically it is redirected then I would have a check if you have a session means that he has signed up so then yes should show the modal and not when the page loads

  • Is this validation done in the correct backend? The frontend only knows that if it receives a variable show_modal_contact the true modal should be shown, it is not?

  • exact @fernandosavio I’m doing so I’ll edit the post here to be better to view

  • Then the line {% if show_modal_contact %} will only send the modal HTML when it is required to be shown on the screen. As this modal will only exist when it needs to be shown, IE, will not be hidden waiting for its activation, would just insert the in same. Already tried to see if the behavior is not the desired?

  • worst I tried @fernandosavio as you can see ai edition I did, tested but it does not appear the modal I did a test with a Alert in function and worked, but with modal no kkkk

Show 1 more comment

1 answer

0


Good, seeing that the way I was trying I was not getting success, I solved the problem using same ajax, follows the code.

py views.:

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 needed to do.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.