1
votes

I am new to django, I am sending a form data from my index.html(1st app 's template) file to accounts app's(another app) views.py

index.html - app01/templates

<!DOCTYPE html>
<html>
<head>
    <title>hello</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">


    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<style type="text/css">
    body{
        background-color: 'lightblue';
    }
</style>
</head>

<body>
<nav class="navbar navbar-inverse bg-faded">
<a class="navbar-brand" href="#about">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2a/Cyno_Small_Logo_(Aug._2015).png/240px-Cyno_Small_Logo_(Aug._2015).png" width="30" height="30" >

</a>
<div class="col-md-2 bg-warning"><h3>Quizapp</h3></div>

<div class="container off col-md-offset-2">
    <ul class="nav nav-tabs">
         <li><a data-toggle="tab" href="#regtab">New User? Register here!</a></li>  
        <li><a data-toggle="tab" href="#logtab">Already have an account? Login!</a></li>
    </ul>
</nav>
    <div class="tab-content">
        <div id="regtab" class="tab-pane fade text-primary">


    {% csrf_token %}

        {{ rform }}



    <button id="rbtn" type="button" class="btn btn-primary btn-lg ">Register!</button> 
        </div>
        <div id="logtab" class="tab-pane fade text-success" data- loading-text="Registering">

    {% csrf_token %}

        {{ lform.as_p }}



        <button id="lbtn" type="button" class="btn btn-primary btn-lg         " data-loading-text="Logging in" >Login!</button> 
        </div>
    </div>
 </div>




<script type="text/javascript">

$('#rbtn').click(function(){
    var form_data = {
        'username' : $('#id_username').val(),
        'password' : $('#id_password').val(),   
        'name' : $('#id_name').val()
    }
    $.post('/register_data/',form_data,function (data, status){
        var dt = JSON.parse(data);
        var reg_status = dt.data.status;
        if(reg_status == 'success'){
            alert("registered! click Ok to go to home");
            window.location = '/';
        }
        else{
            alert("check form bro!");
        }

    });
});

</script>
</body>

</html>

views.py - accounts

from django.shortcuts import render,redirect    
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt    
from app01.models import LoginForm,RegisterForm
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
import json
@csrf_exempt
def register_data(request):
    resp = {
        'status': ''
    }

    if not request.method == 'POST':
        resp['status'] = 'post req pls'
        return HttpResponse(json.dumps({'data': resp}))

    frm = RegisterForm(request.POST)

    if frm.is_valid():

        uname = frm.cleaned_data['username']
        ps = frm.cleaned_data['password']
        name = frm.cleaned_data['name']
        try:
            usr= User(username=uname)
            usr.set_password(ps)
            usr.save()


        except:
            resps['status']='user already exists'
            return HttpResponse(json.dumps({'data':resp}))

        myusr = MyUser(user=usr,name=name)
        myusr.save()
        return redirect('/')
        resp['status'] = 'success'
        return HttpResponse(json.dumps({'data':resp}))

Everytime I click the register button, the terminal returns 403 Forbidden Error, CSRF token missing or incorrect. I have already included {%csrf_token%} before form and also @csrf_exempt before the function.

The code is still under development (login function yet to be made), I am stuck until this register page sends request to the views.py/register_data

1

1 Answers

1
votes

You need to render your forms within form tags. See the docs: https://docs.djangoproject.com/en/1.10/topics/forms/#the-template

<form>
    {% csrf_token %}
    {{ rform }}
</form>
<form>
    {% csrf_token %}
    {{ lform.as_p }}
</form>