The goal of my program is to place the first and last name into my database upon it being entered and Submit button clicked by the user so that when I manually check in Terminal what’s in my database, I can see what the user has entered and submitted. I need to some how connect my Submit button to my views.py file so that it can go through , sort like an onClick() but this time, to go a .py file. (correct me if I’m wrong with this train of thought).
How would I go about making this happen?
Here's my views.py file:
from django.http import HttpResponse
from django.shortcuts import render
from .models import Person
def index(request):
if request.method == 'POST':
first_name = request.POST.get('firstName')
last_name = request.POST.get('lastName')
if first_name and last_name:
user = Person.objects.create(firstName=first_name, lastName=last_name)
user.save()
return render(request, 'music/index.html')
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">
<link rel="stylesheet" href="index.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 form should be declared as:
<form method="POST">
and your <button type="submit"> should be inside the <form></form>.
As the same view deals with the GET and POST methods, you should remove the action="#" attribute, that way action will point to the same view.
Related
i am new to django/python
i am trying to change user password but i am getting error
Method Not Allowed (POST): /password_change_done
Method Not Allowed: /password_change_done
[23/Jul/2020 19:11:05] "POST /password_change_done HTTP/1.1" 405 0
this is my url patterns just for password changes :
path('password_change',
auth_views.PasswordChangeView.as_view(template_name='password_change.html'),
name='password_change'),
path('password_change_done',
auth_views.PasswordChangeDoneView.as_view(template_name='password_change_done.html'),
name='password_change_done'),
both my html pages for this operation
my html code: password_change
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome</title>
</head>
<body>
<h3> Change Password</h3>
<form action="{% url 'password_change_done' %}" method="POST" class="form-signin">{% csrf_token %}
<input name="Old password" class="form_control" placeholder="Old password"
type="password" id=old_password required="true">
<input name="new password" class="form_control" placeholder="new password"
type="password" id=new_password required="true">
<input name="confirm password" class="form_control" placeholder="confirm password"
type="password" id=confirm_password required="true">
<button type="submit">Update</button>
</form>
</body>
</html>
my html code for password_chang_done:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome</title>
</head>
<body>
<h1>Welcome</h1>
<h2> <img src="{% static 'images/welcome.jpg' %}"> </h2>
<h5>hello,{{request.user.username}}</h5>
<script>
window.alert("password sucessfully changed")
</script>
</body>
</html>
You should make the POST request to the password_change endpoint, not the password_change_done` endpoint, so:
<form action="{% url 'password_change' %}" method="POST" class="form-signin">
…
</form>
In is quite common in Django web development, and in web development in general to make a POST to the same view that first generated the page with a GET request.
Furthermore the PasswordChangeView view uses the PasswordChangeForm [GitHub]:
class PasswordChangeForm(SetPasswordForm):
# …
field_order = ['old_password', 'new_password1', 'new_password2']
The name of the <input> elements thus should be old_password, new_password1, and new_password2:
<input name="old_password" class="form_control" placeholder="Old password" type="password" id=old_password required="true">
<input name="new_password1" class="form_control" placeholder="new password" type="password" id="new_password" required="true">
<input name="new_password2" class="form_control" placeholder="confirm password" type="password" id=confirm_password required="true">
Everytime i get the stu_name variable value from form without using is_valid() function then stu_name is always return value enter by user but with is_valid() stu_name is always None.I do some experiments and i found that is_valid() is always return false but why?
This is views.py file code.
from django.shortcuts import render
from django.http import HttpResponse
from .models import student
from .forms import student_data
def my_data(request):
stu_name=None
myform=student_data(request.POST)
if (request.method=="POST" and myform.is_valid()):
stu_name=myform.cleaned_data['user']
else:
myform=student_data
return render(request,'show.html',{'student':stu_name})
This is my html file where the form code is written.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<form action="/payment/show/" method="POST">
{% csrf_token %}
<label for="">Name</label>
<input type="text" name="user" required>
<label for="">ID</label>
<input type="number" required>
<label for="">Address</label>
<input type="text" required>
<button type="submit">Add Me</button>
</form>
</div>
</body>
</html>
forms.py file code.
from django import forms
class student_data(forms.Form):
name=forms.CharField(widget=forms.TextInput,max_length=20)
id=forms.IntegerField(widget=forms.NumberInput,max_value=6)
address=forms.CharField(widget=forms.TextInput,max_length=50)
Modify your view
def my_data(request):
stu_name=None
myform=student_data(request.POST)
if (request.method=="POST" and myform.is_valid()):
stu_name=myform.cleaned_data['user']
else:
myform=student_data
return render(request,'show.html',{'student':stu_name,'form':myform})
In your html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<form action="/payment/show/" method="POST">
{% csrf_token %}
{{ form.as_p}}
<button type="submit">Add Me</button>
</form>
</div>
</body>
</html>
and in your forms.py
class student_data(forms.Form):
name=forms.CharField(widget=forms.TextInput,max_length=20, required=True)
id=forms.IntegerField(widget=forms.NumberInput,max_value=6, required=True)
address=forms.CharField(widget=forms.TextInput,max_length=50, required=True)
I would like do next,
When press on submit button, Django generate some file (it takes some time, about a minute)
I would like that next to submit button will appear another button to download (locally) this file when generating was finished.
screen shot:
image
HTML:
{% load bootstrap %}
<!DOCTYPE html>
<html>
<head>
<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.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Create SWM Client Environment</title>
</head>
<body>
<nav class="navbar navbar-dark bg-dark">
<h4 style="color: aliceblue;">Create SWM client environment</h4>
</nav>
<div style="padding: 20px;">
<form method="post">
{% csrf_token %}
<div class="form-group container w-25">
{{ form|bootstrap }}
</div>
<div class="container w-25">
<button type="reset" class="btn btn-primary">Reset</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</body>
</html>
Forms:
class ContactForm(forms.Form):
swm_server = forms.CharField(
label='server',
widget=forms.TextInput(attrs={'placeholder': 'Server IP or Server DNS'}))
def clean(self):
cleaned_data = super(ContactForm, self).clean()
swm_server = cleaned_data.get('swm_server')
Views:
def home(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
pass # does nothing, just trigger the validation
else:
form = ContactForm()
return render(request, 'home.html', {'form': form})
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.
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)