Django Captcha Decorator - django

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

Related

I am using django for a project and i got this error

I am doing a project in Django and i got this error.How is this occurs?
NoReverseMatch at /
Reverse for 'create_order' with no arguments not found. 1 pattern(s) tried: ['create_order/(?P[^/]+)/$']
urls.py
from django.urls import path
from accounts import views
urlpatterns = [
path('',views.home, name="home"),
path('product/',views.products, name="product"),
path('customer/<str:pkid>/',views.customer, name="customer"),
path('create_order/<str:pk>/',views.createOrder, name="create_order"),
path('update_order/<str:pk>/',views.updateOrder, name="update_order"),
path('delete_order/<str:pk>/',views.deleteOrder, name="delete_order"),
]
views.py
def createOrder(request, pk):
customer = Customer.objects.get(id=pk)
form = OrderForm(initial={'customer':customer})
if request.method == 'POST':
form = OrderForm(request.POST)
if form.is_valid:
form.save()
return redirect('/')
context = {'form':form}
return render(request, 'accounts/order_form.html', context)
order_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<form action="" method="POST">
{% csrf_token %}
{{ form }}
<input type="submit" name="Submit">
</form>
{% endblock %}
customer.html`
{% extends 'accounts/main.html' %}
{% block content %}
<br>
<div class="row" style="margin: auto;">
<div class="col-md">
<div class="card card-body">
<h5>Customer:{{customer.name}}</h5>
<hr>
Update Customer
Place Order
</div>
</div>
<div class="col-md">
<div class="card card-body">
<h5>Contact Information</h5>
<hr>
<p>Email: {{customer.email}}</p>
<p>Phone: {{customer.phone}}</p>
</div>
</div>
<div class="col-md">
<div class="card card-body">
<h5>Total Orders</h5>
<hr>
<h1 style="text-align:center;padding:10px">{{total_orders}}</h1>
</div>
</div>
</div>
<br>
<div class="row" style="margin: auto;">
<div class="col">
<div class="card card-body">
<form method="get">
<button class="btn btn-primary" type="submit">Search</button>
</form>
</div>
</div>
</div>
<br>
<div class="row" style="margin: auto;">
<div class="col-md">
<div class="card card-body">
<table class="table table-sm">
<tr>
<th>Product</th>
<th>Category</th>
<th>Date Ordered</th>
<th>Status</th>
<th>Update</th>
<th>Remove</th>
</tr>
{% for order in orders %}
<tr>
<td>{{order.product.name}}</td>
<td>{{order.product.category}}</td>
<td>{{order.date_created}}</td>
<td>{{order.status}}</td>
<td><a class="btn btn-sm btn-warning" href="{% url 'update_order' order.id %}">Update</a></td>
<td><a class="btn btn-sm btn-danger" href="{% url 'delete_order' order.id %}">Remove</a></td>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
{% endblock %}
The NoReverseMatch error is saying that Django cannot find a matching url pattern for the url you've provided in any of your installed app's urls.
In your HTML write action=" {%url 'create_order' order.id%}"

Django : How can I update my views? url problem

Like below code, I made update view but it doesn't work. after I click the , it doesn't work an just
"GET /moneylogs/update/7/ HTTP/1.1" 200 6243
console log printed. the page remain like just refresh.
How can I update my moneylog?
views.py
class moneylog_update(UpdateView):
model = moneylog_models.Moneylog
form_class = forms.UpdateMoneylogForm
template_name = "moneylogs/update.html"
def form_valid(self, form):
moneylog = form.save(commit=False)
moneybook = moneybook_models.Moneybook.objects.get(
pk=self.kwargs["pk"])
moneylog.save()
form.save_m2m()
return redirect(reverse("moneybooks:detail", kwargs={'pk': moneybook.pk}))
urls.py
app_name = "moneylogs"
urlpatterns = [
path("create/<int:pk>/",
views.moneylog_create.as_view(), name="create"),
path("update/<int:pk>/",
views.moneylog_update.as_view(), name="update"),
path("<int:moneybook_pk>/delete/<int:moneylog_pk>/",
views.moneylog_delete, name="delete"),
]
moneylog_form_update.html
<div class="input {% if field.errors %}has_error{% endif %}">
<div class="flex">
<div class="w-1/4">
{{form.memo.label}}
</div>
<div class="w-3/4 border-b my-2 py-3">
{{form.memo}}
</div>
</div>
{% if form.memo.errors %}
{% for error in form.memo.errors %}
<span class="text-red-700 font-medium text-sm">{{error}}</span>
{% endfor %}
{% endif %}
</div>
<a href="{% url 'moneylogs:update' moneylog.pk %} ">
<div class="px-2 py-1 rounded bg-red-500 text-white">{{cta}}</div>
</a>
Since Update view processes the form on a post request, you need HTML form with post request to submit your data.
<form method="post" action="{% url 'moneylogs:update' moneylog.pk %}">
<div class="input {% if field.errors %}has_error{% endif %}">
<div class="flex">
<div class="w-1/4">
{{form.memo.label}}
</div>
<div class="w-3/4 border-b my-2 py-3">
{{form.memo}}
</div>
</div>
{% if form.memo.errors %}
{% for error in form.memo.errors %}
<span class="text-red-700 font-medium text-sm">{{error}}</span>
{% endfor %}
{% endif %}
</div>
<input type="submit" value="{{cta}}" />
</form>
<a></a> will hit the server using the GET request.

Form Validation Not Displaying on Form

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

NoReverseMatch Django url issue

I am trying to implement a typical url in my django project however i keep getting the error meassage. I have checked my urls, views and html code where i have passed in the KWARGS. I have no clue what went wrong here please help?
The home.html uses user_profile_detail in the template
userprofile/home.html
<div class="sidebar-fixed position-fixed side_nav_bar ">
<a class="logo-wrapper waves-effect">
<img src="/" class="img-fluid" alt="">
</a>
<div class="list-group list-group-flush">
**<a href="{% url 'userprofile:dashboard' user_profile_detail.slug %}" class="list-group-item {% if request.path == dashboard %}active{% endif %} waves-effect">
<i class="fa fa-pie-chart mr-3"></i>Dashboard
</a>**
<a href="{% url 'userprofile:profile' user_profile_detail.slug %}" class="list-group-item {% if request.path == profile %}active{% endif %} list-group-item-action waves-effect">
<i class="fa fa-user mr-3"></i>Profile</a>
<a href="{% url 'userprofile:watchlist' user_profile_detail.slug %}" class="list-group-item {% if request.path == watchlist %}active{% endif %} list-group-item-action waves-effect">
<i class="fa fa-eye mr-3" aria-hidden="true"></i>WatchList</a>
<a href="{% url 'userprofile:blog' user_profile_detail.slug %}" class="list-group-item {% if request.path == blog %}active{% endif %} list-group-item-action waves-effect">
<i class="fa fa-book mr-3" aria-hidden="true"></i>My Blogs</a>
<a href="{% url 'userprofile:history' user_profile_detail.slug %}" class="list-group-item {% if request.path == history %}active{% endif %} list-group-item-action waves-effect">
<i class="fa fa-history mr-3" aria-hidden="true"></i>My Browsing History</a>
</div>
</div>
MODELS.PY
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
slug = models.SlugField(blank=True, unique=True)
VIEWS.PY
def dashboard_view(request, slug):
userprofile = Profile.objects.get(slug=slug)
user_viewed_object = userprofile.objectviewed_set.first()
user_blog = userprofile.userblog_set.first()
user_watchlist = userprofile.watchlist_set.first()
context = {
'user_profile_detail': userprofile,
'user_blog': user_blog,
'user_watchlist': user_watchlist,
'user_viewed_object': user_viewed_object,
'page_name': "Dashboard"
}
print(userprofile.slug)
return render(request, 'userprofile/home.html', context)
def profile_view(request, slug):
user_profile_detail = Profile.objects.get(slug=slug)
if request.method == 'POST':
form = ProfileForm(request.POST or None, request.FILES, instance=user_profile_detail)
if form.is_valid():
print(form)
form.save(commit=False)
user_profile_detail = request.user
form.save()
return HttpResponseRedirect('/')
context = {
'profile': user_profile_detail,
'page_name': 'Profile',
'form': form
}
return render(request, 'userprofile/profile.html', context)
URLS.PY
app_name = 'userprofile'
urlpatterns = [
path('<slug:slug>', dashboard_view, name="dashboard"),
path('<slug:slug>/user_profile/', profile_view, name='profile'),
path('<slug:slug>/watchlist/', watchlist_view, name='watchlist'),
path('<slug:slug>/blog/', userblog_view, name="blog"),
path('<slug:slug>/history/', user_history, name="history"),
]
ERROR MESSAGE:
NoReverseMatch at /profile/jacklit/user_profile/
Reverse for 'dashboard' with arguments '('',)' not found. 1 pattern(s) tried: ['profile\\/(?P<slug>[-a-zA-Z0-9_]+)$']
profile.html
{% extends 'userprofile/dashboard.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container-fluid mt-5">
{% include 'userprofile/dashboard_head.html' %}
{% include 'userprofile/large_center_modal.html' %}
<div class="card">
<h2 class="my-3 mx-3"><i class="fa fa-user mr-3" aria-hidden="true"></i>My Profile</h2>
<hr >
<div class="row my-5 mx-1">
<div class="col-3 text-center pl-3">
{% if profile.profile_picture %}
<img src="{{ profile.profile_picture.url }}" alt=""
class="img-fluid z-depth-1-half rounded-circle">
{% endif %}
<div style="height: 10px"></div>
<p class="title mb-0">{{ profile.first_name }} {{ profile.last_name }}</p><br>
<p class="title mb-0" style="font-size: 13px">{{ profile.role }}</p><br>
<p class="title mb-0"><b>Joined: </b>{{ profile.joined }}</p><br><br>
{% if request.user == profile.user %}
Edit Profile
{% endif %}
</div>
<div class="col-9">
<h3><u>Biography</u></h3>
<h6>{{ profile.biography }}</h6>
<hr>
<h6><i class="fa fa-envelope mr-3" aria-hidden="true"></i>Email Address: {{ profile.email }}</h6>
<h6><i class="fa fa-phone mr-3" aria-hidden="true"></i>Office Number:{{ profile.office_number }}</h6>
<h6><i class="fa fa-mobile-phone mr-3" aria-hidden="true"></i>Phone Number: {{ profile.phone_number }}</h6>
<br><br>
<h3><u>Contact Information</u></h3>
<h6>Email: {{ profile.email }}</h6>
<h6>Office: {{ profile.office_number }}</h6>
<h6>Phone: {{ profile.phone_number }}</h6><br><br>
<h3><u>Social Medias</u></h3>
<h6><i class="fa fa-google-plus mr-3"></i>Google Plus:</h6>
<h6><i class="fa fa-facebook mr-3"></i>Facebook: </h6>
<h6><i class="fa fa-twitter mr-3"></i>Twitter: </h6>
<h6><i class="fa fa-linkedin mr-3"></i>LinkedIn: </h6>
</div>
</div>
</div>
</div>
{% endblock %}
Large_center_Modal.html
<form action="{% url 'userprofile:profile' user_profile_detail.slug %}" enctype="multipart/form-data" method="post">
{% csrf_token %}
<div class="modal fade" id="centralModalLGInfoDemo" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg modal-notify modal-info" role="document">
<!--Content-->
<div class="modal-content">
<!--Header-->
<div class="modal-header">
<p class="heading lead">Update my Profie</p>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true" class="white-text">×</span>
</button>
</div>
<!--Body-->
<div class="modal-body">
<div class="">
<div class="col-10">{{ form | crispy }}</div>
</div>
</div>
<!--Footer-->
<div class="modal-footer">
<button type="submit" class="btn btn-outline-info waves-effect">Update</button>
</div>
</div>
<!--/.Content-->
</div>
</div>
</form>
Your context dict has profile key: 'profile': user_profile_detail,. So in template you should use profile instead of user_profile_detail:
"{% url 'userprofile:dashboard' profile.slug %}"

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':