I have an input field that should save the content to a database:
{% for comment in comments %}
<div class="row">
{{ comment.content }}
</div>
{% endfor %}
<div class="row">
<form action="." method="POST">
<textarea class="form-control" name="contents" placeholder="Enter a comment"></textarea>
<input type="submit" class="btn btn-warning" value="save">
</form>
</div>
in flask_app I check whether it is a POST or GET method. If it is POST it should reload the page with a redirect. However, it always returns me to "home".
#app.route('/photography', methods=["GET", "POST"])
def show_photography():
if request.method == "GET":
return render_template('photography.html', comments=Comment.query.all())
elif request.method == "POST":
comment = Comment(content=request.form["contents"])
db.sesson.add(comment)
db.session.commmit()
return 'welcome to flask!'
else:
flash('error message via flash')
return 'welcome to flaks' was just a test, it still redirects me to home after clicking the button. Can anyone help me?
It looks like your 'action="."' is the problem. Set it to url_for('show_photography') in the template.
Related
I'm trying to create a delete button in my template:
<button type="submit" class="btn btn-danger" value={{ instance.name }}> Delete </button>
And I want this button to submit that data in my views.py :
instance_client = compute_v1.InstancesClient()
if request.method == "POST":
instance = request.POST['data']
instance_client.delete(project='xxx', zone='xxx', instance=HERE_I_WANT_THE_DATA)
It's a script that will delete an instance from gcloud.
But I don't know exactly how to deliver the data from the template to views.py.
I'm using Bootstrap 5.
Hope I understand your question.
Template
<form action="{% url 'delete_function' item.id %}" method="POST">
{% csrf_token %}
Cancel
<input class="btn btn-sm btn-danger" type="submit" value="Delete">
</form>
Views
def deleteFunction(request, pk):
item = Model.objects.get(id=pk)
if request.method == "POST":
item.delete()
return redirect('/')
url
path('delete_function/<str:pk>', views.deleteFunction, name='delete_function')
City is a (dropdown in a main form ) with a +(Add) button.
This +(Add) button opens another form in separate window.
On saving a new city in the second form, I want the new city name to be added in the City dropdown without refreshing the main form.
Here is my code.
<form method="POST" enctype="multipart/form-data" id="form">
{% csrf_token %}
<td>City: {{ form.city }}
<button class="btn btn-primary" onclick="addCity(event)">+</button>
</td>
<button type="submit" class="btn btn-primary">Save</button>
</form>
<script>
function addCity(e){
e.preventDefault();
window.open("/city/", "", "width=500,height=500");
}
</script>
city.html
<form method="POST" class="post-form" action="/city/" id="form">
{% csrf_token %}
<div class="container">
<div class="form-group row">
<label class="col-sm-2 col-form-label">City:</label>
<div class="col-sm-4">
{{ form.name }}
</div>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
urls.py
urlpatterns = [
path('city/', views.add_city, name='city_master'),
]
views.py
def add_city(request):
cities = City.objects.all()
if request.method == "POST":
form = CityForm(request.POST)
if form.is_valid():
try:
form.save()
return redirect('/city/')
except:
pass
else:
form = CityForm()
return render(request,'city.html',{'form':form})
I can not comment that is why i am writing here, Sir you need ajax call. Do not use POST request, for all post request the page reloads it self. so try using ajax, you can create a route and function inside controller.
I'm new with Python and Flask, I have a problem while rendering my page. The function is executed every time I refresh the page but I want the function executed when I click on the SUBMIT button.
Here is my main.py:
#app.route('/gp_bagging_one_app', methods=['POST','GET'])
def gp_bagging_one_app():
if request.method == 'POST':
apk_to_bag = request.form['input']
if (os.path.isfile("./Downloads/" + apk_to_bag)):
print("HELLO")
gp_bag.create_json_for_apk(apk_to_bag[:-4])
else:
print("Apk not found in ./Downloads")
return render_template("GooglePlayStore/gp_bagging_one_app.html")
Here is my view :
{% extends 'layout.html' %}
{% block body %}
<h4> Bagging one app. </h4>
<form method="POST">
<div class="form-group">
<h6>Select an APK to bag:</h6> <input type="file" name="input"><br><br>
</div>
<div class=" form-group">
<button type="submit" class="btn btn-light text-primary" >Bag the APK</button>
</div>
</form>
{% endblock %}
I think it's because of my POST method and way to handle the clickevent but I don't know how to fix it. Thank you
I've been working to make an edit form where shows data saved in db and user can edit it like jsp model and view. When user click button it shows add form but all the relevant information in db is already filled up in the form, so user can modifying old data and once they click submit button it redirect to main.
I succeeded to display a form when user click edit button but failed to get data.
this is views.py
#login_required
def update_article(request, article_no):
article = get_object_or_404(Article, no=article_no)
if request.method == "POST":
form = ArticleForm(request.POST, instance=article)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('blog.views.detail', no=article.no)
else:
form = ArticleForm(instance=article)
return render(request, 'blog/update_article.html', {'form': form})
urls.py
url(r'^update_article/(?P<article_no>[0-9]+)/$', views.update_article, name='update_article'),
update_article.html
{% extends 'blog/base.html' %}
{% block body %}
<form class="form-horizontal" role="form" action="create_article.html" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'blog/form_template.html' %}
<button type="submit" class="button-primary">submit</button>
</form>
list
{% endblock %}
detail.html
This is part of the page send users to update_article.html
<form action="{% url 'blog:update_article' item.no %}" method="post" style="display: inline;">
{% csrf_token %}
<input type="hidden" name="no" value="{{ item.no }}" />
<button type="submit" class="button-primary">edit</button>
</form>
form_template.html
{% for field in form %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ field.errors }}</span>
</div>
<label class="control-label col-sm-2" for="title">{{ field.label_tag }</label>
<div class="col-sm-10">{{ field }}</div>
</div>
{% endfor %}
In update_article views
pass article object with form
return render(request, 'blog/update_article.html', {'form': form, 'article': article})
and then form in html page
<form class="form-horizontal" role="form" action="create_article.html" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'blog/form_template.html' %}
<input class="u-full-width" type="text" name="title" value="{{article.title}}"/>
<textarea class="u-full-width" name="content" value="{{article.content}}"></textarea>
<button type="submit" class="button-primary">등록</button>
</form>
I think this would help your problem
also I guess your action link is not valid
I'm making a webpage where I login and add people to an address book. Once I login and click on the "add address" button, I'm redirected back to the login page with the following url:
http://localhost:8000/xcard/login/?next=/xcard/add_address/
If I login again I can get to account page, address book, and then add_address book page without being caught in the login loop. I can logout and login and add addresses without relogin in twice. But the first time I ever login I have to do it twice. Not sure if it's a problem with the login or the add address code.
Views.py
class LoginView(View):
def get(self, request):
''' if user is authenticated '''
if request.user.is_authenticated():
return render(request, 'xcard/account.html')
else:
return render(request, 'xcard/login.html')
def post(self, request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
state = "The email or password is incorrect"
if user is not None:
login(request, user)
return HttpResponseRedirect('/xcard/account/')
else:
return render(request, 'xcard/login.html', {'state':state})
class AddAddressView(View):
def get(self,request):
address_form = AddressForm()
friend_form = FriendForm()
return render(request, 'xcard/add_address.html', {'friend_form':friend_form, 'address_form':address_form})
def post(self,request):
address_form = AddressForm(request.POST)
friend_form = FriendForm(request.POST)
if address_form.is_valid() and friend_form.is_valid():
new_address = address_form.save()
new_friend = friend_form.save(commit=False)
new_friend.address = new_address
new_friend.save()
return HttpResponseRedirect('/xcard/address_book')
else:
return render(request, 'xcard/add_address.html', {'state' : "Failed", 'friend_form':friend_form, 'address_form':address_form})
Templates:
address_book.html
{% include "xcard/header.html" %}
{% block main %}
<div class="container">
<h3 class="text-info"><u>Your Account</u></h3>
Add
Import
</div>
{% endblock %}
Templates:
login.html
{% extends "xcard/base.html" %}
{% block main %}
<div class="container">
<div class="row space">
<p class="text-center lead text-warning">
Login page</p>
<p class="text-center text-info">Trusted worldwide!</p>
</div>
<div class="row">
<div class="span offset4">
<form class="well" action="/xcard/login/" method="post">
{% csrf_token %}
<p class="lead">Sign In</p>
<fieldset class="login_page">
<p class="text-error"><strong>{{ state }}</strong></p>
<label class="control-label" for ="inputIcon">Email</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-user"></i></span>
<input type="text" class="span3" id="ernainputIcon" required name="username" placeholder="Username...."/><br/><br/>
</div>
</div>
<label>Password</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-lock"></i></span>
<input type="password" class="span3" id="inputIcon" required name="password" placeholder="Password...."/><br/><br/><br />
</div>
</div>
<button class="btn btn-primary">Sign In</button>
Not a user?
Sign up
</fieldset>
</form>
</div>
</div>
</div>
{% endblock %}
I just found this in my urls.py
url(r'^add_address/$', login_required(AddAddressView.as_view(), login_url='/xcard/login/')),
Maybe this is causing the problem? But why doesn't it register that I'm already logged in?
first do the correction in AddAddressView function. update line
return render(request, 'xcard/add_address.html', {'friend_form':friend_form, 'address_form':address_form})
it will work
This was my solution - logout before you try to authenticate.
This issue happened to me when users were logging in and logging back in with a different username.
import django.contrib.auth as djangoAuth
djangoAuth.logout(request) # logout
user = djangoAuth.authenticate(username=username, password=password) # login