I created an endpoint and registered it in urls.py. When I try to hit the endpoint I get a 404 error but on the 404 page the url is shown as one of the patterns django tried to match. Stumped.
api.py
class UpdateLast(viewsets.GenericViewSet, UpdateModelMixin):
def get(self):
return XYZModel.objects.all()
def partial_update(self, request, *args, **kwargs):
if request.user.is_superuser:
with transaction.atomic():
for key, value in request.data:
if key == 'tic':
XYZModel.objects.filter(ticker=request.data['tic']).filter(trail=True).update(
last_high=Case(
When(
LessThan(F('last_high'),
request.data['high']),
then=Value(request.data['high'])),
default=F('last_high')
)
)
urls.py (this is inside the app)
router = routers.DefaultRouter()
router.register('api/dsetting', DViewSet, 'dsetting')
router.register('api/update-last-high', UpdateLast, 'update-last-high')
urlpatterns = [
path('', include(router.urls))
]
urls.py (main)
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('my_app.urls')),
When I hit the end-point api/update-last-high I get a 404 page.
On that page the exact end-point is shown as a pattern that django tried to match.
^api/update-last-high/(?P[^/.]+)/$ [name='update-last-high-detail']
^api/update-last-high/(?P[^/.]+).(?P[a-z0-9]+)/?$ [name='update-last-high-detail']
from rest_framework import routers
from . import views
from django.urls import path, include
router = routers.DefaultRouter()
router.register('api/dsetting', DViewSet, 'dsetting')
router.register('api/update-last-high', UpdateLast, 'update-last-high')
# you forgot to include the router.urls
urlpatterns = [
path('', include(router.urls))
]
Related
views.py
from django.views.generic import ListView
from .models import Staff
class StaffListView(ListView):
model = Staff
template_name = 'staff/staff_list.html'
def get_queryset(self):
return Staff.objects.filter(websites__path=self.kwargs['web'])
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('<str:web>/staff/', include('staff.urls')),
# I want to set web=chemical, if url is http://127.0.0.1:8000/staff
]
With Django URL you cannot do that. But I have a cheat way. You can use middlewares > Check the URL if this one is a URL validated with empty param > redirect it to the correct URL.
Sample:
def redirect_middleware(get_response):
def middleware(request, *args, **kwargs):
# In here I write a sample with a basic check, you can use regex to check.
if request.path == "/staff":
return redirect('/chemical/staff')
response = get_response(request, *args, **kwargs)
return response
return middleware
A simple solution is to use RedirectView ?
urlpatterns = [
path('admin/', admin.site.urls),
path('<str:web>/staff/', include('staff.urls')),
path('staff', StaffRedirectView.as_view()),
]
# in views
from django.views.generic.base import RedirectView
class StaffRedirectView(RedirectView):
def get_redirect_url(self, *args, **kwargs):
return "/chemical" + self.request.get_full_path()
I think, this idea can be work for your case
urlpatterns = [
path('admin/', admin.site.urls),
path('staff/', include('staff.urls'),kwargs={'web':''}),
path('<str:web>/staff/', include('staff.urls')),
]
staff.urls.py
urlpatterns = [
path('',views.StaffListView.as_view())
]
I'm trying to add a secondary admin site and it's working correctly except that any links are pointing to the main admin site. Not sure how to get around this.
If I visit /dispatch/admin/ the model Run is visible but when I click the link it directs me to /admin/dispatch/run/ instead of /dispatch/admin/dispatch/run/.
Django==3.2.7
class DispatchAdminSite(admin.AdminSite):
pass
class DispatchRunAdmin(RunAdmin):
def get_queryset(self, request):
return (
super().get_queryset(request)
.filter_today_or_future()
)
def get_readonly_fields(self, request, obj=None):
return [f.name for f in self.model._meta.fields]
dispatch_admin_site = DispatchAdminSite(name='Dispatch')
dispatch_admin_site.register(models.Run, DispatchRunAdmin)
dispatch/urls.py
app_name = 'dispatch'
urlpatterns = [
path('admin/', admin.dispatch_admin_site.urls),
]
project/urls.py
urlpatterns = [
path('dispatch/', include('dispatch.urls')),
path('admin/', admin.site.urls),
]
For whatever reason the custom admin can't be added using include it has to be a top level URL in your project.
# project/urls.py
from django.contrib import admin
from dispatch.admin import dispatch_admin_site
urlpatterns = [
path('dispatch-admin/', dispatch_admin_site.urls),
path('admin/', admin.site.urls),
]
When I first created the urls with 'pk' they worked fine.
But when I use 'slug' for lookup, when I change the url it throws 404.
from django.urls import path
from .views import (ProductListView, ProductDetailView,
ProductFeaturedListView, ProductFeaturedDetailView)
app_name = 'products'
urlpatterns = [
path('', ProductListView.as_view(),
name='list'),
path('detail/<str:slug>/', ProductDetailView.as_view(),
name='detail'),
path('featured/', ProductFeaturedListView.as_view(),
name='featured-list'),
path('featured/<str:slug>/', ProductFeaturedDetailView.as_view(),
name='featured-detail')
]
Now when I change the 'product-detail' url, the feature url throws error which is irrelevant. And it says that this particular view is causing it. But the view has no relation with 'featured-product-list' url.
from .views import (ProductListView, ProductDetailView,
ProductFeaturedListView, ProductFeaturedDetailView)
app_name = 'products'
urlpatterns = [
path('', ProductListView.as_view(),
name='list'),
path('<str:slug>/', ProductDetailView.as_view(),
name='detail'),
path('featured/', ProductFeaturedListView.as_view(),
name='featured-list'),
path('featured/<str:slug>/', ProductFeaturedDetailView.as_view(),
name='featured-detail')
]
error
On diagnosing it I find that it is trying to pass 'featured' as a slug, which is out of my logic.
Please help me to find what is causing this issue.
here is the detailed error
class ProductDetailView(DetailView):
template_name = 'products/product_detail.html'
def get_object(self):
slug = self.kwargs.get('slug')
try:
instance = Product.objects.all().get(slug=slug)
except Product.DoesNotExist:
raise Http404('Not Found...')
except Exception:
raise Http404('huh?')
return instance
code of project named carparts urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('parts.urls')),
]
code for my app named parts urls.py
from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.index,name='index'),
path('about', views.about,name='about'),
path('contact', views.contact,name='contact'),
]
code for views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return render(request, 'index.html')
# return HttpResponse('this is home page')
def about(request):
return render(request, 'about.html')
def contact(request):
return render(request, 'contact.html')
index page code output is show in http://127.0.0.1:8000 but my about and contact page shows Page not found (404) . Can any one help me with this code.
Thank you
Joint '/' in your both urls.py like that:
urlpatterns = [
path('', views.index,name='index'),
path('about/', views.about,name='about'),
path('contact/', views.contact,name='contact'),
]
According Django Design philosophy on Definitive URLs:
Technically, foo.com/bar and foo.com/bar/ are two different URLs, and
search-engine robots (and some Web traffic-analyzing tools) would
treat them as separate pages. Django should make an effort to
“normalize” URLs so that search-engine robots don’t get confused.
ive created some urls with the default router as per the below:
api.urls
from django.urls import path, include
from rest_framework import routers
from rest_framework_bulk.routes import BulkRouter
from . import views
router = routers.DefaultRouter()
#### NEW ####
router.register(r'data/credentials/', views.DataCredentials)
router.register(r'data/site_circuits', views.DataSiteCircuits)
router.register(r'data/subnets/', views.SubnetsSet)
router.register(r'data/device_conns/', views.DataDeviceConns)
router.register(r'data/email_subscriber/', views.DataEmailSubscriber)
router.register(r'data/pd_user/', views.DataOnCall)
router.register(r'data/bgp/', views.DataBGP)
router.register(r'data/device/routingtable/', views.DataDeviceRoutingTable)
router.register(r'monitoring/bgp/', views.MonitoringBGP)
router.register(r'monitoring/script_results/', views.MonitoringScriptResults)
router.register(r'monitoring/circuit_maintenance/', views.MonitoringCircuitMaintenance)
router.register(r'monitoring/device/routingtable/', views.MonitoringDeviceRoutingTable)
#### LEGACY ####
router.register(r'credentials', views.CredentialDataROView)
router.register(r'tasks', views.TaskSet)
router.register(r'subnets', views.SubnetsSet)
router.register(r'device_conns', views.DeviceConnViewSet)
router.register(r'script_results', views.ScriptResultsView)
router.register(r'circuit_maintenance', views.CircuitMaintenanceView)
router.register(r'email_subscriber', views.EmailSubscriberROView)
router.register(r'pd_user', views.OnCallROView)
router.register(r'bgp_monitoring_data', views.BGPMonitoringDataView)
router.register(r'bgp_status', views.BGPStatusView)
router.register(r'rt_get_devices', views.MonitoringRoutingTableGetDevice)
router.register(r'rt_get_tables', views.MonitoringRoutingTableGet)
router.register(r'rt_upload', views.MonitoringRoutingTableUpload)
router.register(r'contact_type', views.ContactTypeROView)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls')),
#### NEW ####
path('data/site_subnets/', views.DataSiteSubnets.as_view()),
path('data/site_circuits_subnets/', views.DataSiteCircuitSubnets.as_view()),
path('data/device/routing_table/', views.DataDeviceRoutingTable.as_view({'get': 'list','put': 'update'})),
path('data/geomapping/', views.DataGeoMapping.as_view()),
path('monitoring/oncall/', views.MonitoringOnCall.as_view()),
path('monitoring/site_connectivity/', views.MonitoringSiteConnectivity.as_view()),
#### LEGACY ####
path('ss_monitoring_data/', views.SiteSupernetMontioringDataROView.as_view()),
path('monitoring/routing_data', views.MontioringGetRoutingData.as_view()),
path('conn_set_single/<int:site_id>/<int:circuit_id>/', views.MonitoringConnectivitySetSingle.as_view()),
path('conn_set/', views.MonitoringConnectivitySet.as_view()),
path('site_circuits_pending/<int:days>/', views.SiteCircuitsPendingDataROView.as_view({'get': 'list'})),
path('upcoming_circuit_maintenance/<int:days>/', views.UpcomingCircuitMaintenanceView.as_view({'get': 'list'})),
path('aws_bgpdata_set/', views.MonitoringBGPDataSet.as_view()),
path('aws_dc_set/', views.MonitoringAWSDirectConnectSet.as_view()),
path('aws_vpn_set/', views.MonitoringAWSVPNSet.as_view()),
path('four_g_set/', views.FourGDataSet.as_view()),
path('contact_set/', views.ContactSet.as_view()),
path('site_contact_set/', views.SiteContactSet.as_view()),
path('device_version_set/', views.DeviceVersionSet.as_view()),
]
home.urls
from django.urls import path
from . import views
app_name = 'home'
urlpatterns = [
path('', views.index, name='index'),
....
and then I attempt to hit the URL http://localhost:8100/api/data/device/routingtable/ and I am greeted with a 404, would anyone know why this is?
and when I hit my api home page and it lists urls, they are mapped to the wrong views:
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
...
"data/device/routingtable/": "http://localhost:8100/api/rt_upload/",
...
}
views.py:
class DataDeviceRoutingTable(viewsets.ModelViewSet):
time_threshold = datetime.now() - timedelta(minutes=2)
queryset = DeviceData.objects.all().select_related('device','device_use').order_by('monitoring_order')
serializer_class = SerializerDataRoutingTable
permission_classes = (IsAdminUser,)
filter_class = DeviceData
filter_backends = (filters.SearchFilter,)
search_fields = ('device__hostname','device_use__use')
serialisers.py:
class SerializerDataRoutingTable(serializers.ModelSerializer):
hostname = serializers.ReadOnlyField(source='device.hostname', )
site_id = serializers.ReadOnlyField(source='device.site_id', )
routing_table = serializers.SerializerMethodField(source='routing_table',)
use = serializers.ReadOnlyField(source='device_use.use', )
def get_routing_table(self, instance):
try:
return json.loads(instance.routing_table)
except:
return instance.routing_table
class Meta:
model = DeviceData
fields = ('id','site_id','device_id','hostname','use', 'timestamp', 'routing_table')
depth = 1
urls.py:
from django.urls import path, include
from django.conf import settings
from django.contrib.auth import views as auth_views
from django.contrib import admin
import app_settings.views
admin.autodiscover()
handler400 = 'app_settings.views.bad_request'
handler403 = 'app_settings.views.permission_denied'
handler404 = 'app_settings.views.page_not_found'
handler500 = 'app_settings.views.server_error'
urlpatterns = [
path('', include('home.urls')),
path('api/', include('api.urls')),