Django: is_valid() method is always false why? - python

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)

Related

Get the name of hyperlink clicked from previous page-FLASK

I am creating a project on examination.
In my first html page I have a set of hyperlinks which represent the name of question papers. The question papers are stored in the form of tables in MySQL.
What I want is,to return the name of the hyperlink clicked by the user in my python code.
All the links should lead to the same webpage,but the contents in each link is different.
This is my python code for the webpage which should open after one of the links is clicked:
#app.route('/qsetdisplay/exam',methods=['GET','POST'])
def exam():
if request.method == 'POST':
if 'answer' in request.form:
cursor5 = db3.cursor(pymysql.cursors.DictCursor)
tablename = request.args.get('type')
print(tablename)
cursor5.execute("select questions from {}".format(tablename))
cursor5.execute("select answers from {}".format(tablename))
cursor5.execute("select marks from {}".format(tablename))
print("ques:", ques)
print("ans:", ans)
print("marks:",marks)
return render_template('exam.html',ques=ques,marks=marks,ans=ans)
tablename returns as none in the above code.
This is my html code for the webpage which would open after oneof the links is clicked:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>EXAMINATION</title>
</head>
<body>
<div>
<form name="ex" id="ex" action="{{url_for('exam')}}" method=POST>
<h1 align="centre">ALL THE BEST!!!</h1>
{% for que in ques %}
<h6>{{que}}</h6>
<textarea name="answer" id="answer" placeholder="enter answer" rows="10" cols="100"></textarea><br><br>
{% endfor %}
<input name="sub" id="sub" type="submit" value="submit">
</form>
</div>
</body>
</html>
And this is the html code for the previous page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>STUDENT PROFILE</title>
</head>
<body>
<div>
<form action="/">
<h1>"WELCOME STUDENT"</h1>
</form>
</div>
<div>
<form name="QD" action="{{url_for('qset_display')}}" method="get">
<input name="QD" value="CLICK TO VIEW QUES PAPERS" type="submit"><br><br><br><br>
<h1>THESE ARE THE AVAILABLE PAPERS:</h1>
{% for name in names %}
{{name}}<br><br>
{% endfor %}
</form>
</div>
</body>
</html>
How can I correct my code?

Method Not Allowed (POST): /password_change_done

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">

in Django show String on UI when file is ready

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})

How can I connect the Submit button to my .py file?

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.

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.

Categories

Resources