Form Validation Not Displaying on Form - django

I have a custom form validation that runs on my popup window form. If the form validation occurs i get a bad request error which is what i have programmed in my views.py . How do i render it so the user stays on the form and the validation message displays. Thanks for the help. Here is my code.
#login_required
def K8_Points_Classroom(request):
#context_from_k8_points = request.session['k8_points_context']
if request.method == 'POST':
form = K8Points_ClassroomForm(request.POST)
if form.is_valid():
form.save(commit=False)
form.save()
class_name = form.cleaned_data.get('class_name')
getstudents = Student.objects.filter(class_name = class_name)
students = getstudents.all()
form = K8Points_ClassroomForm()
context = {'form': form ,'students' : students, 'class_name': class_name,}
return render(request,'points/k8_points_classroom.html', context)
else:
return HttpResponseBadRequest("Bad Request")
else:
return render(request, 'points/k8_points_classroom.html', {'form': form} )
Updated form.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% crispy K8Points_ClassroomForm %}
{% load static %}
{% block content %}
<br>
<h2>{% load static %}
<img src="{% static 'forms/star.png' %}" alt="chain" height="62" width="62"> {{class_name}}</h2>
<br>
<br>
<form action="/points/k8_points_classroom" method="POST">
{% csrf_token %}
<!-- Start Date -->
<div class="container">
<div class="container">
<div class='row'>
<div class="col-4">
<p> Recording Data as User : {{user.username}} </p>
</div>
</div>
<div class='row'>
<div class = "col-2">
{{form.date|as_crispy_field }}
</div>
<div class = "col-2">
{{form.week_of|as_crispy_field }}
</div>
<div class = "col-2">
{{form.day|as_crispy_field }}
</div>
</div>
</div>
</form>
<div class="jumbotron" align="middle">
<img src="{% static 'forms/levelup.png' %}" alt="levelup" height="120" width= "120">
<h1>My Students</h1>
<!-- Line Break -->
<hr style="border: 1px solid black;"/>
<!-- Line Break -->
<div class="row mb-3">
{% for i in students%}
<div class="col-md-4 themed-grid-col"><h2>{{i.student_name}}</h2>
<p align="left"> Today's Score: {{total}}</p>
<h4>
<button type="button" class="btn btn-primary btn-lg btn-block" data-toggle="modal"
data-target="#PointsBox{{ student.pk }}">Level Up
</button>
</h4>
<div id="PointsBox{{ student.pk }}" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<img src="{% static 'forms/star.png' %}" align="left" alt="chain" height="42"
width="42">
<h4 class="modal-title">Points Confirmation </h4>
<button type="button" class="close" data-dismiss="modal"> ×</button>
</div>
<div class="modal-body">
<h6>
<div class="modal-body">Please add the selected points for the current
student.</div>
</h6>
<form action="/points/k8_points_classroom" method="POST">
{% csrf_token %}
<div class="form-row" align='left'>
<div class="col-7">
{{form.class_name|as_crispy_field }}
<input type="student_name" class="form-control" value ="{{i}}" >
{{form.time_frame|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="col-3" align='left'>
{{form.behavior|as_crispy_field }}
{{form.academic|as_crispy_field }}
<button type="submit" class="btn btn-success" ><i
class="fas fa-star"></i> Level Up
</button>
</div>
</div>
</div>
<div class="modal-foot"></div>
</div>
</div>
</div>
</div>
</form>
{% endfor %}
{% endblock %}

You can't return a bad response if the form is invalid. Instead, render the page again with the invalid form and in the temolate you will be able to render the errors. Try starting rendering the form just using {{ form.as_p }} and you will see the errors. The form errors are in form.errors and each field has its own errors, you can access to them form.field.erorrs
if request.method == 'POST':
form = K8Points_ClassroomForm(request.POST)
if form.is_valid():
form.save(commit=False)
form.save()
class_name = form.cleaned_data.get('class_name')
getstudents = Student.objects.filter(class_name = class_name)
students = getstudents.all()
form = K8Points_ClassroomForm()
context = {'form': form ,'students' : students, 'class_name': class_name,}
return render(request,'points/k8_points_classroom.html', context)
return render(request, 'points/k8_points_classroom.html', {'form': form} )

Related

django returns MultiValueDictKeyError at / 'q'

django returns MultiValueDictKeyError at /
'q' in my dashboard template when I'm trying to add search functionality into my app. I want when a user type something on the search input to return the value that user searched for. but i endup getting an error when i try to do it myself.
MultiValueDictKeyError at /
'q'
def dashboard(request):
photos = Photo.objects.all()
query = request.GET['q']
card_list = Photo.objects.filter(category__contains=query)
context = {'photos': photos, 'card_list':card_list}
return render(request, 'dashboard.html', context)
<div class="container">
<div class="row justify-content-center">
<form action="" method="GET">
<input type="text" name="q" class="form-control">
<br>
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
<br>
<div class="container">
<div class="row justify-content-center">
{% for photo in photos reversed %}
<div class="col-md-4">
<div class="card my-2">
<img class="image-thumbail" src="{{photo.image.url}}" alt="Card
image cap">
<div class="card-body">
<h2 style="color: yellowgreen; font-family: Arial, Helvetica,
sans-serif;">
{{photo.user.username.upper}}
</h2>
<br>
<h3>{{photo.category}}</h3>
<h4>{{photo.price}}</h4>
</div>
<a href="{% url 'Photo-view' photo.id %}" class="btn btn-warning btn-
sm m-1">Buy Now</a>
</div>
</div>
{% empty %}
<h3>No Files...</h3>
{% endfor %}
</div>
</div>
try this
query = request.GET['q']
query = request.GET.get('q', '') # use get to access the q
The get() method returns the value of the item with the specified key.

Django CSRF token missing or incorrect but CSFR has been added

Django give me the following error CSRF token missing or incorrect. but I don't find the issue.
I have created my forms:
class ModCollaboratoriForm(forms.ModelForm):
class Meta:
model = AltriCosti
fields = "__all__"
and my simple views.py:
def collaboratori_commessa(request):
collaboratori_commessa=AltriCosti.objects.all()
if request.method == 'POST':
form = ModCollaboratoriForm(request.POST)
if form.is_valid():
print("Il form è valido")
new_input = form.save()
else :
form = ModCollaboratoriForm()
context={
'form':form,
'collaboratori_commessa': collaboratori_commessa,
}
return render(request, 'commesse/collaboratori_commessa.html', context)
And in my collaboratori_commessa.htm the following form:
<form id="contact-form" name="contact-form" method="post" >
{% csrf_token %}
<div class="card card-outline card-info shadow ">
<div class="card-header ">
<h4 class="mb-0">
<img src="{% static 'icon/plus-circle.svg' %}"> Informazioni generali
</h4>
</div>
<div class="card-body">
{{ form.media }}
<div class="row">
<div class="form-group col-2 0 mb-0" >
{{form.codice_commessa|as_crispy_field}}
</div>
.....
</div>
<div class="card-footer">
<div class="col-md-2">
<button class="btn btn-info form-control" type="submit" onclick="submitForm()">Registra</button>
</div>
</div>
</form>
Why django give me the CSRF Error?

For Loop Populate ID In URL Django

I have a button on my template that says check progress, what the button does is takes you to another page for that user based on their user id.
/points/student_progress/1000 <-- id
What I'm trying to accomplish:
When my for loop runs to populate the student names on my template, i want it also to populate the student ID on the button as well. /points/student_progress/{{student_id}} . Here is my code. How do i add this in ?
Views.py
#login_required
def K8_Points_Classroom(request):
#context_from_k8_points = request.session['k8_points_context']
if request.method == 'POST':
form = K8Points_ClassroomForm(request.POST)
if form.is_valid():
form.save(commit=False)
form.save()
class_name = form.cleaned_data.get('class_name')
getstudents = Student.objects.filter(class_name = class_name)
students = getstudents.all()
form = K8Points_ClassroomForm()
context = {'form': form ,'students' : students, 'class_name': class_name,}
messages.success(request,("Points were successfully added for student !"))
return render(request, 'points/k8_points_classroom.html', context )
if not form.is_valid():
messages.warning(request,(form._errors))
class_name = request.POST.get('class_name')[0]
getstudents = Student.objects.filter(class_name = class_name)
students = getstudents.all()
context = {'form': form, 'students': students,}
return render(request, 'points/k8_points_classroom.html', context )
else:
form = K8Points_ClassroomForm()
return render(request, 'points/k8_points_classroom.html', context)
#login_required
def K8_Points(request):
if request.method == 'POST':
form = K8PointsForm(request.POST)
if form.is_valid():
form.save(commit=False)
class_name = form.cleaned_data.get('class_name')
getstudents = Student.objects.filter(class_name = class_name)
students = getstudents.all()
form = K8Points_ClassroomForm()
context = {'form': form ,'students' : students, 'class_name': class_name,}
# request.session['k8_points_context'] = context
return render(request,'points/k8_points_classroom.html', context)
else:
return HttpResponseBadRequest("Bad Request")
else:
form = K8PointsForm()
return render(request, 'points/k8_points.html', {'form': form} )
def Student_Progress(request, studentpsid):
studentid = Student.objects.get(studentpsid=studentpsid)
if K8Points.objects.filter(student_name=studentpsid).exists():
return render(request, 'points/student_progress.html', {'studentid': studentid} )
else:
return HttpResponseBadRequest("Student doesn't exist !")
HTML Template
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% crispy K8Points_ClassroomForm %}
{% load static %}
{% block content %}
<br>
<h2>{% load static %}
<img src="{% static 'forms/star.png' %}" alt="chain" height="62" width="62"> {{class_name}}</h2>
<br>
<br>
<script> </script>
<form action="/points/k8_points_classroom" method="POST">
{% csrf_token %}
<!-- Start Date -->
<div class="container">
<div class="container">
<div class='row'>
<div class="col-4">
<p> Recording Data as User : {{user.username}} </p>
</div>
</div>
<div class='row'>
<div class = "col-2">
<input type="button" onclick="window.location.href = '/points/k8_points';" value="Exit Classroom"/>
</div>
</div>
<br>
<div class='row'>
<div class = "col-2">
{{form.date|as_crispy_field }}
</div>
<div class = "col-2">
{{form.week_of|as_crispy_field }}
</div>
<div class = "col-2">
{{form.day|as_crispy_field }}
</div>
</div>
</div>
</form>
<div class="jumbotron" align="middle">
<img src="{% static 'forms/levelup.png' %}" alt="levelup" height="120" width= "120">
<h1>My Students</h1>
<!-- Line Break -->
<hr style="border: 1px solid black;"/>
<!-- Line Break -->
<div class="row mb-3">
{% for i in students%}
<div class="col-md-4 themed-grid-col"><h2>{{i.student_name}}</h2>
<p align="left"> Today's Score: {{total}}</p>
<h4>
<button type="button" class="btn btn-primary " data-toggle="modal"
data-target="#PointsBox{{student.pk}}"><i class="fas fa-level-up-alt"></i> Level Up
</button>
<i class="fas fa-chart-line"></i> Check Progress
</h4>
<div id="PointsBox{{student.pk}}" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<img src="{% static 'forms/star.png' %}" align="left" alt="chain" height="42"
width="42">
<h4 class="modal-title">Points Confirmation </h4>
<button type="button" class="close" data-dismiss="modal"> ×</button>
</div>
<div class="modal-body">
<h6>
<div class="modal-body">Please add the selected points for the current
student.</div>
</h6>
<form action="/points/k8_points_classroom" method="POST">
{% csrf_token %}
<div class="form-row" align='left'>
<div class="col-7">
{{form.class_name|as_crispy_field }}
{{form.student_name|as_crispy_field }}
{{form.time_frame|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="col-3" align='left'>
{{form.behavior|as_crispy_field }}
{{form.academic|as_crispy_field }}
<button type="submit" class="btn btn-success" ><i
class="fas fa-star"></i> Level Up
</button>
</div>
</div>
</div>
<div class="modal-foot"></div>
</div>
</div>
</div>
</div>
</form>
{% endfor %}
<script>
const class_name = "{{class_name}}";
var classnamedropdown = document.getElementById('id_class_name');
for (i = 0; i < classnamedropdown.options.length; i++) {
// if(classnamedropdown.options[i].text == "Mr. Neo 8th Grade Science")
if(classnamedropdown.options[i].text == class_name)
{
console.log(classnamedropdown.options[i].text)
$("#id_class_name").val(classnamedropdown.options[i].value)
}
}
</script>
{% endblock %}
Check Progress
Had to just add the {{i.studentpsid}} in the loop.

Django Captcha Decorator

I've used a reCaptcha system created by the simpleisbetterthancomplex.com/ website.
In class-based views, it works perfectly fine, but whenever it comes to built-in libraries like:
from django.contrib.auth import views as auth_views
and functionalities:
auth_views.password_reset
it literally does not work as it should. The process of confirming the code of captcha is not executed at all.
I'm having a following usage of it:
url(r'^password/reset/$', check_recaptcha(auth_views.password_reset), name='password_reset'),
decorators.py:
def check_recaptcha(view_func):
#wraps(view_func)
def _wrapped_view(request, *args, **kwargs):
request.recaptcha_is_valid = None
if request.method == 'POST':
recaptcha_response = request.POST.get('g-recaptcha-response')
url = 'https://www.google.com/recaptcha/api/siteverify'
values = {
'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
'response': recaptcha_response
}
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
result = json.load(response)
if result['success']:
request.recaptcha_is_valid = True
else:
request.recaptcha_is_valid = False
messages.error(request, 'Invalid reCAPTCHA. Please try again.')
print(str('Invalid reCAPTCHA. Please try again.'))
return view_func(request, *args, **kwargs)
return _wrapped_view
password_reset_template.html
{% block content %}
<div class="row justify-content-center">
<div class="col-lg-4 col-md-4 col-sm-4">
</div>
<div class="col-lg-4 col-md-4 col-sm-4">
<div class="row main">
<div class="main-login main-center">
<center>
<br>
<h3 class="card-title"><b>E-mail:</b></h3><br>
<form method="post" action=".">
{% csrf_token %}
{% for field in form %}
<div class="form-group" style="padding: 0px 40px;">
{% if field.errors %}
<div class="alert alert-danger">
{{ field.errors }}
</div>
{% endif %}
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope" aria-hidden="true"></i></span>
{{ field }}
</div>
</div>
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
<br>
<div style="padding: 0px 40px;">
<button type="submit" class="btn btn-primary btn-block">Reset Password</button>
</div>
<br>
<div class="g-recaptcha" data-sitekey="xxxxxx"></div>
<br>
</form>
</center>
</div>
<br>
</div>
<div class="col-lg-4 col-md-4 col-sm-4">
</div>
</div>
</div>
{% endblock %}

Doesn't populate fields with existing data

When I access the update page it doesn't populate the fields with the existing entry data (which is there, and print statements I've placed in parts of the view show that it's accessible and exists), I'm not really sure why it's not populating.
This is my view:
#login_required
def sites_update_view(request, place_id=None):
if place_id:
place = get_object_or_404(SiteMeta, pk=place_id)
else:
return redirect('sites-index')
if request.POST:
form = SitesAddForm(request.POST, instance=place)
if form.is_valid():
form.save()
return redirect('sites-index')
else:
form = SitesAddForm(instance=place)
return render(request, 'sites-update.html', {
'form': form,
'site': place,
'place_id': place_id
})
My template:
{% extends "newbase.html" %}
{% load url from future %}
{% load floppyforms %}
{% load staticfiles %}
{% block title %} - Update Site {% endblock %}
{% block content %}
<div class="row">
<div class="col-sm-6 col-md-6">
<h3 class="heading">Update Surveillance Site</h3>
<form method="post" action={% url 'sites-update' place_id=site.pk %}>
{% csrf_token %}
<div class="formSep">
<div class="row">
<div class="col-sm6 col-md-6">
<label for="id_name">Site Name:<span class="f_req">*</span></label>
{{ form.name }}
<span class="help-block">What is the site name?</span>
</div>
<div class="col-sm-6 col-md-6">
<label for="id_lga">LGA:<span class="f_req">*</span></label>
{{ form.lga }}
<span class="help-block">What is the LGA?</span>
</div>
<div class="col-sm-6 col-md-6">
<label for="id_site_type">Site Type:<span class="f_req">*</span></label>
{{ form.site_type }}
<span class="help-block">What type of site is this?</span>
</div>
<div class="col-sm-6 col-md-6">
<label for="id_site_priority">Site Priority:<span class="f_req">*</span></label>
{{ form.site_priority }}
<span class="help-block">What is the priority of this site?</span>
</div>
<div class="col-sm-6 col-md-6">
<label for="id_site_category">Site Category:<span class="f_req">*</span></label>
{{ form.site_category }}
<span class="help-block">What category should the site be in?</span>
</div>
</div>
</div>
<div class="row">
<input class="btn btn-default" type="submit" value="Save" />
<a class="btn btn-default" href={% url "sites-index" %}>Cancel</a>
</div>
</form>
</div>
</div>
{{ form.errors }}
{% endblock %}
{% block sidebar %}
{% include "afp-sidebar.html" %}
{% endblock %}
if request.POST: should be if request.method == 'POST':