NameError - global name not defined - python

I am trying to read some data from html forms and insert it into database. Doing so i am stuck with this error "NameError at /createEmployee/ : global name 'get_post_param' is not defined" ; i will paste my code here. Can somebody help me to solve this.
VIEWS.PY
def createEmployee(request):
if request.method == "POST":
userName = get_post_param(request,"userName")
designation = get_post_param(request,"designation")
employeeID = get_post_param(request,"employeeID")
contactNumber = get_post_param(request,"contactNumber")
project = get_post_param(request,"project")
dateOfJoin = get_post_param(request,"dateOfJoin")
EmployeeDetails(userName=userName,designation=designation,employeeID=employeeID,contactNumber=contactNumber,project=project,dateOfJoin=dateOfJoin).save()
return render_to_response('createEmployee.html')
else:
return render_to_response('createEmployee.html')
TEMPLATE.PY
<form action="http://127.0.0.1:8000/createEmployee/" method="POST">
Name: <input type="text" name="userName" /><br />
Designation: <input type="text" name="designation" /><br>
EmployeeID: <input type="text" name="employeeID" /><br>
Contact Number: <input type="text" name="contactNumber" /><br>
Project: <input type="text" name="project" /><br>
Date Of Join: <input type="text" name="dateOfJoin" /><br>
<input type="submit" value="Submit" /><br />
</form>

This is a very simple problem. You have not defined get_post_param.
Where did you get this get_post_param idea?
Simply define a function called get_post_param to fix it..
Here's a python shell session
>>> get_post_param(request, 'userName')
NameError: not defined
>>> def get_post_param(request, param):
... return request.POST.get(param)
# or scrap the idea of a function to do a one liner op anyways
>>> get_post_param(request, 'userName'):
'my_username'

Related

Multivaluedict key error wventhough i have set name to input field

I have made a form and set method=post and while taking request.post['name'] to a variable MultiValueDictKeyError is Coming why is that ?
<form action="verify_user" method="post">
{% csrf_token %}
<input required type="text" placeholder="Name" name="name"><br><br>
<input required type="password" placeholder="Password" name="password"><br><br>
<input required type="passord" placeholder="Confirm password" name="confirm_password" id=""> <br><br>
<br><br><h1>{{ messages }}</h1>
<button type="submit">Create</button>
</form>
this is my form ------
def verify_user(request):
inputname = request.POST['name']
inputpass = request.POST['password']
inputconfirmpass = request.POST['confirm_password']
if not inputpass == inputconfirmpass:
messages.info(request,"Passwords don't match")
else:
messages.info(request,"Passwords match")
return redirect('/verify_user')
this is my function in views.py -------------
MultiValueDictKeyError at /verify_user
'name'
Request Method: GET
Request URL: http://127.0.0.1:8000/verify_user
Django Version: 4.1.2
Exception Type: MultiValueDictKeyError
Exception Value: 'name'
this is the error --------
Try to provide another name as name for e.g. person_name something like that, also I'd recommend you to use .get() so that you can also provide some other default value.
views.py:
def verify_user(request):
if request.method=="POST":
inputname = request.POST.get('person_name', False)
inputpass = request.POST.get('password', False)
inputconfirmpass = request.POST.get('confirm_password', False)
if not inputpass == inputconfirmpass:
messages.info(request,"Passwords don't match")
else:
messages.info(request,"Passwords match")
return redirect('/verify_user')
else: # GET request
return render(request, "some_folder_name/your_template.html")
Template file:
<form method="POST">
{% csrf_token %}
<input required type="text" placeholder="Name" name="person_name"><br><br>
<input required type="password" placeholder="Password" name="password"><br><br>
<input required type="passord" placeholder="Confirm password" name="confirm_password" id=""> <br><br>
<br><br><h1>{{ messages }}</h1>
<button type="submit">Create</button>
</form>

Why form with the ImageField is not valid in DJango?

I have model in Django which name is "User":
class User(models.Model):
user_id = models.AutoField(auto_created = True, primary_key = True, serialize = False, verbose_name ='ID')
surname = models.CharField(max_length=100)
name = models.CharField(max_length=100)
patronymic = models.CharField(max_length=100)
email = models.CharField(max_length=100)
avatar = models.ImageField(upload_to='store/static/store/user_avatars/')
Also I include columns of this model into my form:
class UserForm(forms.Form):
surname = forms.CharField(max_length=100)
name = forms.CharField(max_length=100)
patronymic = forms.CharField(max_length=100)
email = forms.CharField(max_length=100)
password = forms.CharField(max_length=100)
avatar = forms.ImageField()
View which gets that data:
def sign_up(request):
if request.method == 'GET':
return render(request, 'store/sign_up.html')
elif request.method == 'POST':
form = UserForm(request.POST, request.FILES)
if form.is_valid():
user = User(surname=form.cleaned_data['surname'],
name=form.cleaned_data['name'],
patronymic=form.cleaned_data['patronymic'],
email=form.cleaned_data['email'],
avatar=form.cleaned_data['avatar'])
user.save()
return HttpResponse("Alright, you signed up! " + form.cleaned_data['email'])
else:
print(form.as_table())
return HttpResponse("Data is error!")
And, finally, front of this view:
<form method="post">
{% csrf_token %}
<div class="user_data">
<div class="user_data_grid">
<input type="text" name="surname" placeholder="Surname" id="surname" style="grid-row: 2 / span 1">
<input type="text" name="name" placeholder="Name" id="name" style="grid-row: 3 / span 1">
<input type="text" name="patronymic" placeholder="Patronymic" id="patronymic" style="grid-row: 4 / span 1">
<input type="email" name="email" placeholder="Enter your mail" id="email" style="grid-row: 5 / span 1">
<input type="password" name="password" id="password" placeholder="Enter password" style="grid-row: 6 / span 1">
<input type="checkbox" id="checkbox" onclick="seePassword()" style="grid-row: 6 / span 1">
<label for="checkbox" style="grid-row: 6 / span 1"></label>
<p id="password_prompt" style="grid-row: 7 / span 1">
Password must be at least 8 symbols length!
</p>
<input type="submit" id="submit_personal_data" value="Sign up" style="grid-row: 8 / span 1" disabled>
</div>
</div>
<div class="user_photo">
<div class="user_photo_grid">
<img src="{% static 'store/sign_up/default_avatar.png' %}" style="grid-row: 2 / span 5" id="avatar_image">
<input name="avatar" type="file" accept=".jpg, .jpeg, .png" id="submit_photo" onchange="displayIMG(this)">
<label for="submit_photo" style="grid-row: 8">Profile photo load</label>
</div>
</div>
</form>
So, what I want to ask about. When I don't include ImageField into my form and model - there is not any of errors, data adds into table correctly. But, when I include ImageField into my form and model like in example above - there is error - my form becomes invalid. I get information about my form in table, and this information is like this:
<tr><th><label for="id_surname">Surname:</label></th><td><input type="text" name="surname" value="Surname" maxlength="100" required id="id_surname"></td></tr>
<tr><th><label for="id_name">Name:</label></th><td><input type="text" name="name" value="Name" maxlength="100" required id="id_name"></td></tr>
<tr><th><label for="id_patronymic">Patronymic:</label></th><td><input type="text" name="patronymic" value="Patronymic" maxlength="100" required id="id_patronymic"></td></tr>
<tr><th><label for="id_email">Email:</label></th><td><input type="text" name="email" value="email#email.com" maxlength="100" required id="id_email"></td></tr>
<tr><th><label for="id_password">Password:</label></th><td><input type="text" name="password" value="password" maxlength="100" required id="id_password"></td></tr>
<tr><th><label for="id_avatar">Avatar:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="file" name="avatar" accept="image/*" required id="id_avatar"
Last string says, that the problem is there, in ImageField. I think that the problem may be in front, because when I add information about user (ImageFielf data also) in Django admin panel - operation is successfull.
So, why my form here is invalid?
You are forgetting enc-type.
your form should be like:
<form method="post" enctype="multipart/form-data">
On your model form avatar field you should type:
avatar = forms.ImageField(blank=True)
If that doesn't work, try this:
avatar = forms.ImageField(required=False)
try it like this:
<form method="post">
{% csrf_token %}
<div class="user_data">
<div class="user_data_grid">
<input type="text" name="surname" placeholder="Surname" id="surname" style="grid-row: 2 / span 1">
<input type="text" name="name" placeholder="Name" id="name" style="grid-row: 3 / span 1">
<input type="text" name="patronymic" placeholder="Patronymic" id="patronymic" style="grid-row: 4 / span 1">
<input type="email" name="email" placeholder="Enter your mail" id="email" style="grid-row: 5 / span 1">
<input type="password" name="password" id="password" placeholder="Enter password" style="grid-row: 6 / span 1">
<input type="checkbox" id="checkbox" onclick="seePassword()" style="grid-row: 6 / span 1">
<label for="checkbox" style="grid-row: 6 / span 1"></label>
<p id="password_prompt" style="grid-row: 7 / span 1">
Password must be at least 8 symbols length!
</p>
<div class="user_photo">
<div class="user_photo_grid">
<img src="{% static 'store/sign_up/default_avatar.png' %}" style="grid-row: 2 / span 5" id="avatar_image">
<input name="avatar" type="file" accept=".jpg, .jpeg, .png" id="submit_photo" onchange="displayIMG(this)">
<label for="submit_photo" style="grid-row: 8">Profile photo load</label>
</div>
</div>
<input type="submit" id="submit_personal_data" value="Sign up" style="grid-row: 8 / span 1" disabled>
</div>
</div>
</form>

I keep getting the BadRequestKeyError 400, and I don't know why

Python Side Routing
#app.route("/loginC", methods=["POST"])
def loginPage():
valid = request.form["idnumber"]
if valid is not None: #Creating A New User
username = request.form["username"]
password = request.form["password"]
firstname = request.form["firstname"]
lastname = request.form["lastname"]
idnumber = request.form["idnumber"]
logins["'"+username+"'"] = {"password":"'"+ password +"'", "firstname":"'"+ firstname +"'", "lastname":"'"+ lastname +"'", "idnumber":"'"+ idnumber +"'"}
session["currentUser"] = username
isLogin = True
return redirect("/login")
else:
username = request.form["username"]
password = request.form["password"]
for account in logins:
if username == logins:
if logins["'"+username+"'"]["password"] == password:
session["currentUser"] = username
isLogin = True
return redirect("/login")
return redirect("/login")
Html
<form action="/loginC" class="formLogin" method="post">
<h3>Existing User</h3>
Username: <input type="text" name="username" placeholder="username" required><br>
Password: <input type="password" name="password" placeholder="password" required><br>
<input type="submit" value="Login">
</form>
<br>
<hr class="formLogin">
<br>
<form action="/loginC" class="formLogin" method="post">
<h3>New User</h3>
Username: <input type="text" name="username" placeholder="username" required><br>
Password: <input type="password" name="password" placeholder="password" required> <br>
Firstname: <input type="text" name="firstname" placeholder="firstname" required><br>
Lastname: <input type="text" name="lastname" placeholder="lastname" required><br>
Student ID: <input name="idnumber" type="text" placeholder="ID number" required><br>
<input type="submit" value="Create">
</form>
I keep getting the error:
"werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'idnumber'"
it is requesting the form in the second for bracket aka the 'new user' bracket
In place of :
valid = request.form["idnumber"]
Change to :
If you want to retrieve POST data:
valid = request.form.get("idnumber")
If you want to retrieve GET (query string) data:
valid = request.args.get("idnumber")
Also :
Change method to
#app.route("/loginC", methods=["GET", "POST"])

when i click the button to update my form CSRF verification failed pop ups

I have two different forms in my index.html template and in both the forms i'm using csrf token.
The problem that i'm facing is when I try to update my form i'm getting "CSRF verification failed. Request aborted." I've searched almost all the questions in this site and other websites and did everything still the error is shown.
This is my first form which adds student entry:
<form action = "{% url 'studentapp:addstudent' %}" id="addform" method = "POST">
{% csrf_token %}
<div class = "form-group">
<label for = "your_name">
Your name:
</label>
<input class = "form-control" id="new_name" type = "text" name="name" value="{{ current_name }}" placeholder="Enter your name">
</div>
<div class="form-group">
<label for = "course_name">
Course:
</label>
<input id="new_course" class = 'form-control' type = "text" name="course" value="{{ current_course }}" placeholder="Enter your course">
</div>
<div class = "form-group">
<label for = "rollno">
Roll No.:
</label>
<input id="new_rollno" type = "text" class = 'form-control' name="roll" value="{{ current_roll }}" placeholder="Enter your roll number">
</div>
<div class = "form-group">
<label for ="addr">
Address:
</label>
<textarea id="new_address" type = "text" name="address" class = 'form-control' value="{{ current_addr }}" placeholder="Enter your address"></textarea>
</div>
<input type = "submit" value="Submit" class = "btn btn-success" style="font-size:18px;" />
</form>
This is my second form which is pre-populated when i click "edit" button on my template. when i click "update" button csrf token verification failed is displayed.
<form action="{% url 'studentapp:editrow' rowid=id %}" id="editform" method="POST">
{% csrf_token %}
<div class = "form-group">
<label for = "your_name">
Your name:
</label>
<input class = "form-control" id="new_name" type = "text" name="name" value="{{ student_detail.name }}" placeholder="Enter your name">
</div>
<div class="form-group">
<label for = "course_name">
Course:
</label>
<input id="new_course" class = 'form-control' type = "text" name="course" value="{{ student_detail.course }}" placeholder="Enter your course">
</div>
<div class = "form-group">
<label for = "rollno">
Roll No.:
</label>
<input id="new_rollno" type = "text" class = 'form-control' name="roll" value="{{ student_detail.roll }}" placeholder="Enter your roll number">
</div>
<div class = "form-group">
<label for ="addr">
Address:
</label>
<input id="new_address" type = "text" name="address" class = 'form-control' value="{{ student_detail.address }}" placeholder="Enter your address"/>
</div>
<input type = "submit" value="Update" id="update" class = "btn btn-success" style="font-size:18px;" />
</form>
</div>
</div>
</div>
</div>
This is my ajax request:
function update_entry(id) {
var id = id
$.ajax({
url: "{% url 'studentapp:index' %}",
type: "POST",
data:{
'csrfmiddlewaretoken': '{{ csrf_token }}',
'id' : id,
},
success: function(response){
$(".response").html(response.template)
$("#editform").modal("show");
}
});
}
function update_property(id) {
window.location.replace("/studentapp/editrow" + id+"/");
}
Since I was using two separate forms, i was using two CSRF tokens. Removing one token was not solving the issue so I just did this:
<input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
in one of my forms and added these two lines in my index view:
if request.is_ajax():
#Your Code
csrf_token = request.POST['csrfmiddlewaretoken']
response = {}
response['status'] = False
student_detail = #Your Model name
context = {
"Your dictionary"
"csrf_token": csrf_token
}
and it's working just fine for me.

How do I pass url parameter to form value?

The form has this hidden field
<input type="hidden" name="dir_type" value="tshirt">
url parameters are
/dir?type=tshirt
/dir?type=books
/dir?type=posters
and so on.
Now I hard coded value="tshirts" but how do I get parameter for the relevant page?
I found several pages like this dealing with similar topics but I did not understand how this is done.
Thanks for your help.
UPDATE
The answer by systempuntoout works perfectly but I decided to solve the problem without using templates. And for anyone who has a similar question, passing the url parameter to the form like this works well:
<form name="submit_form" action="/directorysubmithandler" method="post" onSubmit="return validate_form()">
title: <input type="text" name="title" size=50><br />
url: <input type="text" name="url" size=50><br />
<input type="hidden" name="dir_type" value="%s")>
<input type="submit" value="submit">
</form>""" % self.request.get("type"))
a. pass the type value to the view:
class Directory(webapp.RequestHandler):
def get(self):
....
merchandise_type = self.request.get("type", "")
items = Item.all()
items.filter("type =", merchandise_type)
path = os.path.join(os.path.dirname(__file__), 'dir_details.html')
self.response.out.write(template.render(path,{'type':merchandise_type}))
b. add the type value to the hidden field:
<input type="hidden" name="dir_type" value="{{ type }}">
c. get the dir_type value in your post handler:
class DirectorySubmitHandler(webapp.RequestHandler):
def post(self):
user = users.get_current_user()
merchandise_type = self.request.get("dir_type", "")
dir_type = merchandise_type
if user:
item = Item()
item.title = self.request.get("title")
item.url = self.request.get("url")
item.type = self.request.get("dir_type")
item.user_who_liked_this_item = user
item.put()
self.redirect("/dir?type=%s" %
self.request.get("dir_type"))
else:
self.redirect(users.create_login_url(self.request.uri))

Categories

Resources