the problem that I have is this one:
I created a new re_path in my urls.py file, but when I make a request at that url the wrong function is called.
# myapp/urls.py
from django.urls import path, re_path
from . import views as multiplayer_lite_views
urlpatterns = [
# other paths
re_path(r'vote/(?P<match_id>\w{16})', multiplayer_lite_views.vote, name='multiplayer_lite_vote'),
re_path(r'nightvote/(?P<match_id>\w{16})', multiplayer_lite_views.night_vote, name='multiplayer_lite_night_vote'),
path('new-match/', multiplayer_lite_views.new_match, name='multiplayer_lite_new_match'),
path('', multiplayer_lite_views.home, name='multiplayer_lite_home'),
]
what I did was simply duplicate the line re_path(r'vote/... and renamed it to re_path(r'nightvote/... but changing also all the other info, like multiplayer_lite_views.vote to multiplayer_lite_views.night_vote.
The problem is that when I go to this url nightvote/ the function vote is called.
# myapp/views.py
def vote(request, match_id):
print('vote function')
# do other stuff
return return JsonResponse(...)
def night_vote(request, match_id):
print('nightvote function')
# do other stuff
return return JsonResponse(...)
In the server side what I see is that:
...
vote function
[18/Mar/2020 10:19:16] "POST /nightvote/gfvkpvhlwlqzosae HTTP/1.1" 200 16
...
PS I have already tried to close Django and reopen, the same with vs code.
change your url re_path like as below:
re_path(r'^vote/(?P<match_id>\w{16})$', multiplayer_lite_views.vote, name='multiplayer_lite_vote'),
re_path(r'^nightvote/(?P<match_id>\w{16})$', multiplayer_lite_views.night_vote, name='multiplayer_lite_night_vote'),
I had this problem and this was because ^.
Related
My views.py runs code fine when I press a button on my HTML page, views.py:
def start_or_end_fast(request):
#If starting fast, add a row to the db:
#fast_finished = False
#start_date_time using = current time
#end_date_time using = current time
if request.method == 'POST' and 'start_fast' in request.POST:
add_fast = logTimes(fast_finished=False,start_date_time=datetime.now(),end_date_time=datetime.now())
add_fast.save()
print(add_fast.start_date_time,add_fast.end_date_time)
print('Fast started')
#return render(request,'startandstoptimes/index.html')
return HttpResponseRedirect('startandstoptimes/index.html')
You can see my commented return line, this works but when I refresh the page I can resubmit the data, I want to avoid this. In researching my solution, I saw this could be solved using HttpResponseRedirect but I am not able to get this to work with my code, the more I change the more broken things become.
My application urls.py:
from turtle import home
from django.urls import path,include
from . import views
urlpatterns = [
path('', views.start_or_end_fast,name="start_or_end_fast")
]
My project urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('startandstoptimes.urls'))
]
I believe it is related to the URLs, due to the 404 message I see:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/startandstoptimes/index.html
Using the URLconf defined in myfastingsite.urls, Django tried these URL patterns, in this order:
admin/
[name='start_or_end_fast']
The current path, startandstoptimes/index.html, didn’t match any of these.
Am I going down the right route trying to use HttpResponseRedirect or is there a better solution?
class HttpResponseRedirect¶
The first argument to the constructor is required – the path to redirect to. This can be a fully qualified URL (e.g.
'https://www.yahoo.com/search/'), an absolute path with no domain
(e.g. '/search/'), or even a relative path (e.g. 'search/'). In that
last case, the client browser will reconstruct the full URL itself
according to the current path. See HttpResponse for other optional
constructor arguments. Note that this returns an HTTP status code 302.
See this link for more details: docs
As what the documentation says, HttpResponseRedirect accepts URL and not the path of your template. You should be doing it something like this:
from django.urls import reverse
return HttpResponseRedirect(reverse('start_or_end_fast'))
I was trying to get the variable and value of a url in urlpatterns in Django. I mean, I want to put in the address of the browser type: https://place.com/url=https://www.google.es/... to be able to make a translator. And be able to pick up the variable and value in the function that receives. At the moment I'm trying to get it with re_path like this:
from django.urls import path, re_path
from . import views
urlpatterns = [
path('', views.index),
re_path('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_#.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', views.index_traductor),
]
The regex match picks it up, but I don't know how to send it as a value in a variable to receive here:
from django.http import HttpResponse
def index(request):
return HttpResponse("flag")
def index_traductor(request, url=''):
return HttpResponse("%s" % url)
I get a blank page. Any ideas?
Uh, no need for regex - why not just use get parameters?
URL:
https://place.com/?param1=val1
views.py
def my_view_function(reuqest):
# unpack get parameters:
val1 = request.GET.get('param1')
# do something ...
#code in urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name= 'index'),
path('about/', views.about, name ='about'),
]
#code in views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello")
def about(request):
return HttpResponse("about harry")
Body
I am doing this while watching a tutorial, and the same thing is working for him. Moreover, if mistakenly I write the wrong code and run, cmd shows the errors and on reloading the browser the server doesn't work more. Then I need to restart CMD and again run manage.py. Please tell me the reason and also the solution, Thanks.
What errors do you get?
Besides there're 2 urls' files: url routes for pages are inside urls.py in the same folder where views.py are. In another urls.py (the one which is in the same folder with manage.py) you may need to write following, assuming that 'polls' is the name of you application:
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
]
According to Django docs: include() function allows referencing other URLconfs. Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.
You should always use include() when you include other URL patterns. admin.site.urls is the only exception to this.
If you still get the error: check that you’re going to http://localhost:8000/polls/ and not http://localhost:8000/
Here is content of MyProj/urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('general.urls')), # Main app
]
handler403 = 'general.views.handler403'
handler404 = 'general.views.handler403'
As you can see, both handlers point to the same view, and first one, which I need most, doesn't work! For example, data of other's user at /obj/12 shows default browser 403 page:
[22/Jan/2019 08:39:14] "GET /obj/12 HTTP/1.1" 403 0
But the second one works well and shows correct page (when try to access some not existing data at /obj/768). Why and how can I solve it?
The debug mode is off. My Django version is 2.0.6
Update.
Content of the handler403.py file:
from django.shortcuts import render_to_response
def handler403(request, *args, **argv):
print('Handler 403 was called!')
u = request.user
params = {
'user': u,
}
response = render_to_response('403.html', params)
response.status_code = 403
return response
The string Handler 403 was called! is never printed when I try to get this page.
My guess is that your views returns a django.http.HttpResponseForbidden instead of raising a django.core.exceptions.PermissionDenied exception.
Only the PermissionDenied exception gets handled by handler403, a HttpResponseForbidden is returned as is.
If that's really your handler403 file (aka. handler403.py), you'll probably want
handler403 = 'general.views.handler403.handler403'
(so a dotted path to the actual callable).
handler403 should point to a view
Try something like this:
from general.views.handler403 import handler403
handler403 = handler403
I am new to Django. I have to write a moke. My server will look at a specific address.
Like this:
portal/client_api.ashx?client=SAPRA&key=1234234&func=status&code=99999
I wrote:
urls.py
from django.conf.urls import patterns, url
from rt_moke import views
urlpatterns = patterns('',
url(r'code=(?P<code_id>\w+)/', views.Sapata, name='sapata'),
)
and views.py
from django.http import HttpResponse
status = {u"99999": u'{"code": "99999","status": "undelivered"}',\
u"88888": u'{"code": "88888","status": "delivered"}',\
}
def Sapata(request, code_id):
return HttpResponse(status[code_id])
When I request for portal/client_api.ashx?client=SAPRA&key=1234234&func=status&code=99999 without ? mark - it works, and with ?- not. I understand, that it is query string and Django skips it in the regexp. So what can I do?
This URL:
portal/client_api.ashx?client=SAPRA&key=1234234&func=status&code=99999
has two parts, the path:
portal/client_api.ashx
and the query string:
client=SAPRA&key=1234234&func=status&code=99999
which is parsed into request.GET.
In views.py you should get params from request (like simple dict in request.GET), for example:
def test(request):
code = request.GET.get('code') # here we try to get 'code' key, if not return None
...
and of course, we can't use GET params to parse URLs in urls.py. Your urls.py should looks like:
from django.conf.urls import patterns, url
from rt_moke import views
urlpatterns = patterns('',
url(r'^portal/client_api\.ashx$', views.Sapata, name='sapata'),
)
P.S. Please, don't use capital letters in names of functions.