The view definitely does not populate on my end but password_reset_confirm.html in the demo template folder seems to do that.
password_reset_confirm_form.html
urls.py
path("dj-rest-auth/password/reset/confirm/<str:uid>/<str:token>/",
# TemplateView.as_view(template_name="password_reset_confirm.html"),
PasswordResetConfirmView.as_view(),
name='resend-email-verification'
),
Edit: maybe this webpage here is not the same page in django-rest-auth demo folder.
In django, it is defined as (in django code):
urls.py
path('reset/<uidb64>/<token>/',views.PasswordResetConfirmView.as_view(),name='password_reset_confirm'),
path('reset/done/',views.PasswordResetCompleteView.as_view(),name='password_reset_complete')
Then, you can customize according to your need and override it by inheriting it in your own views.py file.
Answer credits to GitHub user, riteshbisht.
What I am seeing is UI of browsable API of django rest framework that does not have this functionality for reading url and populating form field unless I tell it to.
For it to do this, I created templates/rest_framework/api.html file and inserted following code inside it:
api.html
{% extends "rest_framework/base.html" %}
{% block style %}
{{ block.super }}
<style>
#btn-link {
border: none;
outline: none;
background: none;
display: block;
padding: 3px 20px;
clear: both;
font-weight: 400;
line-height: 1.42857143;
color: #A30000;
white-space: nowrap;
width: 100%;
text-align: left;
}
#btn-link:hover {
background: #EEEEEE;
color: #C20000;
}
</style>
{% endblock %}
{% block userlinks %}
{% if user.is_authenticated or response.data.access_token %}
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
{% firstof user.username 'Registered' %}
<b class="caret"></b>
</a>
<ul class="dropdown-menu dropdown-menu-right">
{% url 'rest_user_details' as user_url %}
<li>User</li>
<li>
{% url 'rest_logout' as logout_url %}
<form action="{{ logout_url }}" method="post">
{% csrf_token %}
<button type="submit" id="btn-link">Logout</button>
</form>
</li>
</ul>
</li>
{% else %}
{% url 'rest_login' as login_url %}
<li>Login</li>
{% url 'rest_register' as register_url %}
<li>Register</li>
{% endif %}
{% endblock %}
{% block script %}
{{block.super}}
<script type="text/javascript">
var url_elements = window.location.pathname.split('/');
if (url_elements.length >= 3){
var uid = url_elements[url_elements.length - 3];
if (uid !== undefined){
$('input[name=uid]').val(uid);
}
var token = url_elements[url_elements.length - 2];
if (token !== undefined){
$('input[name=token]').val(token);
}
}
</script>
{% endblock %}
Related
I need to render my MPTT model as tree with dropdown (open/close every node that contains children) possibility and buttons that will open/close all the nodes in that tree in 1 click.
I tried to find some ready-to-use examples, but best that I found is this:
<ul class="navbar-nav mr-auto">
{% recursetree thecategories %}
{% if node.level == 0 %}
{% if not node.is_leaf_node %}
<!-- Let op: <li> tag wordt steeds onderaan aangevuld, ander werkt het niet...-->
<li class="dropdown nav-item">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
aria-expanded="false">
<span class="mainBarItem">{{ node.ctg_Title }}<span class="caret"></span> </span></a>
{% else %}
<li>{{ node.ctg_Title }}
{% endif %}
{% else %}
{% if not node.is_leaf_node %}
<li class="dropdown-submenu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
aria-expanded="false">
<span class="nav-label">{{ node.ctg_Title }}<span class="caret"></span></span></a>
{% else %}
<li>{{ node.ctg_Title }}
{% endif %}
{% endif %}
{% if not node.is_leaf_node %}
<ul class="children dropdown-menu">
{{ children }}
</ul>
{% endif %}
</li>
{% endrecursetree %}
</ul>
with some CSS and JS, but it is not that I need.
Actually I need to render just one tree at a time. I'm passing variable {{ product }} in my template that is just a root node. And for now I have this code from MPTT docs example that just render it as a list:
{% for product,structure in product.get_family|tree_info %}
{% if structure.new_level %}
<ul>
<li>{% else %}</li>
<li>{% endif %}
{% if product.purchased %}
<span style="color: #f5e642">{{ product.code }}</span>
{% else %}
{{ product.code }}
{% endif %}
{% for level in structure.closed_levels %}</li></ul>{% endfor %}
{% endfor %}
Also tried Nestable2, but it doesn't work for me, and IDK why. It renders as it should with drag and drop possibility but without possibility to open/close parent nodes (buttons are rendered but doesn't work).
I'm weak at front end development (Know just the basics of JS).
I thought maybe I can use some ready-to-use components in Jquery or Vue.js or anything else? Or will it be easier just in vanilla js? I appreciate any help and advices.
If anyone interested in how I did it, here is a simple code:
HTML
<ul id="myUL">
{% recursetree product.get_family %}
<li>
{% if node.is_leaf_node %}
<span class="leaf">{{ node.code }}</span>
{% else %}
<span class="caret parent">{{ node.code }}</span>
<ul class="nested">
{{ children }}
</ul>
{% endif %}
</li>
{% endrecursetree %}
</ul>
CSS
ul, #myUL {
list-style-type: none;
}
/* Remove margins and padding from the parent ul */
#myUL {
margin: 0;
padding: 0;
}
/* Style the caret/arrow */
.caret {
cursor: pointer;
user-select: none; /* Prevent text selection */
}
/* Create the caret/arrow with a unicode, and style it */
.caret::before {
content: "\25B6";
color: black;
display: inline-block;
margin-right: 6px;
}
/* Rotate the caret/arrow icon when clicked on (using JavaScript) */
.caret-down::before {
transform: rotate(90deg);
}
/* Hide the nested list */
.nested {
display: none;
}
/* Show the nested list when the user clicks on the caret/arrow (with JavaScript) */
.active {
display: block;
}
Javascript
'use strict';
var togglers = document.getElementsByClassName("caret");
var i;
for (i = 0; i < togglers.length; i++) {
togglers[i].addEventListener("click", function () {
this.parentElement.querySelector(".nested").classList.toggle("active");
this.classList.toggle("caret-down");
});
}
I am trying to pass one parameter from text input form into my app.py but i got the following error message:
Method Not Allowed
The method is not allowed for the requested URL.
Herewith my app.py configuration:
#main_blueprint.route('/reports/daily_reports')
def downloadsss():
if request.method == 'GET':
daily_path = "./app/templates/Repo/DailyReports"
daily_listOfFiles = os.listdir(daily_path)
return render_template('main/DailyReports.html', len = len(daily_listOfFiles), daily_listOfFiles
= daily_listOfFiles)
elif request.method == 'POST' and 'download' in request.form:
download = request.form.get('download')
path = 'C:/Users/Ahmed Mustafa/FlaskProject/app/templates/Repo/DailyReports/' + download
return send_file(path, as_attachment=True)
and the following is my HTML code:
{% extends "main/main_base.html" %} {# main/main_base.html extends layout.html #}
{% block content %}
<head>
<style>
body {background-color: powderblue;}
h1 {color: blue;}
p {color: red;}
h2 {color: black; font-size: 20px; font-family: "Lucida Sans Unicode", "Lucida Grande", sans-
serif;}
th {vertical-align: top; align-items: center;}
table{align-items: center; }
</style>
<div class="jumbotron text-center">
<p><font size="6">This page is to show the Daily Reports list!</font></p>
<form method="post">
<input type="text" name="download" />
<input type="submit" value="Download" />
</form>
<!-- For loop logic of jinja template -->
<li class="list-group-item"><font size="6">
{% print('Total Number of Reports:'), len %}</font></li>
<div align="left" >
{%for i in range(0, len)%}
{% print('Report Number:'),[i+1] %}
<li class="list-group-item">
<a href="file:///C:/Users/Ahmed
Mustafa/FlaskProject/app/templates/static/DailyReports/{{daily_listOfFiles[i]}}">
{{daily_listOfFiles[i]}}</a>
<p> </p>
<h2></h2>
</li>
{% endfor %}
</div>
</div>
{% endblock %}
You need to allow for a POST request on your route by adding POST to the methods argument of the route:
#main_blueprint.route('/reports/daily_reports', methods=('GET', 'POST'))
while running flask server throwing this error Uncaught TypeError: Cannot read property 'firstChild' of null at Object._.Og (js?key=AIzaSyAbZKo3h1LVhyoURgxcSUG9BGVvZtZpg0U:88) at new Sg (js?key=AIzaSyAbZKo3h1LVhyoURgxcSUG9BGVvZtZpg0U:89)
I'm new google maps in Python-Flask.google map is not showing while running the Flask localhost server.but,it showing while running the template.i'm not aware where i have mistaken in my source code. I need only show the map in between the empty place. here is the dashboard where place be the map here
yesterday i posted answer that is working.but it's showing like Uncaught TypeError: Cannot read property 'firstChild' of null at Object._.Og (js?key=AIzaSyAbZKo3h1LVhyoURgxcSUG9BGVvZtZpg0U:88) at new Sg (js?key=AIzaSyAbZKo3h1LVhyoURgxcSUG9BGVvZtZpg0U:89) where is the problem
Here is the google map code:
{% extends "base.html" %}
{% block head %}
{{super()}}
{% endblock %}
{% block navbar %}
{{super()}}
{% endblock %}
{% block content %}
<div class="row">
<ol class="breadcrumb">
<li><a href="#">
<em class="fa fa-home"></em>
</a></li>
<li class="active">Locations>create locations</li>
</ol>
</div><!--/.row-->
<div class="row">
<div class="col-md-6">
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDv8X0eEAWUtWZrHG_1XLB8gMNxgdcD0-U"></script>
<script >
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(17.3850, 78.4867),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow()
var name;
var lat;
var lng;
var latlngbounds = new google.maps.LatLngBounds();
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
google.maps.event.addListener(map, 'click', function (e) {
var latlng = new google.maps.LatLng(e.latLng.lat(), e.latLng.lng());
var geocoder = geocoder = new google.maps.Geocoder();
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: 'Hello World!'
});
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
name= results[1].formatted_address;
lat=e.latLng.lat();
lng=e.latLng.lng();
alert("Location: " +name + "\r\nLatitude: " + lat + "\r\nLongitude: " +lng );
document.getElementById("loc").value=name;
document.getElementById("lat").value=lat;
document.getElementById("lng").value=lng;
}
}
});
});
}
</script>
<!--<div id="dvMap" style="width: 50%; height: 50%">-->
<!--</div>-->
<form role="form" action="/post/locations" method="post" >
<input type="text" id="loc" name="name" class="form-control"/>
<input type="text" name="latitude" id="lat" class="form-control"/>
<input name="longitude" id="lng" type="text" class="form-control"/>
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</form>
</div>
</div>
<div id="dvMap" style="width: 80%; height: 70% ">
</div>
{% endblock %}
Here is the Python code:
#app.route('/page/locations')
def location():
if session['username']:
return render_template('map.html',user=session['username'])
else:
print ('login first!')
return redirect('/dashboard')
I just found the answer.Here it is my answer.
{% extends "base.html" %}
{% block head %}
{{super()}}
{% endblock %}
{% block navbar %}
{{super()}}
{% endblock %}
{% block content %}
<div class="row">
<ol class="breadcrumb">
<li><a href="#">
<em class="fa fa-home"></em>
</a></li>
<li class="active">Locations>Create Locations</li>
</ol>
</div><!--/.row id="entry.id" id="uploadbanner"-->
<div id="dvMap" style="width: 100%; height: 100%">
</div>
<form role="form" action="/post/locations" method="post">
<label>Name:</label>
<input type="text" id="loc" name="name"/>
<label>Latitude:</label>
<input type="text" name="latitude" id="lat"/>
<label>Longitude:</label>
<input name="longitude" id="lng" type="text"/>
<input type="submit" class="btn btn-primary" value=" Submit ">
<input type="reset" class="btn btn-default" value="Reset">
</form>
{% endblock %}
I just add the script in Javascript folder .
as a like <--static/assets/js/map.js --> in my template base.html source code.
The problem with your code is the javascript snippet is getting executed before the div element ( one with id="dvMap" ) is created. So either place the javascript snippet after the div element like below,
{% extends "base.html" %}
{% block head %}
{{super()}}
{% endblock %}
{% block navbar %}
{{super()}}
{% endblock %}
{% block content %}
<div class="row">
<ol class="breadcrumb">
<li><a href="#">
<em class="fa fa-home"></em>
</a></li>
<li class="active">Locations>create locations</li>
</ol>
</div>{# /.row #}
<div class="row">
<div class="col-md-6">
{# <div id="dvMap" style="width: 50%; height: 50%"></div> #}
<form role="form" action="/post/locations" method="post" >
<input type="text" id="loc" name="name" class="form-control"/>
<input type="text" name="latitude" id="lat" class="form-control"/>
<input name="longitude" id="lng" type="text" class="form-control"/>
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</form>
</div>
</div>
<div id="dvMap" style="width: 80%; height: 70% ">
</div>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDv8X0eEAWUtWZrHG_1XLB8gMNxgdcD0-U"></script>
<script >
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(17.3850, 78.4867),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow()
var name;
var lat;
var lng;
var latlngbounds = new google.maps.LatLngBounds();
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
google.maps.event.addListener(map, 'click', function (e) {
var latlng = new google.maps.LatLng(e.latLng.lat(), e.latLng.lng());
var geocoder = geocoder = new google.maps.Geocoder();
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: 'Hello World!'
});
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
name= results[1].formatted_address;
lat=e.latLng.lat();
lng=e.latLng.lng();
alert("Location: " +name + "\r\nLatitude: " + lat + "\r\nLongitude: " +lng );
document.getElementById("loc").value=name;
document.getElementById("lat").value=lat;
document.getElementById("lng").value=lng;
}
}
});
});
}
</script>
{% endblock %}
Or make a separate js file ( here I have named it custom.js for an example ) in the static folder with the javascript code in it and add <script src='{{ url_for('static', filename='custom.js') }}'></script> at the end of the file.
I hope this helps you.
PS :- Please use the jinja2 comment tags while commenting in jinja2 template file. You can refer it here.
I have written a view which takes input either from a form where you can post your data directly or you can upload a ".csv" file like this given below:
views.py
def Some_view(request):
if request.method == 'POST':
form = My_form(request.POST)
else:
request.method == 'POST' and request.FILES['myfile']
myfile = request.FILES['myfile']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
return render(request, 'myapp/des.html')
return render(request, 'myapp/des.html', {'form': form})
html template: des.html is like this:
{% extends 'protocol/base.html' %}
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title></title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
{% block content %}
<body>
<div class="container">
<div style="width:30%">
<form action="/result_view/" method="post">
{%csrf_token%}
{% for error in form.non_field_errors %}
<div class="form-group has-errors text-danger small">
{{error}}
</div>
{% endfor %}
{% for field in form %}
<div class="form-group has-errors text-danger small">
{{field.errors}}
</div>
<div class="form-group has-errors text-danger small">
</div>
{% endfor %}
<div class="form-group">
{{form.AA}}
</div>
<div class="form-group">
<button class="btn btn-primary" style="width:100%; margin-bottom: 30px ">Submit</button>
</div>
<h2> or <h2>
<style type="text/css">
.button {
background-color: #ff9800; /* Green */
border: none;
color: black;
padding: 10px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin-top: 10px;
margin-bottom: 30px;
}
</style>
<form method="post" enctype="multipart/form-data">
<div class="heading">
</h4>
</div>
{% csrf_token %}
<input class="input" type="file" name="myfile">
<button class="button" type="submit">Upload</button>
</form>
{% if uploaded_file_url %}
<p class="text" >File uploaded successfully. </p>
{% endif %}
</div>
</form>
</div>
</body>
</html>
{% endblock %}
forms.py
from django import forms
class My_form(forms.Form):
AA = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control','placeholder':'Ex.: ARNDCEQGHILKMFPSTWYV'}))
class Meta:
fields = ['AA']
The form is working fine but in my case upload method is not working, when I use to upload file method alone if works fine but with form method, it is not working please help me out in this regards thanks.
i think you need to change if condition sequence:
if request.method == 'POST' and request.FILES.get('myfile'):
# You code here
elif request.method == 'POST':
I am currently following a Django tutorial and I believe that I followed it precisely however I am getting this syntax error. It is saying that {% endblock %} isn't working. Not really sure why this is incorrect. I am trying to create a partial view or template inheritance and plug it into the base.html
My error:
Invalid block tag: 'endblock'
Request Method: GET
Request URL: http://127.0.0.1:8000/articles/all/
Django Version: 1.6
Exception Type: TemplateSyntaxError
Exception Value:
Invalid block tag: 'endblock'
Error during template rendering
In template /Users/bradfordli/Development/django-brad/django_test/article/templates/articles.html, error at line 25
Invalid block tag: 'endblock'
15 {% endfor %}
16 {% else %}
17
18 <p> None to show!</p>
19
20 {% endif %}
21
22 </body>
23 </html>
24
25 {% endblock %}
26
My articles.html
{% extends "base.html" %} <!-- this templates extends the base.html template -->
(% block content %)
<html>
<body>
<h1>Articles</h1>
{% if articles.count > 0 %}
{% for article in articles %}
<div>
<h2>{{article.title}}</h2>
<p>{{article.body|upper}}</p>
</div>
{% endfor %}
{% else %}
<p> None to show!</p>
{% endif %}
</body>
</html>
{% endblock %}
My base.html
<!-- Base of every pate in the side-->
<!DOCTYPE html>
<html lang = "en">
<head>
<title>{% block title %} My Base Template {% endblock %}</title>
<style type="text/css">
body {
text-align: center;
}
#page {
width: 960px;
text-align: left;
margin: 10px auto 20px auto;
background-color: #0c0c0c;
}
#sidebar {
float: left;
width: 200px;
border: 1px solid #000;
}
#content {
float: left;
width: 600px;
border: 1px solid #f00;
padding: 10px;
}
</style>
</head>
<body>
<div id = "page">
<div id = "sidebar">
<!-- This block of the page is named "sidebar"
Also anything between can be substituded by other templates
as long as they refer to sidebar as a block within their template
-->
{% block sidebar %}
<ul>
<li> Articles</li>
<li>Admin</li>
</ul>
{% endblock %}
</div>
<div id = 'content'>
<!-- This block of the page is named "content"-->
{% block content %} This is the content area {% endblock %}
</div>
</div>
</body>
</html>
I don't see any endblock here:
<title>{% block title %} My Base Template</title>
Change the following:
(% block content %) => {% block content %}