VicenteC
VicenteC

Reputation: 422

How to handle POST form data with Django (refresh avoided)?

I'm trying to save the form's data in a database using Django. Refreshing after click on submit button is avoided using:

scripts.py

var form = document.getElementById("mail_form_id");
function handleForm(event) { event.preventDefault(); } 
form.addEventListener('submit', handleForm);



function send_mailform(){
    console.log("cal")
    var http = new XMLHttpRequest();
    http.open("POST", "", true);
    http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    var params = "search=" + document.getElementById('mail_input').value; 
    http.send(params);
    http.onload = function() {
        alert(http.responseText);
    }
}
document.getElementById("mail_send_btn").addEventListener('click', send_mailform, false);

views.py

    #Mail check
    if request.POST:
        Marketingform = Marketingforms(request.POST)
        if Marketingform.is_valid():
            receiver_mail = Marketingform.cleaned_data['receiver_mail']

            p = mail_receiver(receiver_mail=receiver_mail)
            p.save()
            print("correct")

views.py

class mailForm(forms.ModelForm):
    class Meta:
        model = mail_receiver
        fields =[
            'receiver_mail',
        ]
        widgets = {
            'receiver_mail': forms.EmailInput(attrs={ 'id':'mail_input', 'name':'mail_input'}),
        }

How can I receive the value of params in the django views.py?

Upvotes: 1

Views: 408

Answers (1)

Parsa Akbari
Parsa Akbari

Reputation: 118

First your ajax request is not going to work because of csrf token. you must have a request header with name: 'X-CSRFToken' and value of the csrftoken cookie that is in the browser cookies. You must get the csrftoken cookie value and set as the header value.
Header should look like:
http.setRequestHeader('X-CSRFToken', getCookie('csrftoken'));
And getCookie() must be function to get cookie value based on its name. Django has a clean doc about this:
https://docs.djangoproject.com/en/3.0/ref/csrf/
And the answer for your question is that request object contains the post data and you can have them like:
request.POST.get('param_name') This will return None if param_name doesn't exists. Also its better to check like:
if request.is_ajax():instead of if request.POST:

Upvotes: 1

Related Questions