I'm trying to replicate the live search option as described here https://developer.snapappointments.com/bootstrap-select/examples/ in my Flask application. The minimal example below has the third box hardcoded as in the example and it works as expected.
My actual app uses WTF forms/Jinga2 and I cannot figure out how to modify the Jinga2 code such that the live search would be available in my first SelectField or in the second SelectMultipleField.
Can someone suggest how I can implement a live search using the WTF form/Jinga2 to resemble the working example?
from flask import Flask, render_template, request, session, current_app, flash,redirect, url_for, jsonify
from flask_wtf import FlaskForm
from wtforms import StringField, TextField, SubmitField, SelectField, IntegerField, BooleanField, RadioField, FileField, HiddenField,SelectMultipleField
from wtforms.validators import DataRequired, Length
server = Flask(__name__)
server.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
class simpleForm(FlaskForm):
varlist1 = SelectField('Choose', [DataRequired()], coerce=str)
varlist2 = SelectField('Choose', [DataRequired()], coerce=str)
submitA = SubmitField('Get Stuff')
varlist3 = SelectMultipleField('Choose Test(s):', [DataRequired()], choices=[('', '')])
#server.route('/menu', methods=["post", "get"])
def menu():
form = simpleForm()
vars = ['Option 1','Option 2']
var2list = [['A', 'B', 'C'],['D','E', 'F', 'G'],['1', '2']]
vars3 = ['a','b','c','d']
form.varlist1.choices = vars
form.varlist2.choices = var2list[0]
form.varlist3.choices = [(i, i) for i in vars3]
#form.varlist2.choices = var2list[1]
#form.varlist2.choices = var2list[2]
return render_template('menu.html', form = form)
if __name__ == '__main__':
server.run(debug=True)
Here is a minimal html menu.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css" integrity="sha384-VCmXjywReHh4PwowAiWNagnWcLhlEJLA5buUprzK8rxFgeH0kww/aWY76TfkUoSX" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/js/bootstrap.min.js" integrity="sha384-XEerZL0cuoUbHE4nZReLT7nx9gQrQreJekYhJD9WNWhH8nEW+0c5qq7aIo2Wl30J" crossorigin="anonymous"></script>
</head>
<title>My Application</title>
<body>
<br><br><br>
<form action="{{url_for('menu')}}" method="POST" enctype="multipart/form-data">
<br>
<div>
{{ form.varlist2.label}}
{{ form.varlist2 (class="form-control") }}
<br>
{{ form.varlist3.label}}
{{ form.varlist3 }}
</div>
</form>
<br><br>
<select class="selectpicker" data-live-search="true">
<option data-tokens="ketchup mustard">Hot Dog, Fries and a Soda</option>
<option data-tokens="mustard">Burger, Shake and a Smile</option>
<option data-tokens="frosting">Sugar, Spice and all things nice</option>
</select>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.14/dist/css/bootstrap-select.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.14/dist/js/bootstrap-select.min.js"></script>
<!-- (Optional) Latest compiled and minified JavaScript translation files -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.14/dist/js/i18n/defaults-*.min.js"></script>
</body>
</html>
A little late but here is an answer if someone else is having the same issue.
In your Jinja template, you need to replace:
{{ form.varlist2 (class="form-control") }}
with:
<select class="selectpicker form-control" name="varlist2" data-live-search="true">
{% for option in form.varlist2 %}
{{ option }}
{% endfor %}
</select>
Related
I have a page where it allows the user to enter the reception number, so when the user enter the reception number, it should verify with the database if the reception number exist, but i am having this error: 'verifyForm' object has no attribute 'reception'. How do I solve this error?
Updated with traceback error
views.py
#login_required()
def verifydetails(request):
if request.method == 'POST':
#Customername = request.GET['Customername']
form = AddForm(request.POST or None)
if form.reception == Photo.reception:
messages.success(request, 'Both Reception and customer name match')
return redirect('AddMCO')
else:
messages.success(request, 'Both Reception and customer do not match')
return redirect('verifydetails')
else:
form = AddForm()
return render(request, 'verifydetails.html', {'form': form, })
forms.py
class verifyForm(forms.Form):
reception = forms.CharField(label='',
widget=forms.TextInput(
attrs={"class": 'form-control', 'placeholder': 'Enter Reception number'}))
class meta:
model = Photo
fields = ('reception')
verifydetails.html
<!DOCTYPE html>
<html>
<head>
<script>
$(function () {
$("#datetimepicker1").datetimepicker();
});
</script>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>SCS verify details</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
<!-- Font Awesome -->
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<!-- Moment.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js" integrity="sha256-VBLiveTKyUZMEzJd6z2mhfxIqz3ZATCuVMawPZGzIfA=" crossorigin="anonymous"></script>
<!-- Tempus Dominus Bootstrap 4 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.1.2/css/tempusdominus-bootstrap-4.min.css" integrity="sha256-XPTBwC3SBoWHSmKasAk01c08M6sIA5gF5+sRxqak2Qs=" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.1.2/js/tempusdominus-bootstrap-4.min.js" integrity="sha256-z0oKYg6xiLq3yJGsp/LsY9XykbweQlHl42jHv2XTBz4=" crossorigin="anonymous"></script>
</head>
{% if messages %}
{% for message in messages %}
<div class="alert alert-danger" role="alert">
<button type = "button" class="close" data-dismiss = "alert">x</button>
{{ message }}
</div>
{% endfor %}
{% endif %}
<body class="m-5">
<div class="container">
<div class="row justify-content-center">
<div class="col-md-4">
<h3>Verify Details</h3>
Go Back
<div class="card" style="width: 400px">
<form method="post">
{% csrf_token %}
<div class="form-group m-3">
<label>Reception:</label>
<br>
{{ form.reception}}
</div>
<button type='submit' class="btn btn-primary m-3">Submit</button>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
traceback error in my code is this:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/verifydetails/
Django Version: 2.2.20
Python Version: 3.8.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'account.apps.AccountConfig',
'crispy_forms']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django_session_timeout.middleware.SessionTimeoutMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
21. return view_func(request, *args, **kwargs)
File "E:\Role_based_login_system-master\account\views.py" in verifydetails
496. if form.reception == Photo.reception:
Exception Type: AttributeError at /verifydetails/
Exception Value: 'verifyForm' object has no attribute 'reception'
form = AddForm(request.POST or None) This line says that form can also be None if object is not found.
You're trying to run this line if form.reception == Photo.reception: before checking if form is valid or None.
To solve this problem, do something like:
if form:
if form.reception == Photo.reception:
........
else(optional):
print("the object doesn't exist")
Change form.reception to form.cleaned_data["reception"]
Problem: My Bokeh plot, implemented with Flask, is not showing in my browser. When I run the app, the Bokeh frame (with the tools), as well as the x-axis label show up, but no data is plotted inside.
Already tried: I've made sure that the Bokeh version mentioned in the HTML files is as others have suggested. I'm pretty sure I've exhausted the SO solutions presented already. I've used print statements throughout the program and determined that the data is actually collected, cleaned, and processed with the components module and passed to 'script'. So therefore, as far as I can tell, the code seems to be stuck at the 'last render_template line?
from flask import Flask, render_template, request, redirect, session
import pandas as pd
import quandl
from bokeh.plotting import figure, output_file, save
from bokeh.embed import components
from bokeh.io import show
app = Flask(__name__) #create an instance of the flask class (named 'app') in the current file
app.vars={}
#app.route('/')
def main():
return redirect('/index')
#app.route('/index', methods=['GET'])
def index():
return render_template('index.html')
#app.route('/plot', methods=['POST'])
def plot():
app.vars['current_symbol'] = request.form['current_symbol']
quandl.ApiConfig.api_key = 'CD38JS9JqAdmdeio9JPW'
req_data = quandl.get_table('WIKI/PRICES', ticker=app.vars['current_symbol'], qopts = {'columns':['ticker', 'date', 'adj_close']}, date = {'gte': '2017-11-01', 'lte': '2017-12-01'}, paginate = True)
req_data.adj_close = round(req_data.adj_close, 2)
req_data = req_data.set_index('date')
cleaned_data = req_data.pivot(columns = 'ticker')
# Plot the data
p = figure(x_axis_type='datetime', x_axis_label='Date', y_minor_ticks=2, plot_width = 800, plot_height = 600)
p.line(x = cleaned_data.index, y = cleaned_data.adj_close, line_width = 2)
script, div = components(p)
return render_template('plot.html', script=script, div=div)
if __name__ == "__main__":
app.run(debug=True)
Here are the accompanying HTML files.
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Stock Plotter</title>
<link href="https://cdn.bokeh.org/bokeh/release/bokeh-1.2.0.min.css" rel="stylesheet" type="text/css">
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-1.2.0.min.js"></script>
<!-- <link rel="icon" href="favicon.ico"> -->
<title>Stock Plotter</title>
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class=metanav>
<h1>Stock Plotter</h1>
<div>
<form id="tickerform" action="/plot" method="POST">
Ticker Symbol: <input type="text" name="current_symbol" placeholder="ticker symbol"></input> <!--Create a dropdown list with the following options=-->
<div>
<input type="submit" value="Submit"></input> <!--Create the submit button-->
</div>
</form>
</div>
{{ script|safe }} <!--Marks the js scrips as safe for the web-->
{{ div|safe }}
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
plot.html
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="https://cdn.bokeh.org/bokeh/release/bokeh-1.2.0.min.css" rel="stylesheet" type="text/css">
<script src="https://cdn.bokeh**strong text**.org/bokeh/release/bokeh-1.2.0.min.js"></script>
<title>Stock Plotter</title>
</head>
<body>
<div class=page>
<h1>Stock Plotter</h1>
{{ script|safe }}
{{ div|safe }}
</div>
</body>
</html>
I expect the plot to be visible, but it's not.
No error messages are shown in the console.
Check this post:
Embedding multiple bokeh HTML plots into flask
It has a great example as to how to display bokeh figures in flask apps.
For anyone looking for an answer, the problem with this code is that the plot definition (p.line...) has some problem with my defining the x and y values explicitly. Once I used the source argument, the plot appears as desired.
I am making a local page following this tutorial, and it implements a login using django and angular. But I can't get the button register to show anything. It just changes the directory to /register. I think it has to do with routing. I get no errors. And I don't know how to debug this thing anymore, so I've run out of options. This is my first 'website'.
Reason this isn't going smooth is because I did not get the starter project the tutorial came with. I wanted to learn how to implement this from scratch. This means my packages are newer (bootstrap, django, etc). Let me know if you need any more info, please. Thanks.
/templates/index.html
<!DOCTYPE html>
<html ng-app="hawk">
<head>
<title>Hawk</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body>
{% include 'navbar.html' %}
<div class="container-fluid">
<div class="row">
<div class="col-xs-12 ng-view"></div>
</div>
</div>
{% include 'javascripts.html' %}
</body>
</html>
/static/javascripts/hawk.routes.js
(function () {
'use strict';
angular
.module('hawk.routes')
.config(config);
config.$inject = ['$routeProvider'];
function config($routeProvider) {
$routeProvider.when('/register', {
controller: 'RegisterController',
controllerAs: 'vm',
templateUrl: '/static/templates/authentication/register.html'
}).otherwise('/');
}
})();
/static/javascripts/authentication/controllers/register.controller.js
(function () {
'use strict';
angular
.module('hawk.authentication.controllers')
.controller('RegisterController', RegisterController);
RegisterController.$inject = ['$location', '$scope', 'Authentication'];
function RegisterController($location, $scope, Authentication) {
var vm = this;
console.log("\n\nregister\n\n");
vm.register = register;
function register() {
Authentication.register(vm.email, vm.password, vm.username);
}
}
})();
/static/javascripts/hawk.js
(function () {
'use strict';
angular
.module('hawk', [
'hawk.routes',
'hawk.authentication',
'hawk.config',
]);
angular
.module('hawk.routes', [require('angular-route')]);
angular
.module('hawk.config', []);
angular
.module('hawk')
.run(run);
run.$inject = ['$http'];
function run($http) {
$http.defaults.xsrfHeaderName = 'X-CSRFToken';
$http.defaults.xsrfCookieName = 'csrftoken';
}
})();
/templates/javascripts.html
{% load compress %} {% load staticfiles %} {% compress js %}
<script type="text/javascript" src="{% static '../node_modules/jquery/dist/jquery.js' %}"></script>
<script type="text/javascript" src="{% static '../node_modules/bootstrap/dist/js/bootstrap.js' %}"></script>
<script type="text/javascript" src="{% static '../node_modules/bootstrap-material-design/dist/js/material.js' %}"></script>
<script type="text/javascript" src="{% static '../node_modules/bootstrap-material-design/js/ripples.js' %}"></script>
<script type="text/javascript" src="{% static '../node_modules/underscore/underscore.js' %}"></script>
<script type="text/javascript" src="{% static '../node_modules/angular/angular.js' %}"></script>
<script type="text/javascript" src="{% static '../node_modules/angular-route/angular-route.js' %}"></script>
<script type="text/javascript" src="{% static '../node_modules/angular-cookies/angular-cookies.js' %}"></script>
<script type="text/javascript" src="{% static '../node_modules/ng-dialog/js/ngDialog.js' %}"></script>
<script type="text/javascript" src="{% static 'lib/snackbarjs/snackbar.min.js' %}"></script>
<script type="text/javascript" src="{% static 'javascripts/hawk.js' %}"></script>
<script type="text/javascript" src="{% static 'javascripts/hawk.config.js' %}"></script>
<script type="text/javascript" src="{% static 'javascripts/hawk.routes.js' %}"></script>
<script type="text/javascript" src="{% static 'javascripts/authentication/authentication.module.js' %}"></script>
<script type="text/javascript" src="{% static 'javascripts/authentication/services/authentication.service.js' %}"></script>
<script type="text/javascript" src="{% static 'javascripts/authentication/controllers/register.controller.js' %}"></script>
{% endcompress %}
/static/javascripts/authentication/services/authentication.service.js
(function () {
'use strict';
angular
.module('hawk.authentication.services')
.factory('Authentication', Authentication);
Authentication.$inject = ['$cookies', '$http'];
function Authentication($cookies, $http) {
var Authentication = {
register: register
};
return Authentication;
function register(email, password, username) {
return $http.post('/api/v1/accounts/', {
username: username,
password: password,
email: email
});
}
}
})();
/HawkProject/urls.py
from django.contrib import admin
from django.urls import path, re_path, include
from rest_framework_nested import routers
from authentication.views import AccountViewSet
from HawkProject.views import IndexView
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^api/v1/', include(router.urls)),
re_path(r'^.*$', IndexView.as_view(), name='index')
]
Although its not an answer to this question precisely but its an answer with a diff approach
The tutorial you have provided is too long and not included with video. I have worked on Django and AngularJS to create an ecommerce website. I'l suggest you not to mix Django and AngularJS as much as you can to avoid conflicts. That being said, I'll provide you what I implemented for User Registration in brief:
I kept User form separate from AngularJS forms because Django has its own way to handle User Management (Sign in,sign Up, session (using #login_required) etc).
I provided Register on the nav-bar. (Note: /signup is a url mapped in urls.py file)
<form name="regForm" class="form-signup" action="/sign_up/" method="post" role="form" onsubmit="return validateForm()">
{% csrf_token %}
{{form.errors.values.0}}
<div class="form-group reg-username" id="fname">
<div>
<input name="first_name" class="form-control input" size="20" placeholder="Enter First Name" type="text" required>
</div>
<p id="fname-error" class="help-block"></p>
</div>
<div class="form-group reg-username">
<div>
<input name="last_name" class="form-control input" size="20" placeholder="Enter Last Name" type="text" required>
</div>
</div>
<div class="form-group reg-email">
<div>
<input name="email" class="form-control input" placeholder="Enter Email" type="email" required>
</div>
</div>
<div class="form-group reg-password" id="pwd1">
<div>
<input name="password1" class="form-control input" placeholder="Password" type="password" required>
</div>
<p id="pwd-error1" class="help-block"></p>
</div>
<div class="form-group reg-password" id="pwd2">
<div>
<input name="password2" class="form-control input" placeholder="Confirm Password" type="password" required>
</div>
<p id="pwd-error2" class="help-block"></p>
</div>
<input name="submit" class="btn btn-block btn-lg btn-primary" value="REGISTER" type="submit">
</form>
Where url(r'^sign_up/', ('ecommerce.views.register_user')),
In the views.py
#sensitive_post_parameters()
#csrf_protect
#requires_csrf_token
def register_user(request):
args = {}
args.update(csrf(request))
if request.method == 'POST':
if not verify_google_recaptcha(request.POST):
return HttpResponse(get_status_response('Failure', 'Are you sure you are not a robot?'))
else:
logger.info('Recaptcha passed !!!')
form = RegistrationForm(request.POST)
msg = 'register'
args['form'] = form
if form.is_valid():
try:
# username = form.cleaned_data['username']
email_obj ={}
email_obj['email'] = form.cleaned_data['email']
email_obj['first_name'] = form.cleaned_data['first_name']
email_obj['last_name'] = form.cleaned_data['last_name']
salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
activation_key = hashlib.sha1(salt + email_obj['email']).hexdigest()
email_obj['activation_link'] = ACTIVATION_LINK.format(activation_key)
template = get_template('RegistrationLink.html')
context = Context({'email': email_obj})
content = template.render(context)
emsg = EmailMultiAlternatives('Activation link for {0}'.format(DEFAULT_DOMAIN) , content, DEFAULT_FROM_EMAIL, to=[email_obj['email']])
emsg.attach_alternative(content, "text/html")
emsg.send()
form.save() # save user to database if form is valid
# Get user by username
user = SiteUser.objects.get(email=email_obj['email'])
# Create and save user profile
new_profile = UserProfile(user=user, activation_key=activation_key,
key_expires=settings.EXPIRATION_DAYS)
new_profile.save()
except Exception as e:
logger.exception(e)
return render_to_response('500.html')
# return HttpResponseRedirect('/register_success')
return render_to_response('confirm.html', {'msg': msg})
else:
args['form'] = RegistrationForm()
return render_to_response('userRegistration.html', args, context_instance=RequestContext(request))
Note: The code written in def register_user is core Djnago feature to handle user registration which I am exploiting. You can get these over internet
If you need to render any form such as Order address, then create a form of angular and simple pass the value to Django using $http (the /url_called from $http will be mapped in urls.py).
Make sure you are using {% verbatim %} and {% endverbatim %} whenever you are using {{ some_angular_variable }} because it contradicts withDjango Templatesyntax. Better to go forng-bind` as much as you can.
Ignore $locationProvider for now if you are in initial stage. You'll get some issues when using that with Django. I have a solution for that as well but for beginner, dont get into that. Try to integrate the plunkr code in your Django app and see if it's working. Start small, dont jump to complicated examples.
Check one basic example of ngRoute.
In case you get stuck, post another question and put the link in the comment so that I can help you in that as well
I am following this video to create an image gallery using flask and python https://www.youtube.com/watch?v=yO_XNCsBIsg&t=636s
I these github files for (coppied the #app.route('/gallery')) app.py and gallery.html and ran the exact code but I am getting an error:
werkzeug.routing.BuildError: Could not build url for endpoint 'send_image' with values ['filename']. Did you mean 'index' instead?
Here is my exact code
main.py
#!/usr/bin/env python
from flask import Flask, request, send_from_directory, flash, redirect, render_template, request, url_for,jsonify
#https://stackoverflow.com/questions/32019733/getting-value-from-select-tag-using-flask
# reference to code is from https://pythonprogramming.net/jquery-flask-tutorial/
# and from https://www.blog.pythonlibrary.org/2017/12/13/flask-101-how-to-add-a-search-form/
app = Flask(__name__)
# this runs in the background for registering the compnay link that was put in
#app.route('/background_process')
def background_process():
lang = request.args.get('proglang', 0, type=str)
#just checking what was typed, this will be put into a python code eventrually
return jsonify(result=lang)
#app.route('/')
def index():
return render_template('interactive.html', data=[{'name':'red'}, {'name':'green'}, {'name':'blue'}])
filename = request.args.get('proglang')
#app.route("/black" , methods=['GET', 'POST'])
def black():
select = request.form.get('comp_select')
if select=="blue":
return(str("hi")) # just to see what select is
else:
return(str("bye"))
import os
#app.route('/gallery')
def get_gallery():
image_names = os.listdir('./images')
print(image_names)
return render_template("gallery.html", image_names=image_names)
if __name__=='__main__':
app.run(host='127.0.0.1', port=8080, debug=True)
gallery.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Thumbnail Gallery</h1>
</div>
{{image_names}}
<hr>
{% for image_name in image_names %}
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<img class="img-responsive" src=" {{url_for('send_image', filename=image_name)}}">
</div>
{% endfor %}
</div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"
integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS"
crossorigin="anonymous"></script>
</body>
</html>
I'm leaving out my other html files because they aren't needed for my testing of the gallery route.
You are missing the "send_image" route in your Python code:
#app.route('/upload/<filename>')
def send_image(filename):
return send_from_directory("images", filename)
I have two html templates, with index.html extending base.html
base.html is like this:
{{ define "base" }}
<html>
<head>
<meta charget="utf-8">
<title>{{ template "title" . }}</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/js/isotope.pkgd.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="/css/style.css">
</head>
<body>
{{ template "index" . }}
</body>
</html>
{{ end }}
And index.html:
{{ define "title" }}Homepage{{ end }}
{{ define "index" }}
<div class="wrapper">
<div class="page-content">
<div class="container">
<div class="left">
<img src="../public/images/img_landing_page_mac.png">
</div>
<div class="right">
<h2 style="font-size: 33px; letter-spacing: 5px">Organize <br>Modern Knowledge<br> for Mankind</h2>
<p style="font-size: 20px;margin-top: 35px;letter-spacing: 4px">Consume, Colect and Revisit <br>Knowledge at Your Fingertips</p>
<img src="../public/images/btn_get_chrome.png">
</div>
</div>
</div>
</div>
{{ end }}
It should render when requesting path on browser with a callback handler:
func IndexHandler(w http.ResponseWriter,r *http.Request){
files:=[]string{"base","index"}
util.RenderTemplate(w,nil,files...)
}
RenderTemplate is a wrapper function to render
func RenderTemplate(w http.ResponseWriter,data interface{},tmpl... string){
cwd,_:=os.Getwd()
files:=make([]string, len(tmpl))
for i,file:=range tmpl{
files[i]=filepath.Join(cwd,"./view/"+file+".html")
}
t,err:=template.ParseFiles(files...)
if err!=nil{
http.Error(w,err.Error(),http.StatusInternalServerError)
return
}
templates:=template.Must(t,err)
err=templates.Execute(w,data)
if err!=nil {
http.Error(w,err.Error(),http.StatusInternalServerError)
}
}
After I start server, I request that path on browser, but nothing is rendered at all. What am I missing? It seems that no inheritance is comprehended here
I follow this tutorial, trying to render templates with inheritance / extension:
https://elithrar.github.io/article/approximating-html-template-inheritance/
The define action doesn't execute template, only template and block actions do. Most probably you just want to remove define from your base template (first and last lines) and it will work as expected.
Or you can use Template.ExecuteTemplate function instead of Template.Execute. It accepts name of the template:
err = templates.ExecuteTemplate(w, "base", data)
Or if you are using Go1.6 or newer you can try block action instead of define.
On the side note, please, consider using gofmt.