如何从flask_colorpicker中获取RGB值并传递至后端?
Hey there! Since you’re already a pro with Python but just getting started with Flask, let’s walk through exactly how to get that RGB value from flask_colorpicker over to your backend—we’ll cover both the basic request approach and the WTForms method, since you tried both and hit snags.
Chances are, if the request module didn’t work for you, it was a small oversight in how the frontend form was set up. Let’s fix that first:
Frontend (template file, e.g., index.html)
Make sure your form uses POST method, and the color input has a clear name attribute (this is how Flask finds the value in the request):
<form method="POST" action="/process-color"> <!-- Use the color input type to trigger the browser's color picker --> <input type="color" name="selected_color" id="color-picker"> <button type="submit">Send Color to Backend</button> </form>
Backend (Flask app file)
Now use request.form.get() to grab the hex color value, then convert it to RGB if needed:
from flask import Flask, request, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') @app.route('/process-color', methods=['POST']) def process_color(): # Grab the hex color from the form data hex_color = request.form.get('selected_color') # Convert hex to RGB (since you need RGB values) def hex_to_rgb(hex_str): hex_str = hex_str.lstrip('#') return tuple(int(hex_str[i:i+2], 16) for i in (0, 2, 4)) rgb_values = hex_to_rgb(hex_color) print(f"Received RGB values: {rgb_values}") # Add your processing logic here (save to DB, generate output, etc.) return f"Success! RGB values received: {rgb_values}"
Key note: The name attribute in the input must match exactly what you pass to request.form.get()—this is the most common mistake for Flask newbies.
If you tried WTForms and it didn’t work, you probably missed setting the input type to color when rendering the field. Let’s do this correctly:
First, install Flask-WTF if you haven’t:
pip install flask-wtf
Step 1: Define the Form Class
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired class ColorPickerForm(FlaskForm): # Use StringField since color pickers return hex strings selected_color = StringField('Choose a Color', validators=[DataRequired()]) submit = SubmitField('Submit Color')
Step 2: Frontend Template (e.g., wtf_color.html)
Make sure to include the CSRF token with form.hidden_tag(), and set the field type to color:
<form method="POST" action="/process-wtf-color"> {{ form.hidden_tag() }} <!-- Required for CSRF protection --> <!-- Render the field as a color picker --> {{ form.selected_color(type='color', id='wtf-color-picker') }} {{ form.submit() }} </form>
Step 3: Backend Routes
@app.route('/wtf-color-picker') def wtf_color_picker(): form = ColorPickerForm() return render_template('wtf_color.html', form=form) @app.route('/process-wtf-color', methods=['POST']) def process_wtf_color(): form = ColorPickerForm() if form.validate_on_submit(): hex_color = form.selected_color.data # Convert to RGB same as before def hex_to_rgb(hex_str): hex_str = hex_str.lstrip('#') return tuple(int(hex_str[i:i+2], 16) for i in (0, 2, 4)) rgb_values = hex_to_rgb(hex_color) print(f"WTForms received RGB: {rgb_values}") return f"WTForms Success! RGB: {rgb_values}" # If validation fails, send back the form return render_template('wtf_color.html', form=form)
Critical fix: Without setting type='color' when rendering the field, WTForms will default to a text input, which won’t trigger the color picker or send the correct hex value.
- Open your browser’s dev tools (F12), go to the Network tab, and submit the form. Check the Form Data section to see if
selected_coloris being sent with a value. - In the backend, print the entire form data with
print(request.form)to confirm Flask is receiving the input. - Double-check that your route includes
methods=['POST']—Flask routes only accept GET requests by default.
内容的提问来源于stack exchange,提问作者Cole Hunter

