1

I'm brand-new in English, Python and Flask, and I'm sorry if I write really bad things.

I have the following task: when a user go to pfofile.html, the page is loaded with a value from the database. If the user changes the color, then the JavaScript function is started (onchange() is called). I have to write the code that changes the field text_color_in_chat in database. I thought that I did all right, but I have the following error: jinja2.exceptions.UndefinedError: 't' is undefined. And I don't understand how I can pass the "t" variable from JavaScript to Python using Flask, or how to properly call the braces shackle {{}}.

<script type="text/javascript" charset="utf-8">
function change_color(t) {
    alert( {{ current_user.change_color_in_db(t.value) }} );
}
</script>
<div>
    Check your color in chat:
    <input type="color" value="{{ user.text_color_in_chat }}" onchange="change_color(this);">
</div>

Here is a piece of my models.py:

...
text_color_in_chat = db.Column(db.String(8), default='#000000')
...
def change_color_in_db(self, new_color):
        # re.search(r'^#[0-9a-f]{6,6}$', "#000000"
        self.text_color_in_chat = new_color
        db.session.add(self)
        return True
...

And in my Python function, I'm testing the variable new_color with a RegEx. If it does not match it returns None, else it returns the object. And, I don't understand how to use a if condition.

4
  • Your English is not very good, but I do my best to translate your question. I think I have understand what you want. Just tell me if it's unclear. Commented Feb 24, 2017 at 22:27
  • how i can change field in database from js function "change_color()"? Commented Feb 24, 2017 at 22:34
  • and about RegEx i want to now how correctly to create condition if re.search(r'^#[0-9a-f]{6,6}$', str): change data in db else: not change and alert about error str. where "str" is expected color code in hexadecimal form. Commented Feb 24, 2017 at 22:43
  • wau, you correct my errors in question, thank you, may be now answer will be quickly found. Commented Feb 24, 2017 at 22:53

1 Answer 1

2

Let's see and understand the way a client/server application work:

From the user's browser:

  1. the user enter a value in a form;
  2. the user submit the form;
  3. the form data is posted to the server and wait for the response.

On the server:

  1. the server get the HTTP request and decode it;
  2. the URL is translated into a "route";
  3. the server call the function or method attached to the route;
  4. the function do it's job and must return a HTTP response (data + status code);
  5. the response (more often a HTML page) is sent back to the browser.

On the user's browser:

  1. the browser render the HTML page (or other kind of data);
  2. the user can then continue it's browsing.

… and the loop is done.

From the user's browser:

What you want is a way to register the user's change to database.

To do that, you can use a classic HTML form or an Ajax request. Since your are using JavaScript, an Ajax request is the best way to do that. For instance, you can use jQuery.post to do that:

Here is a draft:

<script type="text/javascript" charset="utf-8">
function change_color(t) {
    var url = "/route/to/change_color";
    var data = {color: $('#chat-color').val()};
    $.post(url, data);
}
</script>

This code get the value of the input field which id is #chat-color and post it to the URL "/route/to/change_color".

Of course, you need th change your HTML form like this to add the #chat-color id:

<div>
    Check your color in chat:
    <input id="chat-color" type="color" value="{{ user.text_color_in_chat }}" onchange="change_color(this);">
</div>

On the server:

You need to define a function for the route "/route/to/change_color".

The function could be:

import re
from flask import request

@app.route('/route/to/change_color', methods=['POST'])
def change_color():
    new_color = request.form['color']
    if re.match(r'^#[0-9a-f]{6,6}$', new_color):
        self.text_color_in_chat = new_color
        db.session.add(self)
        ...
    ...

Here is a small solution which use a global variable instead of a database (to keep it simple):

# coding: utf8
import json
import re
import textwrap

from flask import Flask
from flask import request

app = Flask(__name__)

text_color_in_chat = "#000000"


@app.route('/')
def hello_world():
    content = textwrap.dedent("""\
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script type="text/javascript" charset="utf-8">
    function change_color(t) {
        var url = "/route/to/change_color";
        var data = {color: $('#chat-color').val()};
        $.post(url, data);
    }
    </script>
    <div>
        Check your color in chat:
        <input id="chat-color" type="color" value="<color>" onchange="change_color(this);">
    </div>
    """)
    return content.replace("<color>", text_color_in_chat)


@app.route('/route/to/change_color', methods=['POST'])
def change_color():
    new_color = request.form['color']
    if re.match(r'^#[0-9a-f]{6,6}$', new_color):
        global text_color_in_chat
        text_color_in_chat = new_color
        return json.dumps({'change_color': "OK"})
    return json.dumps({'change_color': "Invalid color"})


if __name__ == '__main__':
    app.run(debug=True)
Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much, after I wrote the question, I started to think about Ajax, but not knew how do it correctly and now I understand))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.