I have a little confusion in my app.
I have an HTML page in which I have added one form (form data submitting) and one table (to display the submitted data).
For which I have a view that submit and retrieve the data at the same time but unfortunately, data is successfully storing in the table but in retrieving time, it gives me the error which is mentioned below.
Error
NoReverseMatch at /staff/add_staff_type
Reverse for 'student_profile' with keyword arguments '{'id': ''}' not
found. 1 pattern(s) tried: ['student/profile/(?P[0-9]+)$']
Views.py
def add_staff_type(request):
if request.method == 'POST':
designation = request.POST.get('designation')
salary = request.POST.get('salary')
datetime = request.POST.get('datetime')
add_staff_type = staff_type.objects.create(designation=designation, salary=salary, datetime=datetime)
add_staff_type.save()
messages.info(request, "Staff type has been Added.")
return redirect('add_staff_type')
else:
#fetching records from the database table
display_staff_type = staff_type.objects.all()
return render(request, 'staff/staff_type.html',{'display_staff_type':display_staff_type})
urls.py
urlpatterns = [
path("", views.index, name="index"),
path("student/Add_Student", views.Add_Student, name="Add_Student"),
path("student/display_students", views.Display_Student, name="display_students"),
path("student/edit/<int:id>", views.student_edit, name="student_edit"),
path("student/update/<int:id>", views.student_update, name="student_update"),
path("student/profile/<int:id>", views.student_profile, name="student_profile"),
path("student/delete/<int:id>", views.student_delete, name="student_delete"),
#below url is for staff_type on which i am currently workin
path("staff/add_staff_type", views.add_staff_type, name="add_staff_type"),
]
staff_type.html
<div class="card">
<div class="card-header">
<h3 class="card-title">Add Staff Type</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form
class="needs-validation"
action="add_staff_type"
method="POST"
enctype="multipart/form-data"
novalidate
>
{% csrf_token %}
<div class="card-body">
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationCustom01">Designation</label>
<input
type="text"
class="form-control"
id="validationCustom01"
placeholder="Acountant, Librarian, Teacher"
name="designation"
required
/>
<div class="valid-feedback">Looks good!</div>
</div>
<div class="col-md-4 mb-3">
<label for="validationCustom04">Salary</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Rs.</span>
</div>
<input type="number" class="form-control" id="validationCustom04" name="salary" min="0">
<div class="valid-feedback">Looks good!</div>
</div>
</div>
<div class="col-md-4 mb-3">
<label for="validationCustom03">Date and Time</label>
<input
type="datetime-local"
class="form-control"
id="validationCustom03"
placeholder="MM/DD/YYY"
name="datetime"
required
/>
<div class="valid-feedback">Looks good!</div>
</div>
</div>
<!--
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationCustomUsername">Username</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupPrepend">#</span>
</div>
<input type="text" class="form-control" id="validationCustomUsername" placeholder="Username" aria-describedby="inputGroupPrepend" required>
<div class="invalid-feedback">
Please choose a username.
</div>
</div>
</div>
-->
<button class="btn btn-primary" type="submit">Add Staff Type</button>
</div>
</form>
</div>
<div class="card">
<div class="card-header">
<h3 class="card-title">Available Staff Types</h3>
</div>
<!-- /.card-header -->
<div class="card-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Designation</th>
<th>Salary</th>
<th>Entry Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for staff_type in display_staff_type %}
<tr>
<td>{{staff_type.designation}}</td>
<td>{{staff_type.salary}}</td>
<td>{{staff_type.datetime}}</td>
<td>
<a href="{% url 'student_profile' id=student.id %}">
<i class="far fa-eye"></i>
</a>
<a href="{% url 'student_edit' id=student.id %}">
<i class="far fa-edit"></i>
</a>
<a href="{% url 'student_delete' id=student.id %}">
<i class="far fa-trash-alt"></i>
</a>
</td>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- /.card-body -->
</div>
You can revise your view function to this:
def add_staff_type(request):
if request.method == 'POST':
designation = request.POST.get('designation')
salary = request.POST.get('salary')
datetime = request.POST.get('datetime')
add_staff_type = staff_type.objects.create(designation=designation, salary=salary, datetime=datetime)
add_staff_type.save()
messages.info(request, "Staff type has been Added.")
# this can also be return redirect('staff:add_staff_type')
return redirect('add_staff_type')
#fetching records from the database table
display_staff_type = staff_type.objects.all()
return render(request, 'staff/staff_type.html',{'display_staff_type':display_staff_type})
Since you are calling the same view and serving data to the same form and view you can remove the action value of the form which goes like this:
<form
class="needs-validation"
action=""
method="POST"
enctype="multipart/form-data"
novalidate
>
Related
I was making a blog website, I am new to django and I don't know how to add comment without refreshing the page itself. I was trying to do with the help of tutorial but they are not helping anymore
here is my html file
<div class="row">
<div class="comment-section col-8">
{% for i in data %}
<li>{{i}}</li><br>
{% endfor %}
</div>
<div class="col-4">
<h4 class="m-3">{{comments.count}} Comments...</h4>
{% for j in comments %}
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">{{j.title}}</h5>
<h6 class="card-subtitle mb-2 text-muted">{{j.visitor.name}}</h6>
<p class="card-text">{{j.description}}</p>
</div>
</div>
{% endfor %}
<hr>
<h3>Comment here</h3>
<form method="post" id="comment-form">
{% csrf_token %}
<input type="hidden" id="contentId" name = 'contentId' value="{{ result.id }}">
<div class="form-group">
<input type="hidden" id="name" name="name" class="form-control" value="{{request.session.user.name}}" readonly>
</div>
<div class="form-group">
<label for="title">Title</label>
<input type="text" id="title" name="title" class="form-control">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" id="description" cols="30" rows="5" class="form-control"></textarea>
</div>
<button type="submit" class="btn btn-secondary">Submit</button>
</form>
</div>
here is my views.py file
def addComment(request):
if request.method == 'POST':
post_id = request.POST['contentId']
title = request.POST['title']
description = request.POST['description']
user = request.session['user']['id']
con = Comment(
post_id=post_id,
title=title,
description=description,
visitor_id=user,
)
con.save()
print()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
This question already has answers here:
Flask view return error "View function did not return a response"
(3 answers)
Closed 8 months ago.
flask code
#bp.route('/delete/<int:id>')
#login_required
def delete_tracker(id):
if Trackers.user_id == current_user.id:
trackers = Trackers.query.filter_by(id=id).first()
print(trackers)
db.session.delete(trackers)
db.session.commit()
return redirect(url_for("authen.dashboard"))
Html code- look for /delete url t bottom there is the error
{% extends "base.html" %}
{% block title %} Dashboard {% endblock %}
{% block content %}
<nav class="sidenav">
<div class="main-buttons">
<a class="nav-link active" id="trackers" aria-current="page" href="/dashboard">Trackers</a>
<a class="nav-link active" id="goals" aria-current="page" href="/goals">Goals</a>
<div>
</nav>
<div id="dashbar">
<nav class="navbar bg-light">
<div class="container-fluid">
<button type="button" class="btn btn-outline-dark" data-bs-toggle="modal" data-bs-target="#exampleModal">
Add Tracker
</button>
<form method="POST">
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add a Tracker</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<label for="tracker_name" class="col-form-label">Tracker Name:</label>
<input type="text" class="form-control" id="tracker_name" name="tracker_name"
placeholder="Enter a Tracker name">
<div class="from-fieldset" style="width:200px;">
<label for="tracker_type" class="form-label">Choose a Tracker type:</label>
<select id="tracker_type" name="tracker_type">
<option value="">choose Tracker type</option>
{% for t in data_trackers %}
<option value="{{t.name}}">{{t.name}}</option>
{% endfor %}
<label for="tracker_description " class="col-form-label">Description</label>
<input type="text" class="form-control" id="tracker_description" name="tracker_description"
placeholder="Enter Description">
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-light border-dark">Submit</button>
</div>
</div>
</div>
</div>
</form>
<form class="d-flex" role="search">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</nav>
</div>
<div class="wrapper">
<div class="container-tracker">
{% for track in user.trackers %}
<div class="tra">
<h3 id="trackername"> {{track.tracker_name}}</h3>
<div class="dropdown-container" tabindex="-1">
<form method="GET" action="/delete/{{track.id}}">
<button type="submit" class="btn btn-outline-light">Delete</button>
</form>
<div class="three-dots"></div>
<div class="dropdown">
<a href="#">
<div>Records and Graphs</div>
</a>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
( in form method=GET , the delete url is there and the flask code is at top for that endpoint
if I remove if condition in the delete_tracker() fucntion that is if user.id==current_user.id then I will get a different error that is , this is for session 2nd but this is 3rd session something like this, so my file I want to delete is different session )
can you try to change your line
#bp.route('/delete/<int:id>')
to
#bp.route('/delete/<track.id>')
Looked a lot into a solution of my issue but didn't get it right.
I want to show the errors in the Modal form and don't close until it is valid.
For now I am able to get the errors in the customer.html page after the Modal closes.
Forms.py
class CustomerForm(forms.ModelForm):
#...... Form Widget HERE ......
class Meta:
model = Customer
fields =['customername','customerlogo','emailaddress','addressLine1','membership','pobox','phonenumber','emailaddress']
Views.py
def customer(request):
context = {}
customers = Customer.objects.all()
context['customers'] = customers
if request.method == 'GET':
form = CustomerForm()
context['form'] = form
return render(request, 'Mainapp/customer.html', context)
if request.method == 'POST':
form = CustomerForm(request.POST, request.FILES)
if form.is_valid():
form.save()
messages.success(request, 'New Client Added')
return redirect('customer')
else:
messages.error(request, form.errors)
return redirect('customer')
return render(request, 'Mainapp/customer.html', context)
HTML MODAL
<div id="create-modal" data-backdrop="static" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Customer Details</h4>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body p-4" data-backdrop="static">
<div id="error">
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert-dismissible alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% endif %}
</div>
<form action="#" action="Mainapp/customer.html" id="customerfrm" method="POST">
<!-- onsubmit="submitForm(event)"-->
{% csrf_token %}
<div class="row">
<div class="col-lg-9">
<div class="mb-3">
<label for="customername" class="form-label">Customer Name<span class="text-danger">*</span></label>
{{form.customername}}
</div>
</div>
</div>
<div class="row">
<div class="col-lg-9">
<div class="mb-3">
<label for="emailaddress" class="form-label">Email Address<span class="text-danger">*</span></label>
{{form.emailaddress}}
</div>
</div>
<div class="col-lg-3">
<div class="mb-3">
<label for="customermembership" class="form-label">Membership<span class="text-danger">*</span></label>
{{form.membership}}
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="mb-3">
<label for="customeraddress" class="form-label">Address<span class="text-danger">*</span></label>
{{form.addressLine1}}
</div>
</div>
<div class="col-lg-6">
<div class="mb-3">
<label for="customerlogo" class="form-label">Logo</label>
{{form.customerlogo}}
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="mb-3">
<label for="POBox" class="form-label">POBox<span class="text-danger">*</span></label>
{{form.pobox}}
</div>
</div>
<div class="col-lg-6">
<div class="mb-3">
<label for="customernumber" class="form-label">Phone Number<span class="text-danger">*</span></label>
{{form.phonenumber}}
</div>
</div>
</div>
<div class="text-end">
<button type="submit" class="btn btn-primary waves-effect waves-light" >Submit</button>
<a type="reset" href= "{% url 'customer' %}" class="btn btn-secondary waves-effect">Cancel</a>
</div>
</form>
</div>
</div>
</div>
</div><!-- /.modal -->
I'm trying to shape up my login page form as per django. I'm facing an extra >" characters at the end of my entry fields.
There is the image error. See image below.
You might need to pay attention to right up corner of the input fields. Is there any idea, where is this "> came from ? Thanks for your time!
<form method="POST"> {% csrf_token%}
<div class="field">
<span class="fa fa-user"></span>
<input type="text" required placeholder="Email Adress" for="{{form.username}}">
</div>
<div class="field space">
<span class="fa fa-lock"></span>
<input type="password" class="pass-key" required placeholder="Password" for="{{form.password}}">
<span class="show">SHOW</span>
</div>
<div class="pass">
Forgot Password?
</div>
<div class="field">
<input type="submit" value="LOGIN">
</div>
</form>
There is the full code
{% load static %}
<!DOCTYPE html>
<!-- Created By CodingNepal -->
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<!-- Somehow I got an error, so I comment the title, just uncomment to show -->
<!-- <title>Transparent Login Form UI</title> -->
<link href="{% static 'css/login.css' %}" rel="stylesheet" />
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
</head>
<body>
<div class="bg-img">
<div class="content">
<header>Welcome to Norga</header>
<form method="POST"> {% csrf_token%}
<div class="field">
<span class="fa fa-user"></span>
<input type="text" required placeholder="Email Adress" for="{{form.username}}">
<!-- {{form.username}} -->
</div>
<div class="field space">
<span class="fa fa-lock"></span>
<input type="password" class="pass-key" required placeholder="Password" for="{{form.password}}">
<!-- {{form.password}} -->
<span class="show">SHOW</span>
</div>
<div class="pass">
Forgot Password?
</div>
<div class="field">
<input type="submit" value="LOGIN">
</div>
</form>
<div class="login">
Or login with</div>
<div class="links">
<div class="facebook">
<i class="fab fa-facebook-f"><span>Facebook</span></i>
</div>
<div class="instagram">
<i class="fab fa-instagram"><span>Instagram</span></i>
</div>
</div>
<div class="signup">
Don't have account?
Signup Now
</div>
<br>
<div class="signup">
Email verification
Send Again
</div>
</div>
</div>
<script>
const pass_field = document.querySelector('.pass-key');
const showBtn = document.querySelector('.show');
showBtn.addEventListener('click', function(){
if(pass_field.type === "password"){
pass_field.type = "text";
showBtn.textContent = "HIDE";
showBtn.style.color = "#3498db";
}else{
pass_field.type = "password";
showBtn.textContent = "SHOW";
showBtn.style.color = "#222";
}
});
</script>
</body>
</html>
I have solved my problem with re-coding my login views. I was using the django auth_views.LoginView , however it was not fit to my html scale in that way. Therefore, I came up with a new form in forms.py file and change my urls in accordance with the url in the below.
There is the solution link for the form and custimizing the loginview and there is my new form in html file in the below;
<form method="post">
{% csrf_token%}
<div class="form-group">
{{ form.non_field_errors }}
{{ form.username.errors }}
{{ form.password.errors }}
</div>
<div class="field">
<span class="fa fa-user"></span>
{{ form.username }}
</div>
<div class="field space">
<span class="fa fa-lock"></span>
{{ form.password }}
<span class="show">SHOW</span>
</div>
<div class="pass">
Forgot Password?
</div>
<div class="field">
<input type="submit" value="LOGIN">
</div>
</form>
I've a register form and a function to post the values to django via ajax, but for some reasons, the post request says 403 forbidden but the get request does the job.
I want to use post request in this functionality but it doesn't seem to work, tried putting {% csrf_form %} too within the template, but still it says 403 Forbidden. Any sugestion?
Views.py
from django.http import HttpResponse
from django.shortcuts import render
from django.views import View
class signUp(View):
def post(self, request):
return HttpResponse(" POST method successfull !!")
Urls.py
path('insert/', views.signUp.as_view()),
HTML Form:
{% extends 'base.html' %}
{% block title %}
<title> Register </title>
{% endblock %}
{% block content %}
<div class="row breadcrumb_nav">
<div class="col-md-1" ></div>
<div class="col-md-10" style="margin-bottom: 35px;">
<!-- START col-md-12 Section -->
<ol class="breadcrumb nm" >
<li> Home </li>
<li class="active"> Register </li>
</ol>
<div id="quickViewPage_error_container">
<div id="animated_image"></div>
<div id="results_container"></div>
</div>
</div>
<!--end of col-md-12 -->
<div class="col-md-1" ></div>
</div> <!-- end of row -->
<!--start of row -->
<div class="row">
<div class="col-md-1" ></div>
<div class="col-md-12"> <!-- START Right Section -->
<div class="main_shadow panel panel-default"> <!-- START OF panel panel-default-->
<div class="panel-body panel-body-padding"> <!-- -START OF PANE -->
<div class="modal-header">
<h4 class="modal-title" id="exampleModalLabel"> Register </h4>
</div>
<div class="modal-body">
<div class="panel-body"> <!-- -START OF PANE -->
<form id="signup_form" name="signup_form" method="post">
{% csrf_token %}
<div class="form-group">
<div class="row">
<div class="col-sm-6">
<label class="control-label"> eMail <span class="text-danger">*</span></label>
<input name="email" type="text" class="form-control" autocomplete="off" required>
</div>
<div class="col-sm-6">
<label class="control-label">Password <span class="text-danger">*</span></label>
<input name="password" type="password" class="form-control" autocomplete="off" data-parsley-trigger="change" required>
</div>
</div>
</div>
<input type="hidden" name="register_new_user" id="register_new_user" value="register_new_user">
<input type="submit" name="register_btn" id="register_btn" class="btn btn-primary" value="Register" style="float:left;padding-left:25px;padding-right:25px;margin-right: 25px;">
<a href="/register">
<input type="button" class="btn btn-primary" value="Register Now" style="float:left;padding-left:25px;padding-right:25px;">
</a>
</form> <!--end of Login_Management -->
</div> <!-- END OF panel-body -->
</div>
</div> <!-- END OF panel-body -->
</div> <!--/ End of Form layout -->
</div> <!-- END OF Right Section -->
<div class="col-md-1" ></div>
</div>
<!-- end of row -->
enter code here
{% endblock %}
{% block javascript %}
<script>
$('#register_btn').click(function(e) {
e.preventDefault();
$.post('/insert/', '®ister_new_user=register_new_user' +
'&csrftoken={{ csrf_token }}' , function(response) {
$('#results_container').html(response);
});
});
</script>
{% endblock %}
You are sending the data in the path like this:
$.post('/insert/', '®ister_new_user=register_new_user' +
'&csrftoken={{ csrf_token }}' , function(response) {
$('#results_container').html(response);
});
Try sending the data in the body:
$.post( '/insert/', { register_new_user: "register_new_user", csrftoken: "your_token_here" } );