Home > Software design >  Getting Django view dictionary key in Javascript, but instead of considering it a String, considers
Getting Django view dictionary key in Javascript, but instead of considering it a String, considers

Time:04-12

I am doing a project in Django. In my views I send data to the HTML pages with dictionaries. I can easily access that data on HTML, but when I try to access it on Javascript I can't because Javascripts thinks it's a variable name.

For example, I have a log in page. If the credentials are wrong, I send them to the same page and tell them that the username or password are wrong. I want to keep the previously written username on the form, so the person only needs to rewrite the password. I send the username from the view to the Javascript, but I can't access it.

My view code:

def login_form(request):
    assert isinstance(request, HttpRequest)
    if 'username' and 'password' in request.POST:
        user = request.POST['username']
        passw = request.POST['password']

        if rightcredentials(user,passw):
            tparams = {
                'message': 'login successful',
            }
            return render(request, 'about.html', tparams)
        else:
            tparams = {
                'login' : 'failure1',
                'username_info' : user
            }
            return render(request, 'login_form.html', tparams)

Javascript code:

{% if login == 'failure1' %}

    <form action="." method="post">
        {% csrf_token %}
            <div >
                <h3 >Sign Into Your Account</h3>
                <p>Wrong Username or password</p>
                <div >
                    <input type="text" value=""  name="username" id="username" placeholder="Username">
                </div>
                <div >
                    <input type="password"  name="password" placeholder="Password">
                </div>
                <button type="submit" >Log In</button>
            </div>
    </form>
    <script type="text/javascript">
        {% autoescape off %}
        var paramvalue = {{ username_info }}
        {% endautoescape %}

        document.getElementById("username").value = paramvalue; 
    </script> 

{%endif%}

After inserting username: 'pedro' and the wrong password on the form I get the following error:

Uncaught ReferenceError: pedro is not defined

Is there a way to access the string username_info or a way to convert the variable name to a string?

CodePudding user response:

Wrapping the {{ }} in quotation marks should do the trick

{% autoescape off %}
var paramvalue = "{{ username_info }}"
{% endautoescape %}
  • Related