directing based on GET request parameters in django - django

I'm in c.html (http://localhost:8000/practice/c) and I click a link that changes my url to
http://localhost:8000/practice/c/?q=1
this is urls.py
url(r'^$', prac_c),
url(r'^q=\d',fetch_c),
and this is views.py
def prac_c(request):
return render_to_response('subject/c.html', {"problem_list":problem_list})
def fetch_c(request):
qno = request.GET.get('q')
if qno:
return render_to_response('subject/que.html', {'qno':qno}, context_instance=RequestContext(request))
but I'm not getting directed to que.html. Something wrong with the urls.py?

What the URLconf searches against
The URLconf searches against the requested URL, as a normal Python string. This does not include GET or POST parameters, or the domain name.
source

Related

Redirecting to root URL from another app's view

I am trying to redirect to root URL when an app's URL is accessed without the user being logged-in.
I've tried to do so in 2 ways:
Using a decorator
#login_required(login_url = '')
def index(request):
return render(request, 'professors/index.html')
Which returned a 404 error saying the current path is accounts/login
Passing the views of the root page to redirect
def index(request):
if request.user.is_authenticated:
return render(request, 'professors/index.html')
else:
return redirect('login.views.index')
Which returned a 404 error saying the current path is professors/login.views.index
The root URL is localhost:8000/ and I am trying to redirect to it after accessing localhost:8000/professors/ when the user is not logged-in.
This problem is similar to what I've found here: Django redirect to root from a view
However, applying the solution did not work for me. It looks like when redirecting to root from an app's view, the root it is redirecting to is the app's root, and not the website's, and this is true for any URL redirected after accessing an app's URL. E.g., if the root URL is localhost:8000 and the app's URL is localhost:8000/professors/, then trying to access any other URL from the latter, will mean that localhost:8000/professors/ is the starting point and what I write in the login_url or redirect(redirect_URL) is added to that, which means that I can no longer access localhost:8000
Final note:
When I tried return redirect ('') in else it returned
NoReverseMatch at /professors/
Reverse for '' not found. '' is not a valid view function or pattern name.
Which shows that the starting point is again from localhost:800/professors/
Set your login_url parameter in login_required decorator,
#login_required(login_url='/')
def index(request):
return render(request, 'professors/index.html')
You can also set the LOGIN_URL in settings
#settings.py
LOGIN_URL='/'

redirect vs reverse django

I have experienced using reverse within get_absolute_url method in the model, but I wish I have an idea about the difference between reverse and redirect, I have tried to search on google about it but there is almost nothing
I don't know what should I write also to convince stack overflow that I don't have any other description
Reverse and redirect have a different meaning. Here is a simple explanation:
reverse in Django is used to find the URL of a given resource. Let's say that you have a blog website and from the main page, you want to provide links to your blog posts. You can of course just hard-code /posts/123/ and just change the ID of your blog post in URL, but that makes it hard to change your URL for the post in the future. That's why Django comes with reverse function. All you need to do is to pass the name of your URL path (defined in your urlpatterns) and Django will find for you the correct URL. It is called reverse because it is a reverse process of determining which view should be called for a given URL (which process is called resolving).
Redirects are not specific to Django or any other web frameworks. Redirect means that for a given URL (or action), the user should be instructed to visit a specific URL. This can be done by sending a special redirect request and from there the browser will handle it for the user, so no user action is required in that process. You can use reverse in redirect process to determine the URL that the user should be redirected to.
GwynBleidD has given you the answer, but there is a reason why you might be getting confused. The Django redirect shortcut accepts arguments in several different forms. One of them is a URLpattern mane, with arguments, that is then passed to reverse to generate the actual URL to redirect to. But that's just a shortcut, to enable a common pattern.
here's an example
app/views
#imports
def indexView(request):
....
return render(request, 'index.html', context)
def loginView(request):
....
return redirect('index')
def articleDetailView(request, id):
....
return redirect(reverse('article-comments', kwargs={'id':id})
def articleCommentsView(request, id):
....
return render(request, 'comment_list.html', context)
proj/urls
#imports
urlpatterns = [
....,
path('', include(app.urls))
]
app/urls
#imports
urlpatterns = [
....,
path('index/', index, name='index'),
path('login/', loginView, name='login'),
path('article/<int:id>/detail', articleDetailView, name='article-detail'),
path('article/<int:id>/comments/',articleCommentsView, name='article-comments')
....,
]
For loginView redirect will return url as-is i.e. 'index' which will be appended to base(project) urlpatterns. Here redirect(reverse('index')) will also work since kwargs is None by default for reverse function and 'index' view doesn't require any kwarg. It returns '/index/' which is passed to redirect(which again will be appended to base urls).
One thing to note is that reverse is used to make complete url - needed for redirect - that is shown in 'articleDetailview'.
The most basic difference between the two is :
Redirect Method will redirect you to a specific route in General.
Reverse Method will return the complete URL to that route as a String.

URL patterns for GET

I want to define url pattern for the below url and read these parameters in views
http://example.com/user/account?id=USR1045&status=1
I tried
url(r'^user/account/(?P<id>\w+)/(?P<status>\d+)/$', useraccount),
In Views
request.GET ['id']
request.GET ['status']
but it is not working, please correct me.
django url patterns do not capture the query string:
The URLconf searches against the requested URL, as a normal Python
string. This does not include GET or POST parameters, or the domain
name.
For example, in a request to http://www.example.com/myapp/, the
URLconf will look for myapp/.
In a request to http://www.example.com/myapp/?page=3, the URLconf will
look for myapp/.
The URLconf doesn’t look at the request method. In other words, all
request methods – POST, GET, HEAD, etc. – will be routed to the same
function for the same URL.
So, with that in mind, your url pattern should be:
url(r'^user/account/$', useraccount),
In your useraccount method:
def useraccount(request):
user_id = request.GET.get('id')
status = request.GET.get('status')
if user_id and status:
# do stuff
else:
# user id or status were not in the querystring
# do other stuff
Querystring params and django urls pattern are not the same thing.
so, using django urls pattern:
your url:
http://example.com/user/account/USR1045/1
urls.py
url(r'^user/account/(?P<id>\w+)/(?P<status>\d+)/$', views.useraccount)
views.py
def useraccount(request, id, status):

Redirect 404 error to other site

I want to redirect all pages with 404 error to another site example.com. I tried to write something like this:
handler404 = 'index.views.custom404'
def custom404(request):
return HttpResponseRedirect(reverse('index'))
But it doesn't work.
What should I write in urls.py and views.py for this operation?
Just write the fully qualified url:
handler404 = 'index.views.custom404'
def custom404(request):
return HttpResponseRedirect('http://othersite.com/custom404.html')

django redirect not working as expected

I have a view that either displays a form or a 'thank you' page (if the form submission was successful). I am using redirect with a url that I have tested working to display the thank-you page.
def form8(request):
form = UserInfoForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('/sjwork/thanks')
return render(request, 'form8.html', {'form': form})
However, when the form is successfully submitted django give the error:
ViewDoesNotExist at /sjwork/form8
Could not import views. Error was: No module named views
As said, I can go to localhost:8000/sjwork/thanks directly and it displays the thank-you page. According to documentation I can use a hard-coded url like this. I tried alternatives, too (giving the view, using a full url like http://google.com) - nothing works. I must be missing something basic here. Would appreciate if someone can explain what is going on here. Thanks.
The app 'sjwork' has the following in its urls.py:
url(r'^$', 'views.home', name='home'),
url(r'^thanks$', 'sjwork.views.thanks'),
url(r'^form8$', 'sjwork.views.form8', name='form8'),
whereas the project urls.py contains:
url(r'^sjwork/', include('formtest.sjwork.urls')),
Looks like error is related to this pattern.
url(r'^$', 'views.home', name='home'),
Try removing it and try again.
Also, Could you include your import statements in your question.