How to delete a comment from the comment section in flask - python

I have a comment section and I want to allow users to delete their comments, however when I click the delete button the comment doesn't get delete, and over that a new comment with nothing get add.
Here is my python code. When I tried to print "delete" I got none in my terminal window
#app.route("/deletecomment", methods=["GET", "POST"])
#login_required
def deletecomment():
delete = request.args.get("delete")
print(delete)
#if the method is get
if request.method == "GET":
#testing purpose
print("vvv")
print(delete)
#delete the comment
comments = db.execute("DELETE FROM comment WHERE comment=?",delete)
return redirect (url_for("addcomment"))
Here is my html. Is it bad to have a form inside another form?
<form action="/comment" method="get">
<div class="row bootstrap snippets bootdeys">
<div class="col-md-8 col-sm-12">
<div class="comment-wrapper">
<div class="panel panel-info">
<div class="panel-heading">
Comment panel
</div>
<div class="panel-body">
<textarea name="comment" class="form-control" placeholder="write a comment..." rows="3"></textarea>
<br>
<button type="submit" class="btn btn-info pull-right">Post</button>
<div class="clearfix"></div>
<hr>
{% for comments in comments %}
<ul class="media-list">
<!--<button type="submit" class="btn btn-danger">Delete</button>-->
<li class="media">
<a href="#" class="pull-left">
<img src="https://bootdey.com/img/Content/user_1.jpg" alt="" class="img-circle">
</a>
<div class="media-body">
<!--<button type="submit" class="btn btn-danger">Delete</button>-->
<span class="text-muted pull-right">
</span>
<!--<button type="submit" class="btn btn-danger">Delete</button>-->
<strong class="text-success">{{comments.user}}</strong>
<form action="/deletecomment" method="get">
<p name="delete">
{{comments.comment}}
</p>
<button id="but" type="submit" class="btn btn-danger">Delete</button>
</form>
</div>
</li>
</div>
</ul>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
</form>

Put the comment ID as a URL parameter in the action URL
<form action="/deletecomment?delete={{comment.id}}" method="get">
and change the controller to use the parameter as the ID in the query.
#app.route("/deletecomment", methods=["GET", "POST"])
#login_required
def deletecomment():
#if the method is get
if request.method == "GET":
delete = request.args.get("delete")
print(delete)
#testing purpose
print("vvv")
print(delete)
#delete the comment
comments = db.execute("DELETE FROM comment WHERE id=?",delete)
return redirect (url_for("addcomment"))

Related

When i delete last comment was added an empty comment get add

I'm trying to build a comment section in my flask web app. My code works fine, but when I try to delete the last comment that was just added it doesn't delete and I also got an empty comment. this just happens when I try to delete the last comment.
Here is my python code
#app.route("/addcomment", methods=["GET", "POST"])
#login_required
def addcomment():
global book
if request.method == "GET":
book = request.args.get("book")
comments = db.execute("SELECT * FROM comment WHERE book_id=? ORDER BY Timestamp DESC",book)
# print(comments)
return render_template ("comment.html", comments=comments)
else:
comment = request.form.get("comment")
id = session["user_id"]
user = db.execute("SELECT username FROM users WHERE id=?", id)
db.execute("INSERT INTO comment (comment, user,book_id) VALUES(?, ?,?)",comment, user[0]["username"],book)
return redirect (request.referrer)
#app.route("/deletecomment/<comment_id>", methods=["GET", "POST"])
#login_required
def deletecomment(comment_id):
#get the comment that will delete
#if the method is get
delete = request.args.get("delete")
#delete the comment
db.execute("DELETE FROM comment WHERE id=?",comment_id)
print("Djyhhh")
return redirect (request.referrer)
And if it's important here is my comment.html
<form action="{{url_for('addcomment')}}" method="post">
<div class="row bootstrap snippets bootdeys">
<div class="col-md-8 col-sm-12">
<div class="comment-wrapper">
<div class="panel panel-info">
<div class="panel-heading">
Comment panel
</div>
<div class="panel-body">
<textarea name="comment" class="form-control" placeholder="write a comment..." rows="3"></textarea>
<br>
<button type="submit" class="btn btn-info pull-right">Post</button>
<div class="clearfix"></div>
<hr>
{% for comments in comments %}
<ul class="media-list">
<!--<button type="submit" class="btn btn-danger">Delete</button>-->
<li class="media">
<a href="#" class="pull-left">
<img src="https://bootdey.com/img/Content/user_1.jpg" alt="" class="img-circle">
</a>
<div class="media-body">
<!--<button type="submit" class="btn btn-danger">Delete</button>-->
<span class="text-muted pull-right">
</span>
<!--<button type="submit" class="btn btn-danger">Delete</button>-->
<strong class="text-success">{{comments.user}}</strong>
<form action="/deletecomment/{{comments.id}}" method="get">
<p>
{{comments.comment}}
</p>
<button id="but" type="submit" class="btn btn-danger">Delete</button>
</form>
</div>
</li>
</div>
</ul>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
</form>

How to Submit and Retrieve data in one view in Django?

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
>

Django form validation on clicking Next instead of Submit

I have this HTML page in which I have 2 forms. Django is not checking the form validation for the first form. I want it to check form validation for the first form.
This is the Html Code
<form method="post" id="msform">
{% csrf_token %}
<!-- progressbar -->
<ul id="progressbar">
<li class="active" id="conf"><strong>Configuration</strong></li>
<li id="auth"><strong>Authentication</strong></li>
</ul>
<div class="progress">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuemin="0" aria-valuemax="100"></div>
</div> <br> <!-- fieldsets -->
<fieldset>
<div class="form-card">
<div class="row">
<div class="col-7">
<h2 class="fs-title">Cluster Configuration</h2>
</div>
<div class="col-5">
<h2 class="steps">Step 1 - 2</h2>
</div>
</div>
{{ form1|crispy }}
</div> <input type="button" name="next" class="next action-button" value="Next" />
</fieldset>
<fieldset>
<div class="form-card">
<div class="row">
<div class="col-7">
<h2 class="fs-title">Authentication</h2>
</div>
<div class="col-5">
<h2 class="steps">Step 2 - 2</h2>
</div>
</div>
{{ form2|crispy }}
</div><button type="submit" class="btn btn-primary" >Next</button>
</fieldset>
</form>
If I use submit button instead of next for the first form then neither the second form opens nor the form is submitted (i.e. nothing is happening).
So I think the issue might be because you have over arching form tag, and two forms sent inside it from your view function:
What you have right now is this:
<form>
<fieldset>
<! –– Your Code ––>
{{ form1|crispy }}
</div> <input type="button" name="next" class="next action-button" value="Next" />
</fieldset>
<fieldset>
<! –– Your Code ––>
{{ form2|crispy }}
</div><button type="submit" class="btn btn-primary" >Next</button>
</fieldset>
</form>
As you can see from the above simplification of your original post, you have two forms templated inside one form tag. Thus when you hit either of the the submit button both of them gets sent.
If I am not mistaken, I believe what you might want is something along the lines of this:
<form name="form1" id="form1">
<fieldset>
<! –– Your Code ––>
{{ form1|crispy }}
</div> <input type="button" name="form1" class="next action-button" value="Next1" />
</fieldset>
</form>
<form name="form2" id="form2">
<fieldset>
<! –– Your Code ––>
{{ form1|crispy }}
</div> <input type="button" name="form2" class="next action-button" value="Next2" />
</fieldset>
</form>
Take note of the fact that I have changed your button names, as well as added ids and names to each form, you might also want to add ids as well as unique values to your buttons as well. This would help you build if conditions to determine which form has been submitted and so on, in your view function
Here is a link that describe how to handle this in more depth.
Which is all nice and dandy, but the conclusion of that linked page is this:
Let me know if it helps, feel free to ask more if you do not understand/the changes does not work

How to use registration(signup/login) modal(bootstrap template) with django views?

I am new to programming. I found nice bootstrap modal for registration, so i put it to my html code and it looks nice but nothing can be pressed or post.
Before i was using django and UserCreationForm without modals. So help me to concatenate these two things:
so this is my bootstrap modal that i found
<!-- Modal -->
<div class="modal fade" id="elegantModalForm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<!--Content-->
<div class="modal-content form-elegant">
<!--Header-->
<div class="modal-header text-center">
<h3 class="modal-title w-100 dark-grey-text font-weight-bold my-3" id="myModalLabel"><strong>Войти</strong></h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<!--Body-->
<form type="post" action="{% url 'common:login' %}">
<div class="modal-body mx-4">
<!--Body-->
<div class="md-form mb-5">
<input type="email" name="useremail" id="Form-email1" class="form-control validate">
<label data-error="wrong" data-success="right" for="Form-email1">Ваша почта</label>
</div>
<div class="md-form pb-3">
<input type="password" id="Form-pass1" class="form-control validate">
<label data-error="wrong" data-success="right" for="Form-pass1">Пароль</label>
<p class="font-small blue-text d-flex justify-content-end">Забыли <a href="#" class="blue-text ml-1">
пароль?</a></p>
</div>
<div class="text-center mb-3">
<button type="button" class="btn blue-gradient btn-block btn-rounded">ок</button>
</div>
<p class="font-small dark-grey-text text-right d-flex justify-content-center mb-3 pt-2"> или войти
с помощью:</p>
<div class="row my-3 d-flex justify-content-center">
<!--Facebook-->
<button type="button" class="btn btn-white btn-rounded mr-md-3 z-depth-1a"><i class="fab fa-facebook-f text-center"></i></button>
<!--Twitter-->
<button type="button" class="btn btn-white btn-rounded mr-md-3 z-depth-1a"><i class="fab fa-twitter"></i></button>
<!--Google +-->
<button type="button" class="btn btn-white btn-rounded z-depth-1a"><i class="fab fa-google-plus-g"></i></button>
</div>
</div>
</form>
<!--Footer-->
<div class="modal-footer mx-5 pt-3 mb-1">
<p class="font-small grey-text d-flex justify-content-end">Первый раз? <a href="{% url 'common:signup' %}" class="blue-text ml-1">
Зарегистрируйся</a></p>
</div>
</div>
<!--/.Content-->
</div>
</div>
<!-- Modal -->
and this is my views.py before using modal:
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('index')
else:
form = UserCreationForm()
return render(request, 'registration/signup.html', {'form': form})
So help me to show how it should work. Actually i used to use {{form.as_p}} but how should i do in this case?
I think what you are looking for is Django Forms
official doc- https://docs.djangoproject.com/en/2.2/topics/forms/
other- ( https://www.tutorialspoint.com/django/django_form_processing)
First, you need to create a form model and define the fields which you are taking as input.
Here is a sample-
from django import forms
class LoginForm(forms.Form):
user = forms.CharField(max_length = 100)
password = forms.CharField(max_length =100)
Then, you need to modify the view according to form. Here is a sample-
def login(request):
username = "not logged in"
if request.method == "POST":
#Get the posted form
MyLoginForm = LoginForm(request.POST)
if MyLoginForm.is_valid():
username = MyLoginForm.cleaned_data['username']
else:
MyLoginForm = Loginform()
return render(request, 'loggedin.html', {"username" : username})
and if you are sending data through POST, don't forget to add csrf token just in Html file.
form type="post" action="{% url 'common:login' %}">
{% csrf_token %}

form in modal action not doing anything

This is some code from my index.html. My issue is that the action on the form in the modal is not working (no error, just doing nothing) yet the form outside the model is working fine (commented test button). The model is opening fine and seems correctly formatted, yet the 'yes' button does nothing but closes the modal. The problem does not seem to be in the URL. Any help would be much appreciated. I am using django by the way
{% for patient in all_patients %}
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-body">
<!-- Name -->
<h4>{{ patient }}</h4>
<!-- View Details -->
View Details
<!-- Edit Details -->
Edit Details
<!-- Delete Patient -->
<input type="hidden" name="patient_id" value="{{ patient.id }}" />
<button type="submit" class="btn btn-default btn-sm" data-toggle="modal" data-target="#patient_id">
<span class="glyphicon glyphicon-trash"></span>
</button>
<!-- Modal -->
<div class="modal fade" id="patient_id" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Confirm delete</h4>
</div>
<div class="modal-body">
<p>Are you sure you want to delete {{ patient }}?</p>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default" data-dismiss="modal">No</button>
<form action="{% url 'patients:patient-delete' patient.id %}" method="post" style="display: inline;">
{% csrf_token %}
<button type="submit" class="btn btn-danger" data-dismiss="modal">Yes</button>
</form>
</div>
</div>
</div>
</div>
<!-- test button -->
<form action="{% url 'patients:patient-delete' patient.id %}" method="post" style="display: inline;">
{% csrf_token %}
<button type="submit" class="btn btn-danger" data-dismiss="modal">Delete</button>
</form>
</div>
</div>
</div>
{% cycle '' '' '' '' '' '<div class="clearfix visible-lg"></div>' %}
{% endfor %}

Categories

Resources