Save markdown content in simplemde - python

I am trying to build a blog using flask. SimpleMDE is used as post editor(html code below). I want to save the markdown content to local file and render by flask-misaka in jinja2.
In SimpleMDE, I can get raw markdown content by simplemde.value(). But when I pass simplemde.value() to var in javascript. "\n" is missing aftering passing. I think it may have some "magic" tools in javascript. The html code return 2 alert message, first message contains line feed, the second doesn't.
Could somebody give me some hits about this problems?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Editor</title>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<link rel='stylesheet' href='.{{ url_for("static", filename="css/simplemde.min.css") }}'>
<script src='.{{ url_for("static", filename="js/simplemde.min.js") }}'></script>
</head>
<script type='text/javascript'>
function check() {
var raw = simplemde.value();
alert(raw);
document.testform.markdown_raw.value=raw;
alert(document.testform.markdown_raw.value);
}
</script>
<body>
<form method='post' class='form' role='form' name='testform'>
<div class="form-group " style="padding-top:10px">
<input class="form-control" id="post_title" name="post_title" type="text" value="Title?">
</div>
<div class="form-group">
<input class="form-control" id="markdown" name="post_content" type="textarea" value="">
</div>
<div class="form-group" style='display:none'>
<input class="form-control" id="markdown_raw" name="markdown_raw" type="textarea" value="Origin">
</div>
<div>
<input class='btn btn-default' onclick="check();" id='submit' name='submit' type='submit' value='Save'>
<input class='btn btn-default' id='publish' name='publish' type='submit' value='Publish'>
</div>
</form>
<script type='text/javascript'>
var simplemde = new SimpleMDE({ element: document.getElementById('markdown') });
</script>
</body>
</html>

If you want to get raw markdown, just use simplemde.value().
When you put raw markdown into normal textarea, it turns into pure text.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Editor</title>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.css">
<script src="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.js"></script>
</head>
<body>
<form method='post' class='form' role='form' name='testform'>
<div class="form-group " style="padding-top:10px">
<input class="form-control" id="post_title" name="post_title" type="text" value="Title?">
</div>
<div class="form-group">
<textarea class="form-control" id="markdown" name="post_content"></textarea>
</div>
<div>
<input class='btn btn-default' onclick="" id='submit' name='submit' type='submit' value='Save'>
<input class='btn btn-default' id='publish' name='publish' type='submit' value='Publish'>
</div>
</form>
<script type='text/javascript'>
var simplemde = new SimpleMDE({ element: document.getElementById('markdown') });
</script>
</body>
</html>
Get the content:
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def test():
if request.method == 'POST':
raw_md = request.form['post_content']
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)

Related

Making with a POST request with checkboxes

I am trying to pass in a list of classes into a checkbox (this works), and when the Submit button is clicked, I want to make a Post Request to send all the selected boxes to the backend and then also go to the next page (Does not work).
Here is my HTML page right:
<!doctype html>
<html lang="en">
<head>
<style>
h1 {color: rgb(240, 112, 38);}
</style>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script>
function myFunction() {
window.location.href="./classinfo";
}
function sendPOST() {
let formData = { user_classes: $("#user_classes").val() };
$.post("/class", formData)
};
</script>
</head>
<body style="background-color:powderblue;">
<div class="container">
<br>
<h1>What Classes Have You Taken</h1>
<div class="form-group row">
<label class="col-lg-12">
<form method="POST" action='/class'>
<label class="col-xs-6" style="font-family:verdana;">
{% for c in cs_req %}
<input type="checkbox" style="text-align:left;" name = 'user_classes' option value = "{{c}}" SELECTED> {{c}}<br></option>
{% endfor %}
</label>
<br>
<input class="btn btn-secondary" style="font-family:verdana;" type="Submit" onclick="sendPOST();MyFunction()">
</form>
</label>
</div>
<div id="content">
</div>
</div>
<script>
$(document).ready(function(){
$('.selectpicker').selectpicker();
})
</script>
</body>
</html>
and my backend function is this:
#app.route('/class', methods=["POST"])
def store_classes():
"'Based on checkboxes selected from checkboxes(), store the classes in txt'"
user_classes = request.form.getlist('class') #--> returns nothing
return render_template("class.html")
My onclick is not sending the post request or going to the next page. I'm not sure how to solve this so any advice is appreciated.

Submitting two forms with ajax independently with Django

Im trying to submit two POST forms with Django using ajax, but just one of the forms has the method POST in it. I dont really know what to do here, the error is probably in the Javascript, but i dont see why the first form submit with POST method and the second doesn't, i tried to search in the internet but i think i didnt search the right question.
(sorry for my bad english)
views.py
import os
import time
from datetime import datetime
from django.http import HttpResponse, StreamingHttpResponse
from django.shortcuts import render
from utils.camera_streaming_widget import CameraStreamingWidget
# Camera feed
def camera_feed(request):
stream = CameraStreamingWidget()
frames = stream.get_frames()
return StreamingHttpResponse(frames, content_type='multipart/x-mixed-replace; boundary=frame')
def detect(request):
stream = CameraStreamingWidget()
success, frame = stream.camera.read()
if success:
status = True
else:
status = False
return render(request, 'detect_barcodes/detect.html', context={'cam_status': status})
def dados(request):
if request.method == 'POST':
name = request.POST['name']
print('HELLO')
return HttpResponse(name)
def dados_cod(request):
if request.method == 'POST':
cod = request.POST['cod']
print(cod)
return HttpResponse(cod)
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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">
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.9.2/dist/umd/popper.min.js" ></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<title>Detect Barcodes</title>
<style type="text/css">
.navbar-brand
{
font-size: xx-large;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light" style="background-color: #3c8f56;">
<div class="container-fluid container-md">
<a class="navbar-brand" href="{% url 'detect_barcodes' %}"></a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup"
aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div id='NomeDoSem'><h2>Sistema de Presença</h2></div>
<div class="dropdown">
<button class="btn btn-success dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
Nome do Seminario
</button>
<ul class="dropdown-menu">
<form id="post-name">
{% csrf_token %}
<div class="input-group mb-3">
<input type="text" class="form-control" aria-describedby="basic-addon2" id="name" name="name">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="submit">Enviar</button>
</div>
</div>
</form>
</ul>
</div>
</div>
</nav>
<div class="container">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW"
crossorigin="anonymous"></script>
{% block content %}
{% endblock content %}
</div>
<br>
<form name="post-cod">
{% csrf_token %}
<div class="input-group mb-3">
<input type="text" class="col-md-offset-5 col-md-5 " id="cod" name="cod" style="border: 0.5px solid gray;">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="submit">Enviar</button>
</div>
</div>
</form>
<script text="text/javascript">
$('#post-name').submit(function(e){
e.preventDefault();
$.ajax({
type:'post',
url:'{% url "dados" %}',
data:{
name:$('#name').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
},
success: function(data){
$('#NomeDoSem').empty()
$('#NomeDoSem').html('<h2>'+data+'</h2>')
}
});
});
$('#post-cod').submit(function(b){
b.preventDefault();
$.ajax({
type:'post',
url:'{% url "dados_cod" %}',
data:{
cod:$('#cod').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
},
success: function(data){
alert('cpf')
}
});
});
</script>
</body>
</html>
replace <form name="post-cod"> with <form id="post-cod">

How to fix "Forbidden (403) CSRF verification failed. Request aborted." error in django

I'm getting this common error as in the title. I'm doing a project in Django in a virtual environment folder.
setting.py:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
index.html:
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Instapic</title>
<link rel="stylesheet" href="{% static 'assets/bootstrap/css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'assets/css/Login-Form-Clean.css' %}">
<link rel="stylesheet" href="{% static 'assets/css/styles.css' %}">
</head>
<body>
<div class="login-clean">
<form method="post">
{% csrf_token %}
<h2 class="sr-only">Login Form</h2>
<div class="illustration">
<div style="display: none" id="errors" class="well form-error-message"></div>
<img src="{% static 'assets/img/logo.jpg' %}">
</div>
<div class="form-group">
<input class="form-control" id="username" type="text" name="username" required="" placeholder="Username" maxlength="20" minlength="4">
</div>
<div class="form-group">
<input class="form-control" id="email" type="email" name="email" required="" placeholder="Email" maxlength="100" minlength="6">
</div>
<div class="form-group">
<input class="form-control" id="password" type="password" name="password" required="" placeholder="Password" maxlength="20" minlength="6">
</div>
<div class="form-group">
<button class="btn btn-primary btn-block" id="go" type="submit">Create Account</button>
</div>Already got an account? Login here ...</form>
</div>
<script src="{% static 'assets/js/jquery.min.js' %}"></script>
<script src="{% static 'assets/bootstrap/js/bootstrap.min.js' %}"></script>
<script src={% static "assets/js/django-ajax.js" %}></script>
<script type="text/javascript">
$(document).ready(function() {
$('#go').click(function() {
$.post("ajax-sign-up",
{
username: $("#username").val(),
email: $("#email").val(),
password: $("#password").val()
},
function(data, status){
if (JSON.parse(data).Status == 'Success') {
window.location = '/';
} else {
$('#errors').html("<span>" + JSON.parse(data).Message + "</span>")
$('#errors').css('display', 'block')
}
});
return false;
})
})
</script>
</body>
</html>
I added {% csrf_token %} in my html file trying fix this - didn't work. I've found online this tag example:
<input type="hidden" id="csrf_token" value='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>.
Unfortunately I don't know how to use it in order to fix my error.
Thanks for help
I guess, instead of post a form you are posting values.
You need to add csrfmiddlewaretoken key while execute $.post() statement.
This is not Tested but it may be fix your problem
csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value
or
csrfmiddlewaretoken: $('[name=csrfmiddlewaretoken]').val()
add this line in HTML file by updating
$.post("ajax-sign-up",
{
username: $("#username").val(),
email: $("#email").val(),
password: $("#password"),
csrfmiddlewaretoken: $('[name=csrfmiddlewaretoken]').val()
},
updated code is :
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Instapic</title>
<link rel="stylesheet" href="{% static 'assets/bootstrap/css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'assets/css/Login-Form-Clean.css' %}">
<link rel="stylesheet" href="{% static 'assets/css/styles.css' %}">
</head>
<body>
<div class="login-clean">
<form method="post">
{% csrf_token %}
<h2 class="sr-only">Login Form</h2>
<div class="illustration">
<div style="display: none" id="errors" class="well form-error-message"></div>
<img src="{% static 'assets/img/logo.jpg' %}">
</div>
<div class="form-group">
<input class="form-control" id="username" type="text" name="username" required="" placeholder="Username" maxlength="20" minlength="4">
</div>
<div class="form-group">
<input class="form-control" id="email" type="email" name="email" required="" placeholder="Email" maxlength="100" minlength="6">
</div>
<div class="form-group">
<input class="form-control" id="password" type="password" name="password" required="" placeholder="Password" maxlength="20" minlength="6">
</div>
<div class="form-group">
<button class="btn btn-primary btn-block" id="go" type="submit">Create Account</button>
</div>Already got an account? Login here ...</form>
</div>
<script src="{% static 'assets/js/jquery.min.js' %}"></script>
<script src="{% static 'assets/bootstrap/js/bootstrap.min.js' %}"></script>
<script src={% static "assets/js/django-ajax.js" %}></script>
<script type="text/javascript">
$(document).ready(function() {
$('#go').click(function() {
$.post("ajax-sign-up",
{
username: $("#username").val(),
email: $("#email").val(),
password: $("#password").val(),
csrfmiddlewaretoken: $('[name=csrfmiddlewaretoken]').val()
},
function(data, status){
if (JSON.parse(data).Status == 'Success') {
window.location = '/';
} else {
$('#errors').html("<span>" + JSON.parse(data).Message + "</span>")
$('#errors').css('display', 'block')
}
});
return false;
})
})
</script>
</body>
</html>
If you're just posting the contents of a HTML form with id signup-form (add that to the <form>), and your form has the {% csrf_token %}, then you can do that in ajax using:
$.post("ajax-sign-up", $("#signup-form").serialize(), function(data, status){...})

Why won't my index.html file be found in directory?

I'm 100% sure my path is correct in my code, why is it giving me TemplateDoesNotExist error? I can't see how this is possible.
I tried:
settings.py > TEMPLATES > Dirs: [/template/music]
and a laundry list of other things on SO but it doesn't rectify my problem.
Here's my views.py file:
from django.http import HttpResponse
from django.template import loader
def index(request):
template = loader.get_template('music/index.html')
return HttpResponse(template.render())
def detail(request, user_id): # Testing out page 2
return HttpResponse("<h2>Page # (testing this out) " + str(user_id) + "</h2>")
Here's my index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<title>The Page</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form action="#">
<div class="form-group">
<label for="firstName">First Name:</label>
<input type="email" class="form-control" id="firstName" placeholder="Enter first name" name="firstName">
</div>
<div class="form-group">
<label for="">Last Name:</label>
<input type="email" class="form-control" id="lastName" placeholder="Enter last name" name="lastName">
</div>
</form>
<div class="checkbox">
<label><input type="checkbox" name="remember">Remember me</label></div></br>
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</body>
</html>
Your templates directory is inside migrations. Move it out of there.

error when page is refreshed in django

I am learning to create a website using django. I have a homepage through which user can select city. The next page shows the list of hotels.It works properly,but when page is refreshed it gives me error
This is my html file for list page.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="//code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="//code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-backstretch/2.0.4/jquery.backstretch.min.js"></script>
<script type="text/javascript" src="../js/typeahead/0.11.1/typeahead.bundle.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
{% load static %}
<script src="/static/typeahead.js "></script>
</head>
<body>
<div >
<div style="float:left; background-color:#d9d9d9;margin-top:100px;width:30%;height:800px;">
<h2 style="text-align:center;">Filters</h2>
<div style="width:95%; margin-left: 10px; " >
<form method="post" data-ajax="false" action="{% url 'list' %}">
{% csrf_token %}
<div data-role="rangeslider" data-mini="true" style="width:100%">
<label for="range-1a">price:</label>
<input name="range-1a" id="range-1a" min="0" max="100" value="0" type="range">
<label for="range-1b">Rangeslider:</label>
<input name="range-1b" id="range-1b" min="0" max="100" value="100" type="range">
</div>
<input type="submit" value="Submit">
</form>
</div>
</div>
<div style=" float:right;margin-right:30px;margin-top:100px;width:60%;height:80%">
{% for hotel in city_list %}
{% load static %}
<div class="col-md-4" style="width:45%;border:0;position:relative;">
<div class="thumbnail" style="height:300px; background-color:black;border:0;border-radius:0;position:relative;box-shadow:0;" >
<a href="/w3images/lights.jpg" data-ajax="false">
<img src="{% static hotel.photo.url %}" style="border:0;height:85%;width:100%;" >
<div class="caption">
<p style="color:white;">Name</p>
</div>
</a>
</div>
</div>
{% endfor %}
</div>
</div>
</body>
</html>
This is my views.py
def homepage(request):
hotel_list=Hotels.objects.all()
context={'hotel_list':hotel_list}
return render(request, 'polls/homepage.html',context)
def wholelist(request):
hotelvar=request.POST.get('service_type')
if hotelvar=='Hotels':
city_list=Hotels.objects.filter(city_name__iexact=request.POST.get('searchabc'))
if not city_list:
hotel_list=Hotels.objects.all()
context={'hotel_list':hotel_list}
return render(request, 'polls/homepage.html',context)
pricemin=200
pricemax=800
context={'pmin':pricemin,'pmax':pricemax,'city_list':city_list}
return render(request, 'polls/list.html',context)
i get the following error when refreshed
UnboundLocalError at /polls/wholelist/
local variable city_list referenced before assignment
city_list is being passed from the homepage, but when page is reloaded it not being passed. Is there a way to pass it when page is refreshed?
when hotelvar not equal to 'Hotels', variable city_list is not set
def wholelist(request):
hotelvar=request.POST.get('service_type')
city_list = None
if hotelvar=='Hotels':
city_list=Hotels.objects.filter(city_name__iexact=request.POST.get('searchabc'))
if not city_list:
hotel_list=Hotels.objects.all()
context={'hotel_list':hotel_list}
return render(request, 'polls/homepage.html',context)
pricemin=200
pricemax=800
context={'pmin':pricemin,'pmax':pricemax,'city_list':city_list}
return render(request, 'polls/list.html',context)

Categories

Resources