So far, I have built a REST API with Django Rest Framework (DRF) which can be consumed by any front-end. Let call this API backend.
I am trying to add another Django app (a regular one this time i.e. no DRF) which shares the same models. Let call this app webapp
However, it seems that the URLs linked to webapp are not available.
Here is my urls.py:
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from rest_framework.authtoken import views as token_views
from backend import views
from webapp import views as webapp_views
router = routers.SimpleRouter()
router.register(r'users', views.UserViewSet, 'User')
router.register(r'games', views.GameViewSet, 'Game')
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^connect/', views.CustomObtainAuthToken.as_view()),
url(r'membership_create/', views.MembershipCreate.as_view()),
url(r'auth/connect_with_fb/', views.ConvertTokenViewWithData.as_view()),
url(r'auth/connect_with_credentials/', views.TokenViewWithData.as_view()),
url(r'debug/', views.UserLoginAndIdView.as_view()),
url(r'^auth/', include('rest_framework_social_oauth2.urls'),
url(r'^test/', webapp_views.home, name='test'), # the new view
)
]
urlpatterns += router.urls
And the single view (from webapp.views):
from django.http import HttpResponse
from django.shortcuts import render
def home(request):
return HttpResponse("""
<h1>WEBAPP !</h1>
<p>test webapp</p>
""")
I am thus wondering if DRF and regular Django views can be mixed so easily or if it is not the right way of doing it.
EDIT:
Using the URLconf defined in WMC.urls, Django tried these URL patterns, in this order:
^admin/
^connect/
membership_create/
auth/connect_with_fb/
auth/connect_with_credentials/
debug/
^auth/
^users/$ [name='User-list']
^users/(?P<pk>[^/.]+)/$ [name='User-detail']
^users/(?P<pk>[^/.]+)/games/$ [name='User-games']
^games/$ [name='Game-list']
^games/(?P<pk>[^/.]+)/$ [name='Game-detail']
The current URL, test/, didn't match any of these.
Moving url(r'^test/', webapp_views.home, name='test') before url(r'^admin/', admin.site.urls) solves the problem although I do not know why.
urlpatterns = [
url(r'^test/', webapp_views.home, name='test'),
url(r'^admin/', admin.site.urls),
url(r'^connect/', views.CustomObtainAuthToken.as_view()),
url(r'^membership_create/', views.MembershipCreate.as_view()),
url(r'^auth/connect_with_fb/', views.ConvertTokenViewWithData.as_view()),
url(r'^auth/connect_with_credentials/', views.TokenViewWithData.as_view()),
url(r'^debug/', views.UserLoginAndIdView.as_view()),
url(r'^auth/', include('rest_framework_social_oauth2.urls'),
)
]
Related
ok polls tutorial is done and can enter questions, vote, etc. but from the admin pages View site aka localhost:8000 gives...
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
dose/
admin/
The empty path didn’t match any of these.
Now I have polls/views.py...
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.utils import timezone
from django.views import generic
from .models import Choice, Question
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
"""
Return the last five published questions (not including those set to be
published in the future).
"""
return Question.objects.filter(
pub_date__lte=timezone.now()
).order_by('-pub_date')[:5]
and mysite/urls.py set to ...
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
and polls/urls.py set to...
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
The only hint I can find is that all the imports show error highlights in VSCode with the Error "reportMissingModuleSources"
But python and django run perfectly well everywhere but index.html
No url at http://localhost:8000/ address is expected behaviour, where you want to go is http://localhost:8000/polls/.
If you want go directly to the desired View without writing polls/ prefix you should define your urls this way:
urlpatterns = [
path('', include('polls.urls')),
path('admin/', admin.site.urls),
]
So you place path() call without url prefix. Generally if you include any url group you define the beginning of address this way.
I've tried setting these URL's in this project, but I get a 404 when trying to access the registration.html file and the api-auth URL that is related to a REST API
For reference:
index = app
django_test = site
index/urls.py
from django.urls import include, path
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path('', views.homepage, name="homepage"),
path('/register', views.registration, name="registration"),
path('api', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace="rest framework")),
]
django_test/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('index.urls')),
path('admin/', admin.site.urls)
]
index/views.py
from django.shortcuts import render
def homepage(request):
return render(request,"home/homepage.html")
def registration(request):
return render(request, 'home/registration.html')
All of our HTML files are located in index/templates/home directory
Can you try changing name="registration" to name="register" ?
Change the URL "register/" to "/registration"
I migrated my Django project to an Ubuntu distant server. I'm using mod_wsgi in order to runserver and I have some questions about default page.
I'm really new in this domain and I apologize if my question is bad or useless ..
When I want to connect to my Django application, I have to write something like that :
http://172.XX.XX.XXX/Home/login/
If I write just :
http://172.XX.XX.XXX
I get :
Page not found
Using the URLconf defined in Etat_civil.urls, Django tried these URL patterns, in this order:
^admin/
^BirthCertificate/
^Identity/
^Accueil/
^Home/
^captcha/
^Mairie/
The current URL, , didn't match any of these.
My question is :
How I can define redirected url in order to write http://172.XX.XX.XXX in my browser and go directly to http://172.XX.XX.XXX/Home/login/ for example ?
This is urls.py file from my project :
from django.conf.urls import url, include
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
from BirthCertificate import views
from Identity import views
from Accueil import views
from log import views
from Mairie import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^BirthCertificate/', include('BirthCertificate.urls')),
url(r'^Identity/', include('Identity.urls')),
url(r'^Accueil/', include('Accueil.urls')),
url(r'^Home/', include('log.urls')),
url(r'^captcha/', include('captcha.urls')),
url(r'^Mairie/', include('Mairie.urls')),
]
Because I just want for example, write my IP adress in order to access to my Django application and not write all the time a complete url.
If you need some files (apache2 files, ...) please tell me which one I have to post there.
Include this in views.py file of your any app:
from django.shortcuts import redirect
def some_view(request):
return redirect('/Home/login/')
Suppose the view is in log app then,
Include this in your urls.py:
from log.views import some_view
urlpatterns = [
url(r'^$', some_view,name='index'),
url(r'^admin/', admin.site.urls),
url(r'^BirthCertificate/', include('BirthCertificate.urls')),
url(r'^Identity/', include('Identity.urls')),
url(r'^Accueil/', include('Accueil.urls')),
url(r'^Home/', include('log.urls')),
url(r'^captcha/', include('captcha.urls')),
url(r'^Mairie/', include('Mairie.urls')),
]
One method is to use RedirectView by making the following changes to your urls.py:
from django.views.generic.base import RedirectView
urlpatterns = [
url(r'^$', RedirectView.as_view(url='/Home'), name='home'),
...
]
You can either do this in Django or Configure from your webserver. Django has redirects app go through https://docs.djangoproject.com/en/1.10/ref/contrib/redirects/ for more info. You just add the source and redirect urls in the redirects section of your django admin.
I want to use the admin page as 2 section
Admin site
Rest Framework API
After login into the admin only I have to access the REST API too.
Project Url is,
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/', include('snippets.urls')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) )
My App Url is
urlpatterns = [
url(r'^snippets/$', views.snippet_list),]
You can do something like this.In app urls.py by wrapping login_required decorator
from django.contrib.auth.decorators import login_required
urlpatterns = [
url(r'^snippets/$', login_required(views.snippet_list)),]
you need use real functions instead of their names.(its ok now)
OR
Use middleware, to check whether user is authenticated.
I'm totally new to Django, and I'm trying to understand how does it work (I'm more used to PHP and Spring frameworks.
I have a project called testrun and inside it an app called graphs, so my views.py looks like:
#!/usr/bin/python
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, World. You're at the graphs index.")
then, in graphs/urls.py:
from django.conf.urls import patterns, url, include
from graphs import views
urlpatterns = patterns(
url(r'^$', views.index, name='index'),
)
finally, at testrun/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'testrun.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^graphs/', include('graphs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
However, when I try to access http://127.0.0.1:8000/graphs/ I get:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/graphs/
Using the URLconf defined in testrun.urls, Django tried these URL patterns, in this order:
^admin/
The current URL, graphs/, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
What am I doing wrong that I can't get that simple message to be displayed in the browser?
To expand on my comment, the first argument to patterns() function is
a prefix to apply to each view function
You can find more information here:
https://docs.djangoproject.com/en/dev/topics/http/urls/#syntax-of-the-urlpatterns-variable
Therefore in graphs/urls.py you need to fix the patterns call like so:
urlpatterns = patterns('', # <-- note the `'',`
url(r'^$', views.index, name='index'),
)