HTML form button not deleting rows from sqlite database - python

I have built a forum in pythonanywhere using python and html, in which users can post information that gets inserted into a sqlite database. At the bottom of each post is a delete button that will delete the post that it's under from the database and refresh the page. Right now the delete button only refreshes the page while the post remains. I am wondering how to edit the code so that the post which the form button is attached to is deleted and the page is refreshed.
HTML Code snippet
{% for post in forumposts %}
<tr>
<td>
<h1>{{post[1]}}</h1>
<h3>{{post[3]}}</h3>
<p>{{post[2]}}</p>
<p>{{post[6]}}</p>
<img src="{{post[7]}}" alt="Wrong image link.">
<p></p>
<form action="{{ url_for('delete_post') }}" method=POST class=delete-post>
<input type=hidden value="{{ postid }}"name=post_to_delete></input>
<input type=submit></input>
</form>
</td>
</tr>
{%endfor%}
</table>
Python Code snippet
#app.route('/delete', methods=['POST'])
def delete_post():
db = connect_db()
db.execute('DELETE FROM posts WHERE postid = ?', [request.form['post_to_delete']])
db.commit()
db.close()
return redirect(url_for('forum'))

Got the code working.
HTML
{% for post in forumposts %}
<tr>
<td>
<h1>{{post[1]}}</h1>
<h3>{{post[3]}}</h3>
<p>{{post[2]}}</p>
<p>{{post[6]}}</p>
<img src="{{post[7]}}" alt="Wrong image link.">
<p></p>
<form action="{{ url_for('delete_post') }}" method=POST class=delete-post>
<input type=hidden value={{post[0]}} name=post_to_delete></input>
<input type=submit value=POST></input>
</form>
</td>
</tr>
{%endfor%}
</table>
PYTHON
#app.route('/delete', methods=['POST'])
def delete_post():
if request.method == 'POST':
db = connect_db()
db.execute('DELETE FROM posts WHERE postid = ?', (request.form['post_to_delete'],))
db.commit()
db.close()
return redirect(url_for('forum'))
Hope this helps someone. :)

Related

Not able to delete an account on a login page made using flask

I'm trying to make a simple login page using python flask and MySQL. The webpage itself is being made using html, bootstrap 4 and css. I followed a tutorial to make the login page but now I want to add a way to delete an account.
This is a profile page which is visible after you login(it shows your username, password and email). The database table(called accounts) has a primary key id. The part in /// is the code I'm trying to add for creating a delete button. Please help me fix my delete account button.
#app.route('/pythonlogin/profile', methods = ['GET'])
def profile():
# Check if user is loggedin
if 'loggedin' in session:
# We need all the account info for the user so we can display it on the profile page
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM accounts WHERE id = %s', (session['id'],))
account = cursor.fetchone()
# Show the profile page with account info
return render_template('profile.html', account=account)
# User is not loggedin redirect to login page
///if request.method == 'GET':
id = session['id']
mycursor = mysql.cursor()
sql = ('DELETE from accounts WHERE id = 4;')
# return redirect(url_for('logout)')
mycursor.execute(sql)
mysql.connection.commit()///
return redirect(url_for('login'))
The following is the html part called profile.html.
{% extends 'layout.html' %}
{% block title %}Profile{% endblock %}
{% block content %}
<h2>Profile Page</h2>
<div>
<p>Your account details are below:</p>
<table>
<tr>
<td>Username:</td>
<td>{{ account['username'] }}</td>
</tr>
<tr>
<td>Password:</td>
<td>{{ account['password'] }}</td>
</tr>
<tr>
<td>Email:</td>
<td>{{ account['email'] }}</td>
</tr>
<tr>
<form action="{{ url_for('logout') }}">
<td>
<button type="submit" class="btn btn-danger">Delete Account</button>
</td>
</form>
</tr>
</table>
</div>
{% endblock %}
In the provided code I can see some mistakes (logical)
If use logged in, code after return render_template('profile.html', account=account)
will not be executed
And another problem is that you are creating the URL to logout instead of the profile page <form action="{{ url_for('logout') }}">
And better to do the form with POST method.

Multiple button in Django: Accept and Reject

I am new to Django. I am working on a project where I want accept and reject button and whenever client click on the respective button that object will go into the accept or reject template. I have no idea how can I do this.
This is my .html file which is displaying all the objects and have a accept and reject button:
<div class="body table-responsive">
<form id="form" method="POST" action = "{% url 'admin_team_detail' %}">
{% csrf_token %}
<table class="table table-hover">
<thead>
<tr>
<th>S No.</th>
<th>COMPANY NAME</th>
<th>TEAM MEMBER</th>
<th>EMAIL</th>
<th>STATUS</th>
<th><center>#</center></th>
</tr>
</thead>
<tbody>
{%for team in object%}
<tr>
<th scope="row"> {{ forloop.counter }}</th>
<td>{{team.company_name}}</td>
<td>{{team.team_member}}</td>
<td>{{team.email}}</td>
<td>-</td>
<td><center><input type="submit" value="accept" name="accept">
<input type="submit" value="reject" name="reject"></center></td>
</tr>
{% endfor %}
</tbody>
</table>
</form>
Here is views.py:
def admin_team_detail(request):
obj= Create_Team.objects.all()
print(request.method)
if request.method == 'POST':
if 'reject' in request.POST :
Create_Team.status = 'reject'
else:
Create_Team.status = 'accept'
Create_Team.save()
return render(request, "admin/team-details.html", {"object": obj})
This is rendering all the objects from database and displaying on the website.
I know that I have to make two templates for accept and reject but I don't know how it will take the objects that have a accept or reject response.
And I also want that if client click on the button then that response will be saved in the database.
And I also want to know that whether I have to add a field in my model.py for status.
First your two buttons should send the desired value to your views.py and one hidden input in order to pass the team id
<input type="submit" value="reject" name="status">
<input type="submit" value="accept" name="status">
<input type="hidden" name="id" value={{ team.id }}>
Next, in your views.py
def admin_team_detail(request):
if request.method == 'POST':
# First, you should retrieve the team instance you want to update
team = Create_Team.objects.get(id=request.POST('id'))
# Next, you update the status
if request.POST.get('status'):
team.status = request.POST.get('status')
team.save()
Note: this example assumes your Team model has a status field in order to store the reject/accept value.
class Team(models.Model):
# You existing fields...
status = models.CharField(max_length=30)
First You need to create a form for each object inside the template.
{%for team in object%}
<form method="POST">
{%csrf_token%}
<input type="hidden" name="team_id" value={{ team.id }}>
<input type="submit" value="reject" name="status">
<input type="submit" value="accept" name="status">
</form>
{% endfor %}
Now in View.py, you need to do something like this:
def admin_team_detail(request):
if request.method == 'POST':
# I am assuming Create_Team is your model where all team's are present.
team = Create_Team.objects.get(id=request.POST.get("team_id"))
team.status = request.POST.get("status")
team.save()

Search function in Flask

I have a problem with my search. At the moment i am trying to write a small receipe portal and i am trying to search words in tables user,category and recipe. When i write some word, i receive an error message:
Bad request. The browser (or proxy) sent a request that this server
could not understand.
I suppose, that problem stays in my function search, but i dont see it.
#app.route("/search", methods=['GET', 'POST'])
def search():
cursor = g.con.cursor()
cursor.execute('SELECT * FROM nutzer, kategorien, rezepte WHERE Nutzername OR Titel = %s', (request.form["search"],))
result = cursor.fetchall()
cursor.close()
return render_template('Results.html', result = result)
{% extends "layout.html" %}
{% block body %}
<table border="1">
{% for i in result %}
<tr><td>{{ i.1 }}</td></tr>
{% endfor %}
</table>
{% endblock %}
HTML Code of the searchbar
<form action="search">
<input name="search" type="text" placeholder="suchen" value="{{ request.form.search}}" required />
<button>finden</button>
</form>
request.form() implies the POST method, while the default one is GET. You should either check request.method and use request.args() in the case of GET, or add the argument method="POST" to the <form> (and leave POST as the only accepted method in #app.route().
I think your form action has to point to your search endpoint.
<form action="{{ url_for(search) }}">
<input name="search" type="text" placeholder="suchen" value="" required />
<button>finden</button>
</form>

How can I delete a table row by clicking a HTML button beside the row, using python flask

I'm new to coding and have to do this for a school assignment. I do not have very good knowledge of code but I have to create a to-do list webpage that uses a database (SQLite3) to store the to-dos and users. I have the to-do list page successfully showing the created to-dos but I want a button beside the to-dos pulled from the database (to-dos are in table format) that will delete the table row that it is next to. I am not using django or anything like that, so is there a way that this can be done without any python extensions?
Here's my python flask code for my to-do list page
#app.route('/todo', methods=['GET','POST'])
def todo():
error = None
if 'login' in session:
user = session['userid']
db = connect_db()
cursor = db.execute("SELECT * from todolist where userid=?",(user,))
userdetails = cursor.fetchall()
db.commit()
db.close()
if request.method == 'POST':
userid = session['userid']
db = connect_db()
cursor = db.execute("DELETE FROM todolist where userid=?",(userid,))
userdetails = cursor.fetchall()
db.commit()
db.close()
return render_template('todo.html',userdetails=userdetails)
else:
flash('Please login')
return redirect(url_for('.login'))
else:
flash('Please login')
return redirect(url_for('.login'))
And here's my to-do html code for the table section, the rest contains bootstrap links and whatnot:
<h1>Your to-do list!</h1>
<p>{{message}}</p>
<body>
<table border=1 style="width:100%">
{% for row in userdetails %}
<tr id='todorow'>
<td>
<form action="">
<input type="checkbox" name="complete" value="Complete">
</form>
</td>
<td>
{{row[2]}}
</td>
<td>
{{row[3]}}
</td>
<td><form action="/todo" method='POST'>
<input type=submit name="delete" value="Delete"></input>
</form></td>
<td><form action="/todoedit">
<input type="submit" value="Edit item"
onclick="window.location='/todoedit';" /></input>
</form></td>
</tr>
{%endfor%}
If anyone could please explain to me how I can use a html submit button to delete the to-do on the same row as the button, deleting the to-do data from the todolist database table, or what I am doing wrong in my code, and please, if you don't mind, explaining how your code works to do this.

How do I submit "POST" method forms in Django without AJAX?

I'm completely new to Django and I'm also developing a very important project in this framework with some friends. I'm having problems in submitting a "POST" method form in Django.
I'm having the "403 Forbidden" error. It says that my CSRF token isn't configured correctly. I'm pretty sure that I did setup it correctly, though.
My form is about updating an django user account in the database (MySQL). I also don't know if my program logic is right in the view. I didn't even had the opportunity to test it because of this dumb error.
The image and codes below exemplificate my problem.
My form:
<form method="POST" action="/validacao/" name="user" class="current2"> {% csrf_token %}
<table>
<tr>
<td>Nome:</td><td>
<input type='text' name='first_name' maxlength='30' value='{{usuario.first_name}}' class="campo2" />
</td>
<td>Permissão: <font style="color: red;">
{% if usuario.is_staff %} Admin {% else %} Comum {% endif %}</font>
</td>
</tr>
<tr>
<td>Sobrenome:</td>
<td><input type='text' name='last_name' maxlength='30' value='{{usuario.last_name}}' class="campo2" /></td>
</tr>
<tr>
<td>Email:</td>
<td><input type='text' name='email' maxlength='75' value='{{usuario.email}}' class="campo2"/></td>
</tr>
<tr>
<td>Senha:</td><td> <input type='password' name='password' maxlength='120' class="campo2"/></td>
</tr>
<tr>
<td>Confirmar Senha:</td><td><input type='password' name='password2' maxlength='120' class="campo2"/></td>
</tr>
<tr><td></td><td><input type='submit' name='salvar' value='Salvar' class="botao2"/></td></tr>
</table>
</form>
My view:
def validacao_perfil(request):
if request.POST:
try:
request.user.first_name = request.POST['first_name']
request.user.last_name = request.POST['last_name']
request.user.email = request.POST['email']
request.user.password = request.POST['password']
request.user.save()
validacao=1
except:
validacao=0
variaveis_resposta={ 'usuario':request.user,
'MEDIA_URL':settings.MEDIA_URL,
'height_backgroud':'900',
'rodape':'position:relative; top: 148px;',
'ordem':0,
'validacao':validacao,
'context_instance':RequestContext(request),
}
return render_to_response("perfil_usuario.html", variaveis_resposta)
Obs.: the "urls.py" is set correctly and the bizarre thing is that I can see the csrftoken cookie var using Django Debug Toolbar.
just put #csrf_exempt on your def validacao_perfil(request):, to see if this work,and also try to read the doc of django .It's very good!!

Categories