Django, GET parameters keeped into the URL after a POST call - python

I'm new to Django!
I'm doing a simple registration form, when it is submitted, it returns a label to the previous page, that is the main page:
The form is submitted like this:
<form method="post"">
And its mapped in urls.py:
url(r'^userfilt/insertForm/$', views.insertForm, name='insertForm')
All the urls.py file:
app_name = 'SSO_Management_POC'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^user/$', views.user, name='user'),
url(r'^userfilt/$', views.userfilt, name='userfilt'),
url(r'^userfilt/insertForm/$', views.insertForm, name='insertForm'),
#url(r'^updateForm/$', views.updateForm, name='updateForm'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
So the related "def" its called:
def insertForm(request):
if request.method == 'POST':
#some stuff here
#sending the get parameter to the main page:
return redirect('/SSO_Management_POC/userfilt/?label=User Registered!')
now when i redirect to the main page i'll see something like:
Now i want just continue working so, I'll put a filter into the input and i perform a search, below the code:
if request.method == 'POST':
form = UserForm(data=request.POST)
val = request.POST.get('my_textarea')
return render(request, 'SSO_Management_POC/userfilt.html', {'top_user': TopUser.objects.filter(user_name__regex=val)})
As you can see is a POST call, but it comes the issue, GET parameter is still there so this cause
And obviously i don't want anymore the label there, it should disappear after another call...
And the url still looks like this:
http://127.0.0.1:8000/SSO_Management_POC/userfilt/?label=User%20Registered!
Now, i know i can resolve this with workaround front end side, but i would like to know:
Is there something that is not good as flow of operations?
How can i resolve this? Where am i wrong..?
I tried to look for something to clean the get parameter in the url, or to reset it, beacuse i thought it was the easier way, but the only things i found costs a lot of code, have you other idea about to clean the url?
is there any other Django method that helps you resolve this, or maybe simply avoid this problem?

The problem is that you don't have an action="" in your form tag which simply means that you want to post to the existing URL, including any querystring (ie. existing GET parameters).
Just add action="" to the form tag, such as:
<form method="POST" action="{% url 'insertForm' %}">

Related

django redirect view with parameter

In my App I have the file urls.py that contains these rows:
...
path('home/', views.home, name='home'),
path('page/', views.page, name='page'),
....
and in my view.py file i have two view like this:
def home(request, value=0):
print("value=", value)
return render(request, 'template.html', context)
def page(request):
if bad:
return redirect(reverse('home'), value=1)
Is it possible to have the view function with a parameter (like the value in this case) and then use redirection from the page view passing some value based on the same condition like value=1, in this case, using the format described in the urls.py?
The code above always prints value=0 no matter what.
The only way I can think to do this is to use global variables which I would really like to avoid...
Yes, but you need to add the parameter to the URL:
path('home/', views.home, name='home1'),
path('home/<int:value>/', views.home, name='home2'),
Then you need to pass the page in the redirect itself, together with the name of the view, you should not use reverse(..) here:
def page(request):
if bad:
return redirect('home2', value=1)

Codes in one of my views are not processed when I access to that view

My intention is to change from interface view -> switch view to process some data and send those data and change to -> test view to display the result. However, nothing in switch view seems to be processed and switch view doesn't change to test view after I hit 'submit' on userInterface.html. My guess is that the problem lies on the HttpResponseRedirect() function or anything related to url paths. Everything worked find with my other project that I worked on my computer. I'm not sure what I need to change to use Django on RaspberryPi.
At first, I found out I didn't import libraries needed for those function. After I imported them, the code was still not working.
I commented out other codes in switch view that do nothing with changing views and just focus on changing view in my switch view.
view.py
def user_interface(request):
return render(request,'zuumcoin/userInterface.html',
{})
def switch(request):
return HttpResponseRedirect(reverse('zuumcoin:test'))
def test(request):
return render(request,'zuumcoin/test.html',{})
userInterface.html
....
<form action="{% url 'zuumcoin:swicht' %} method = "POST">
{% csrf_token %}
...
...
</form>
urls.py
app_name='zuumcoin'
urlpatterns = [
url(r'', views.user_interface, name='interface'),
url(r'switch/', views.switch, name='switch'),
url(r'test/', views.test, name='test')
]
I expect HttpResponseRedirect to direct me to test view instead of being stuck in switch view. If it can do that, I think I can find a way for other part of my code in my switch view to run.
You didn't terminate your regexes. So the first pattern matches every path.
You should do:
url(r'^$', views.user_interface...)
It seems you have typo in your userInterface.html template. change this:
{% url 'zuumcoin:swicht' %}
to this one:
{% url 'zuumcoin:switch' %}

why do my django urls render the wrong template?

I'm suprised that I cannot access my product detail page through the url and I don't understand why since I've already done this basic thing plenty of times...
I have a page where all my products are displayed, when the user click on a product he is redirected to the product detail, that's it.
Somehow when I click a link linked to the product detail or type de correct path to the url it loads the same page where all the product are shown but it doesn't even call the product detail view, why so ?
Here are the views :
def rcdex(request):
list = Liste.objects.all()
return render(request, 'rcdex.html', {'list':list,})
def rc_detail(request, id):
list = Liste.objects.get(id=id)
return render(request, 'rc_detail.html', {'list':list,})
Here are the urls :
url(r'^', views.rcdex, name="rcdex"),
url(r'^rc/(?P<id>\d+)/$', views.rc_detail, name='rc_detail'),
Here is how I call the rc_detail view on the template :
<th>{{ l.entreprise }}</th>
I don't get why it doesn't show me the correct template (rc_detail.html) but instead reload rcdex.html ?
You haven't terminated your rcdex urlpattern, so it matches everything. You should use a $:
url(r'^$', views.rcdex, name="rcdex"),
you can also do like this..
url(r'^rc/(?P<id>\d+)/$', views.rc_detail, name='rc_detail'),
url(r'^', views.rcdex, name="rcdex"),

Django, rendering a view from another view (call a specific URL)

I have a little form:
<form action="#" method="post">
{% csrf_token %}
<label>Company Number:</label>
<input type="text" name="company" placeholder=""/><br>
<input type="submit" id="register value=" OK" />
</form>
Which is mapped like this:
url(r'^userfilt/insertForm/$', views.insertForm, name='insertForm'),
Now after submitting this form, I want to get back to the main view:
url(r'^userfilt/$', views.userfilt, name='userfilt')
URL mapping file:
app_name = 'SSO_Management_POC'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^user/$', views.user, name='user'),
url(r'^userfilt/$', views.userfilt, name='userfilt'),
url(r'^userfilt/insertForm/$', views.insertForm, name='insertForm'),
#url(r'^updateForm/$', views.updateForm, name='updateForm'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
The main view is like this (but I don't think this code is related to the problem..):
def userfilt(request):
if request.GET.get('create'):
return HttpResponseRedirect('insertForm')
if request.GET.get('update'):
print request.GET.get('pk')
return render(request, 'SSO_Management_POC/updateForm.html')
if request.method == 'POST':
form = UserForm(request.POST)
val = request.POST.get('my_textarea')
return render(request, 'SSO_Management_POC/userfilt.html',
{'top_user': TopUser.objects.filter(user_name__regex=val)})
else:
print '4'
return render(request, 'SSO_Management_POC/userfilt.html')
Now the call that is killing me happens when N submit the form, N just wanna get back to the main page calling it with a POST, like a always did!
return render(request, "SSO_Management_POC/userfilt.html")
I do it like this, but the problem is that the URL has not been reset.. and results in this,
http://127.0.0.1:8000/SSO_Management_POC/userfilt/insertForm/#
Resulting in every operation I make on that page not work because it's not mapped anymore
I mean, it should be:
http://127.0.0.1:8000/SSO_Management_POC/userfilt/
but instead it is
http://127.0.0.1:8000/SSO_Management_POC/userfilt/insertForm/#)
To try to explain my issue better..
I go to the main page (http://127.0.0.1:8000/SSO_Management_POC/userfilt/)
"GET /SSO_Management_POC/userfilt/ HTTP/1.1" 200 2648
Then I click on the create User to call the form, it brings me to: (http://127.0.0.1:8000/SSO_Management_POC/userfilt/insertForm/)
"GET /SSO_Management_POC/userfilt/insertForm/ HTTP/1.1" 200 1549
Than I submit the form and I would like to get back to the main page, and here comes the thing I don't understand:
it bring me here
http://127.0.0.1:8000/SSO_Management_POC/userfilt/insertForm/#
But I want to go here
http://127.0.0.1:8000/SSO_Management_POC/userfilt
This is again the code:
return render(request, "SSO_Management_POC/userfilt.html")
This is the call made:
"POST /SSO_Management_POC/userfilt/insertForm/ HTTP/1.1" 200 2648
I tried with render, with HttpResponseRedirect and so on... But always it happened the URL I'm calling with the previous one, I want it to be reset, I want it to be ../ !!!
The only thing that work for me is:
return redirect("../")
but
this is dirty
this does not permit to make a POST call!
Thanks to Daniel, I fixed it like this:
return redirect('/SSO_Management_POC/userfilt')
But it still give me same issue with:
return render(request,'/SSO_Management_POC/userfilt')
Getting me to http://127.0.0.1:8000/SSO_Management_POC/userfilt/insertForm/
You should always redirect, not render, after a successful post. Doing return redirect(url) is the correct thing to do, and it's not clear why you're not happy with this.
Note that redirect can accept the name of a URL pattern, so you could do return redirect('userfilt') which will take you to the correct place.
Does the following code solve your problem?
In your template:
<form action="{% url 'userfilt' %}" method="post">

How to redirect with variables in django?

How to redirect with variables in django?
Please guide me, thank you.
urls.py:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^computer/$', views.computer, name='computer'),
url(r'^result/$', views.result, name='result'),
)
This is my original views.py :
def computer(request):
result = Computer.objects.order_by('?')[:1]
return render(request, 'many/result.html',{'result':result})
And I found I problem, render will not redirect to moneymany/result.html on the url,
so if the user refresh, it will get another result on the same page.
So I have to use redirect to many/result.html .
What's the usually way to redirect in django and I have to pass variable result?
I try this,but not work :
def result(request):
return render(request, 'many/result.html')
def computer(request):
result = Computer.objects.order_by('?')[:1]
url = reverse(('many:result'), kwargs={ 'result': result })
return HttpResponseRedirect(url)
you need
url(r'^result/(?P<result>[^\/]*)/$', views.result, name='result'),
and
return redirect(reverse('many:result', kwargs={ 'result': result }))
or (without changing url)
return redirect('/result/?p=%s' % result )
if you want to maintain POST data while redirecting, then it means your design isnot good. quoting Lukasz:
If you faced such problem there's slight chance that you had
over-complicated your design. This is a restriction of HTTP that POST
data cannot go with redirects.
How about using redirect.
from django.shortcuts import redirect
def computer(request):
result = Computer.objects.order_by('?')[:1]
return redirect('view-name-you-want', { 'result'=result })
this worked with i just needed to pass url parameters as arguments
return redirect('pagename' ,param1 , param2)
my url looks like :
path('page', views.somefunction, name="pagename")
Note: in my case somefunction accept only POST parameters
To redirect from a view to another view with data, you can use session with request.session['key'] and in this case, you don't need to modify path() in "myapp/urls.py" as shown below. Then, give the conbination of the app name "myapp", colon ":" and the view name "dest_view" which is set in path() in "myapp/urls.py" as shown below:
# "myapp/views.py"
from django.shortcuts import redirect
def redirect_view(request):
# Here
request.session['person'] = {'name': 'John', 'age': 27}
# Here
return redirect("myapp:dest_view")
# "myapp/urls.py"
from django.urls import path
from . import views
app_name = "myapp"
urlpatterns = [ # This is view name
path('dest/', views.destination_view, name="dest_view")
]
Then, this is how you get the data of "post" method:
# "myapp/index.html"
{{ request.session.person.name }} {# John #}
{{ request.session.person.age }} {# 27 #}

Categories