I created an input form to get the data into web and use the inputs for an AP call.
When I want t refresh the page, there is a popup asking if you want to refresh the input. This is very annoying.
The solution was to use HttpResponseRedirect, which workout nicely, but it's throwing away all the inputs. Then the though would be to use variable in the URL with "URL?rds=2".
How do you get the input variables through the HttpResponseRedirect to the same site?
And also how to get variables from URL to input and from input to the URL?
HTML input definition:
<form action="{% url 'page' %}" method="post">
{% csrf_token %}
<input type="number" value="{{request.GET.rds}}" name='rds'>
<input type="submit" value="Search">
</form>
views.py:
Getting the data from the URL input
if 'rds' in request.GET.keys():
radius = request.GET.get('rds')
else:
request.GET.rds = '3'
radius = '3'
Redirecting input if user pressed. Add more variables with "&" if needed.
if request.method == 'POST':
radius = request.POST.get('rds')
redirect_link = request.path_info + '?rds=' + str(radius)
return HttpResponseRedirect(redirect_link)
This will redirect the radius to the same page and will put rds as a get attribute, which will be fatched by the if method.
Afterwards you can use the data with.
context = {'radius': radius}
return render(request=request, template_name='realestate/page.html', context = context)
I hope this is helpfull. Maybe there is also a way better solution then this.
Related
I added a search functionality to my website, such that if you goto www.mywebsite.com/search/texthere , it displays all the songs with title=texthere. I would like to add this functionality to my index page.
In my page, there is an input box where users could type the input and the press submit to submit the input but it goes to some another page.
How can I solve this?
urls.py
url(r'^search/(?P<query>[\w\-]+)/$', views.search, name='search'),
index.html
<form action="/search/">
<input type="text" name="query" value="me"><br>
<input type = "submit">
</form>
What I want is when the user clicks submit button, the text from the input box should be used as the query in urls.py Any help would be appreciated. Thanks!
I think you can get this work by using redirect.
Add a url for /search/ endpoint in your form:
url(r'^search/$', views.search_redirect),
In the views:
def search_redirect(request):
query = request.POST.get('query', '')
return redirect('/search/{}/'.format(query))
the form in your index.html should use method 'POST':
<form action="/search/" method="POST">
<input type="text" name="query" value="me"><br>
<input type = "submit">
</form>
When you submit the query string, search_redirect function get the query string and redirects the request to your /search/<query>/ function.
Hope this will help.
EDIT: Your current search url needs query value also to be passed. But in form action only /search/ is there. During the form submission query value will be passed in request.POST and you wont be able to pass the the query value directly in the url like this /search/sample_query
You need to add one more url:
url(r'^search/$', views.search, name='search'),
And in views:
def search(request, query_via_url=false):
# if form submission is true
if request.post:
query_via_form = request.post.get('query', '')
...
# if query value is passed directly via url
if query_via_url:
....
This is my first django project and I'm struggling to finish it.
I've been working to function that editing post. When user clicks button, it send no(int)for that article, and get information related to no and display on page. User can edit that post in the same form and when user click submit, it redirect to home.html
However, the function I made keep sending me an error message that it takes 2 arguments even though I did not use any function that takes 2 arguments.
Here is views.py
#login_required
def edit_article(request, article_no):
article = Article.objects.filter(pk=article_no)
form = ArticleForm(request.POST, instance=request.article)
if form.is_valid():
form.save()
messages.add_message(request, messages.SUCCESS, _('Article correctly saved.'))
# If the save was successful, redirect to another page
redirect_url = reverse('blog/home.html')
return HttpResponseRedirect(redirect_url)
else:
form = ArticleForm(instance=request.article)
return (request, {'form': form}, context)
This is form in detail.html where send no value to edit_article.html
<form action="{% url 'blog:edit_article' %}" method="post" style="display: inline;">
{% csrf_token %}
<input type="hidden" name="no" value="{{ item.no }}" />
<button type="submit">edit></button>
</form>
The article_no arg does not magically find its way into the function call via the POST submit. You need to provide it to the url tag:
{% url 'blog:edit_article' item.no %}
This assumes, of course, that you have a url pattern with an appropriate named group associated with this view/view name.
If You are talking about this function, it does recieve more than one Arg, it recieves the No you are talking about, and the request object
def edit_article(request, article_no):
...
If your view needs arguments you must give the arguments in the url templatetag, like this :
{% url 'accounts:detail_account' username = username %}
I'm using Pyramid to build a webapp, and I've got two views where one leads to the other:
config.add_route("new", "/workflow/new")
config.add_route("next", "/workflow/{id}/next")
The new view is really very simple and presents only an HTML form as a Jinja2 template for the user to fill in some information:
<form method="post" action="{{ request.route_url('next',id='') }}" >
<input type="text" name="id" value="Identifier" />
...
<input type="submit" name="next" value="Next" />
</form>
The question here regards the action of that form: how can I use the content of the text input field id, perhaps process it a little, and then pass it on in the route request?
Note that in this scenario the form data is passed from the new view to the next view, and that should stay the same.
When the form is posted, the forms fields will be available in the request object, see
http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/webob.html#request
I believe it is also a good idea to post to the same url (<form action="#" method="post">), so that you can validate the form. Then you can process and redirect to the next url when the form is valid, or recreate the form with errors if it isn't.
So your view may end up something like this;
from pyramid.httpexceptions import HTTPFound
from pyramid.url import route_url
def myview(request):
if request.method == 'POST':
# Validate the form data
if <form validates successfully>:
# Do any processing and saving here.
return HTTPFound(location = route_url('next', id=request.params['id'], request=self.request))
else:
request.session.flash("The form isn't valid.")
# Do some stuff here to re-populate your form with the request.params
return { # globals for rendering your form }
There are already many questions/answers addressing this, such as How can I redirect after POST in Pyramid?
Heres the scenario:
I have a email subscriber/un-subscriber app. I am stuck up in the un-subscribing a user part. The user is given a link, which if he/she follows will be able to un-subscribe. The link is typically a view, in the following format:
r^'/unsub_view/(?P<user_id>\w+)/$'
So, when the user follows this links he/she is doing a GET request on the view unsub_view with a parameter user_id. So I have coded up my view as:
def unsub_view(request, user_id):
if request.method == 'GET':
### Do some DB lookup to determine if it is a valid user or not
if user_is_valid:
return direct_to_template(request, '/app/unsub.html', {'user': user})
Now when a valid user is doing the GET, a confirmation dialogue is shown, along with a button. If he/she clicks on the button, I want the template to post the 'user' to the same view, thus the unsub_view also has this piece of code:
if request.method == 'POST':
if user_is_subscribed:
#Unsubscribe the user.
else:
#Show error meessage.
My question is how can I have the button in my template to post to this view ? I have looked around but I got POST-ing to a .php or .asp
Please help.
Note: If there is a better workflow idea, I am also open to that, so please do suggest if there is one.
In the template unsub.html rendering the form with the button, you should pass the url of your view using the reverse method
from django.code.urlresolvers import reverse
def unsub_view(request, viewid):
if request.method == 'POST':
if user_is_subscribed:
#Unsubscribe the user.
submit_url = reverse('unsub_view', viewid)
return direct_to_template(request, '/app/unsub.html', {'user': user, 'submit_url'})
else:
#Show error meessage.
in your template you can then render the form like follows :
...
<form method='post' action='{{ submit_url }}'>
{% csrf_token %}
<input type="hidden" value="{{ user_id }}" name="user_id" />
<input type="submit" value="unsubscribe"/>
</form>
...
Django also has a full framework dedicated to form modeling and rendering. You could take advantage of that to generate the form.
I am using Python 2.7, Django 1.3.1.
I am trying to implement a sign in functionality that can be called from arbitrary page and redirects to the same page without any code duplication. The current way that I have is that I have two views: one for the homepage and one for sign in. I want to be able redirect from sign_in view to the home view with a bound form. The main problem is that when the user enters incorrect data (e.g wrong password) I want to redirect to the same page but want to send the context of the original form. I want to be able to do this without explicitly calling the view function since I want to be able to do it from arbitrary page. How do I do this? My current attempts always return an unbound form in case the data is invalid.
My current code is (simplfied):
urls.py
urlpatterns = patterns('myapp.views',
url(r'^$', 'index', name='home'),
url(r'sign_in/^$', 'signin', name='sign_in')
)
views.py
def index(request, loginForm=LoginForm)
extra_context = dict()
extra_context['login_form'] = loginForm
return direct_to_template(request, 'home.html', extra_context=extra_context)
def signin(request)
if request.method == 'POST':
login_form = LoginForm(request.POST, request.FILES)
if login_form.is_valid():
# login user
redirect_view = reverse('home')
return redirect(redirect_view, kwargs={'loginForm': login_form})
# I also tried:
# return redirect(redirect_view, loginForm=login_form)
# what works is:
# return index(request, loginForm = login_form)
home.html
<form action="{% url sign_in %}" method="post">
{{ form.as_p }}
</form>
Not with reverse. Reverse gets you a path /my-homepage/
The django paradigm for this is to use a hidden "next" variable set to the initial page.
#In your template
<input type="hidden" value="{{ request.path }}" name="next" />
Then, on success return an HttpResponseRedirect to next:
if login_form.is_valid():
# login user
return HttpResponseRedirect(form.cleaned_data['next'])
This is durable, because if there is an issue, you display a form with errors on the /account/login/ page with the hidden next variable and the user still gets back to where they were.