redirect(url_for) not working with me..i should enter title and content then the shown page for these info should shown up to me but its not , no errors its just not coming.. i dont know why ?
this is my code
from flask import Flask, render_template ,request, redirect , url_for
app=Flask(__name__)
blog={
'name':'My Nice Blog',
'posts': {}
}
#app.route('/')
def home():
return render_template('home.html')
#app.route('/post/<int:post_id>')
def post(post_id):
post=blog['posts'].get(post_id) #Nnon if not found
if not post:
return render_template('404.J2',message=f'A post no# {post_id} Not Exist')
return render_template('post.J2',post=post)
#app.route('/post/create',methods=['GET','Post'])
def create():
if request.method=='Post':
title=request.form.get("Title")
Content=request.form.get("content")
post_id=len(blog['posts'])
blog['posts'][post_id]={'post_id':post_id,'Title':title,'content':Content}
**return redirect(url_for('post',post_id=post_id))**
return render_template('create.html')
every thing is work just this line:
return redirect(url_for('post',post_id=post_id))
Try (note that POST is in all caps) and make sure you do are doing a POST to the route's endpoint
methods=['GET','POST']
and
if request.method=='POST':
Related
I have a button on my homepage that redirects to my controller:
redirect_to edit_user_path(user, track: "homepage")
I can see that the redirect works correctly because if I throw a pry inside the controller it'll freeze.
The edit action inside my users_controller renders a react page. I am using the react rails gem.
When I visit the users/:id/edit page it works properly but for whatever reason when I go thru the redirect it doesn't load properly.
# edit.html.erb
`<%= react_component("App", #data) %>`
# users_controller#edit
# GET users/:id/edit
def edit
#tracking = params[:track] if params[:track].present?
#data = {name: "steve", age: 33, track: #tracking}
end
It almost looks like all of the props are missing because the react developer tools says: "waiting for roots to load..."
I think you got the redirect code wrong.
Can you try this in the redirection controller?
redirect_to edit_user_path(user, track: "homepage")
Use redirect_to instead of return
Turns out it was a timing issue. The link I was using had turbolinks enabled. When I changed turbolinks to be false everything worked as expected.
At my work, we are in the middle of breaking up our Rails monolith. We are currently serving our react app through the asset pipeline. I am implementing JWT for authentication. I am trying to pass the token in the url without using sessions/cookies as part of an admin impersonating a user.
class ReactPagesController < ApplicationController
def index
render :index #this will open up the react app
end
end
Is it possible to render a view and pass along parameters in the url?
I want this to open up the index page with url parameter (i.e. localhost:4000/users?jwt=abc.def.ghi
I've tried doing something like render :index, jwt: abc.def.ghi, but that doesn't work. Is the only way to do this via redirect_to?
You are actually defining a redirection:
You want to go to localhost:4000/users
The page display the index page, and URL becomes localhost:4000/users?id=123
For the normal webpage, changing URL will make the browser redirect. As you can see the result when executing this JS in the Chrome Console:
window.location.href = "google.com"
the browser will redirect you to google.com
So, for a Rails's application, you should do a redirection by redirect_to to achieve the current needs.
However, if you really want to change the URL without redirection, you can do it via Javascript. Just use window.history to change your URL
Your controller:
# app/controllers/users_controller.rb
def index
#desired_id = 123
end
and your view
<%-# app/views/users/index.html.erb %>
<!-- rest of HTML -->
<script>
window.history.pushState("", "", "?id=<%= j #desired_id %>");
</script>
you can use redirect_to
redirect_to users_url, id: 5
will get you to /users?id=5
I don't think so, render is for rending the view and has nothing to do with the setting the url.
ruby docs
I have a Page model in my rails 4 app. It has an :permalink attribute that is used so that when someone goes to "mysite.com/pages/page-name", the controller finds the Page with "page-name" as the permalink and then shows the view.
pages_controller.rb:
def show
#page = Page.find_by_permalink!(params[:id])
end
After a few months of the site being up, I want to change the permalink of a certain page, however I don't want to lose all the incoming links. I'm thinking I would do this.
First I'd add_colum :new_permalink to the Page model. Then if this :new_permalink attribute was anything but nil or blank, it would pull up a new page in the controller like this:
def show
#page = Page.find_by_permalink!(params[:id])
if !#page.new_permalink.blank?
#page = Page.find_by_permalink!(#page.new_permalink)
end
end
This works, but the url in the browser still shows the old URL. I suppose this might not be so bad, but I think I'd like it to actually forward to the new page. Perhaps, instead of "new_permalink" it should be a new url and actually do a redirect? What would be your best solution for this? And could I make it a 301 redirect?
Yes, you should use a 301 redirect so that both the user and search engines would send the browser to the correct location.
def show
#page = Page.find_by_permalink!(params[:id])
if #page.new_permalink.present?
redirect_to page_path(#page.new_permalink), status: :moved_permanently
return
end
end
I have a method where i am redirecting it to another action. Here's the code:
def redirectPage (String appNum) {
redirect(action: "showMan")
}
Now, once this the navigates to another page the URL will appear as http://myserver/myapp/showMan
I want this URL to appear as http://myserver/myapp/showMan?SomeIdentifier
I actually want to append this ID to the end of the page ?SomeIdentifier . How can i do it?
Use the param attribute of redirect according to the official documentation.
redirect(action: 'showMan', params: [param1: 'value1', param2: 'value2'])
This will result in
http://<host>/<your-app>/<controller>/showMan?param1=value1¶m2=value2
So I almost have a pingback sender ready for my rails app (people post links to content and donate to them). Almost.
I've borrowed heavily from the code here:
http://theadmin.org/articles/2007/12/04/mephisto-trackback-library/
I modified the slightly for my purposes:
require 'net/http'
require 'uri'
class Trackback
#data = { }
def initialize(link_id)
link = Link.find(link_id)
site = Link.website
if link.nil?
raise "Could not find link"
end
if link.created_at.nil?
raise "link not published"
end
#data = {
:title => link.name,
:excerpt => link.description,
:url => "http:://www.MyApp.org/links/#{link.to_param}/donations/new",
:blog_name => "My App"
}
end
def send(trackback_url)
u = URI.parse trackback_url
res = Net::HTTP.start(u.host, u.port) do |http|
http.post(u.request_uri, url_encode(#data), { 'Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8' })
end
RAILS_DEFAULT_LOGGER.info "TRACKBACK: #{trackback_url} returned a response of #{res.code} (#{res.body})"
return res
end
private
def url_encode(data)
return data.map {|k,v| "#{k}=#{v}"}.join('&')
end
end
Looks like I'm sending links successfully to my wordpress blog but when I look at the link displayed on the trackback I get this: http://www.theurl.com/that/my/browser/iscurrentlypointing/at/http:://www.MyApp.org/links/#{link.to_param}/donations/new"
All I want is the second half of this long string. Don't know why the current location on my browser is sneaking in there.
I've tried this on two of my blogs so it doesn't seem to be problem related to my wordpress installation.
UPDATE: Okay this is a little odd: I checked the page source and it shows the correct link. When I click on it, however, I get directed to the weird link I mentioned above. Is this a Wordpress Issue?
Whoops! Looks like it was just a syntax error. A sneaky double colon
This line
url => "http:://www.MyApp.org/links/#{link.to_param}/donations/new"
Should of course be like this
url => "http://www.MyApp.org/links/#{link.to_param}/donations/new",