I have a django project with django-rest-framework named MyProject in which I have created an app accounts.
I have the following code inside MyProject/urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('accounts.urls', namespace='accounts')),
path('admin/', admin.site.urls),
]
Inside MyProject/accounts/urls.py, I have:
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register('accounts', views.UserView)
urlpatterns = [
path('', router.urls)
]
Inside MyProject/accounts/views.py:
import sys
from django.shortcuts import render, redirect
from django.contrib.auth.models import User, auth
from django.contrib import messages
from rest_framework import viewsets
from .serializers import UserSerializer
class UserView(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
I am getting the error:
> File
> "C:\Users\user\PycharmProjects\MyProject\accounts\urls.py",
> line 10, in <module>
> path('', router.urls) File "C:\Users\user\PycharmProjects\MyProject\venv\lib\site-packages\django\urls\conf.py",
> line 61, in _path
> urlconf_module, app_name, namespace = view ValueError: too many values to unpack (expected 3)
The router.urls contains a list of urls. You can simply set the urlpatterns to that list:
router = routers.DefaultRouter()
router.register('accounts', views.UserView)
urlpatterns = router.urls
Or you can append the values if you want to make other paths:
router = routers.DefaultRouter()
router.register('accounts', views.UserView)
urlpatterns = [
# …
]
urlpatterns += router.urls
Related
I am unable to access the url after path("", include(router.urls)),
i would like to render a template after the load
i am using django rest framework and i want to access the url after the rest fromework router and render a template
from django.urls import path, include
from rest_framework import routers
from .views import NSE_DATA_VIEW_SET, AddCoi
router = routers.DefaultRouter()
router.register(r"", NSE_DATA_VIEW_SET)
urlpatterns = [
path("", include(router.urls)),
path("add", AddCoi)
]
Image:
from django.urls import include, path
urlpatterns = [
path("nsedata/", include("api.nsedata.urls")),
path("coidata/", include("api.coidata.urls"))
]
I am keep getting 404 in DRF whenever I send request from postman even though the url is correct.
urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('backend.urls'))
]
backend/urls.py
from django.urls import path, include
from . import views
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('/post', views.PostView, basename='post')
urlpatterns = [
path('', include(router.urls)),
]
From postman I am sending post request on the endpoint http://127.0.0.1:8000/post but I am keep getting 404 not found error. What am I doing wrong?
This is what works for me.
Create a app named backend using python manage.py startapp {app_name} where app_name is backend
Add the newly created app to INSTALLED_APPS in your project settings.py
In your project url.py file do this:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path("", include("backend.urls")),
]
In your app urls.py file. (where app is backend):
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register('post', views.PostView, basename='post')
app_name = 'backend'
urlpatterns = [
path('', include(router.urls)),
]
Then in your app(backend) views.py define PostView
This should work.The endpoint should be at :
http://localhost:8000/post/ .
if your using port 8000
Try to change backend/urls.py:
import views
from django.urls import path, include
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('post', views.PostView, basename='post')
urlpatterns = router.urls
I have a HomeView Class which I added a login_required, but I don't know how to redirect it with the custom login page that I made.
Here are the urls.py and settings.py in my project:
myblog\urls.py
from django.contrib import admin
from django.urls import path,include
from .settings import DEBUG, STATIC_URL, STATIC_ROOT, MEDIA_URL, MEDIA_ROOT
from django.conf.urls.static import static
# from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myblog_app.urls')),
path('members/', include('django.contrib.auth.urls')),
path('members/', include('members.urls')),
]
# + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
if DEBUG:
urlpatterns += static(STATIC_URL,document_root =STATIC_ROOT )
urlpatterns += static(MEDIA_URL,document_root = MEDIA_ROOT)
myblog_app\urls.py
from django.urls import path
from django.contrib.auth.decorators import login_required
from .views import HomeView,ArticleDetailView,AddPostView,UpdatePostView,DeletePostView,AddCategoryView,CategoryView,CategoryListView,LikeView,AddCommentView
urlpatterns = [
path('', login_required(HomeView.as_view()),name='home'),
path('article/<int:pk>', ArticleDetailView.as_view(),name='article-detail'),
path('add_post/', AddPostView.as_view(),name='add_post'),
path('article/<int:pk>/comment/', AddCommentView.as_view(),name='add_comment'),
path('article/edit/<int:pk>', UpdatePostView.as_view(),name='update_post'),
path('article/<int:pk>/remove', DeletePostView.as_view(),name='delete_post'),
path('add_category/', AddCategoryView.as_view(),name='add_category'),
path('category/<str:cats>', CategoryView,name='category'),
path('category-list', CategoryListView,name='category_list'),
path('like/<int:pk>', LikeView,name='like_post'),
]
members/urls.py
from django.urls import path
from .views import UserRegisterView,UserEditView,UserLoginView,PasswordsChangeView,ShowProfilePageView,EditProfilePageView
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
path('login/',UserLoginView, name='login'),
path('register/',UserRegisterView.as_view(), name='register'),
path('edit_profile/',UserEditView.as_view(), name='edit_profile'),
# path('password/',auth_views.PasswordChangeView.as_view(template_name='registration/change-password.html')),
path('password/',PasswordsChangeView.as_view(template_name='registration/change-password.html')),
path('password_success/',views.password_success,name='password_success'),
path('<int:pk>/profile/',ShowProfilePageView.as_view(),name='show_profile_page'),
path('<int:pk>/edit_profile_page/',EditProfilePageView.as_view(),name='edit_profile_page'),
]
settings.py
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
LOGIN_REDIRECT_URL='home'
LOGOUT_REDIRECT_URL='login'
What it's doing now is that it basically just redirects to the
path('', login_required(HomeView.as_view()),name='home') and it doesn't know where to get the login url from, so instead it should redirect to path('login/',UserLoginView, name='login') but I have no idea how to do it
Okay I found the answer, so I just add in login_url='([login url path])' so that it redirects to the login url that I wanted... now it should look like this:
path('',login_required(HomeView.as_view(),login_url='/members/login/'),name='home'),
I have got a CRUD App, I'm learning API rest with Python and Django... I create this module:
from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model: User
fields = ['url', 'username', 'email', 'groups']
And after that, I write this:
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from djangoCRUD.Api.serializer import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().orderby('-date_joined')
serializer_class = UserSerializer
This is all right, but, when I write my url.py Here, I have got a problem:
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from djangoCRUD.Api import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
And I have this error message:
File "C:\PythonDev\pythoncrud\venv\djangoCRUD\djangoCRUD\urls.py", line 20, in
from djangoCRUD.Api import views
ModuleNotFoundError: No module named 'djangoCRUD.Api'
Try the following code:
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
# from djangoCRUD.Api import views
from djangoCRUD.Api.views import UserViewSet
router = routers.DefaultRouter()
# router.register(r'users', views.UserViewSet)
router.register(r'users', UserViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
I'm trying to create an api that uploads an image with an email to the database. But I'm getting an error "raise ImproperlyConfigured(msg.format(name=self.urlconf_name))" Is the problem in my urls.py?
https://imgur.com/OjPUhOv.jpg
This is how my structure looks
https://imgur.com/TW6pKPn.jpg
This is the error
for urls.py-
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('user.urls')),
path('api/',include('api_test.urls'))
# path('articles/',include('articles.urls'))
]
for api_test/urls.py
from django.urls import path,include
from django.conf import settings
from . import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register('image_test',views.api_test,base_name='image_test')
urlpatterns = [
# path('/',views.api_test),
path('',include(routers.url)),
]
for views.py
class api_test(viewsets.ModelViewSet):
queryset = fineDB.objects.all()
serializer_class = fineSerializer
##for serializers.py
from rest_framework import serializers
from .models import fineDB
class fineSerializer(serializers.ModelSerializer):
image = serializers.ImageField(max_length=None,use_url=True)
class Meta:
model = fineDB
fields = {'email','image'}
You should probably get the urls from router, not routers.
At the same time you don't need both the router and the urlpatterns in that file. You can import the router and mount it's router.urls in urls.py.
from rest_framework import routers
router = routers.DefaultRouter()
router.register('image_test',views.api_test,base_name='image_test')
urlpatterns = [
# path('/',views.api_test),
path('',include(router.urls)), # <-
]