Why M I getting a 404 in my django project? - django

So I have a page which I want to render after the details section in my project. My urls.py is below:
from django.conf.urls import url
from . import views
app_name = 'main'
urlpatterns = [
url(r'^home/', views.home, name='home'), # Home page
url(r'incubators/$', views.incubators, name='incubators'), # Incubator list page
url(r'about/', views.about, name='about'), # Websie about page
url(r'results', views.result, name = 'result'), # For search function
url(r'incubators/(?P<incubator_id>[0-9]+)/', views.details, name = 'details'), # shows details of incubators
url(r'incubators/add-incuabtor/$', views.AddIncubator.as_view(), name = 'add-incubator'), # Adding Inc
url(r'/add-details/', views.AddDetails.as_view(), name = 'add-details'), #for additional details
url(r'news/', views.news, name = 'news'),
url(r'added/', views.added, name = 'added'), #your incubator will be added soon page
url(r'apply/', views.apply, name = 'apply'),
url(r'done/', views.done, name = 'done'),
url(r'location/', views.location, name = 'location'),
url(r'prediction/', views.prediction, name = 'prediction'),
url(r'^/locate/', views.locate, name = 'locate'),
]
I want to open a page (present in the details.html) which will be showing some info (in my case latitude and longitude) of that particular element.
Following is my views.py
def details(request, incubator_id):
inc = get_object_or_404(Incubators, pk = incubator_id)
details = Details.objects.get(pk = incubator_id)
return render(request, 'main/details.html', {'inc': inc, 'details': details})
def locate(request):
locate = get_object_or_404(Incubators, pk = incubator_id)
return render(request, 'main/locate.html', {'locate': locate})
But I am getting the following error:
NameError at //locate/
name 'incubator_id' is not defined
Request Method: GET
Request URL: http://127.0.0.1:8000//locate/
Django Version: 1.11.3
Exception Type: NameError
Exception Value:
name 'incubator_id' is not defined
Exception Location: C:\Users\my dell\Desktop\Project\junityme\main\views.py in locate, line 137
Python Executable: C:\Users\my dell\AppData\Local\Programs\Python\Python36-32\python.exe
Using the URLconf defined in Ekyam.urls, Django tried these URL patterns, in this order:
I think I am doing some mistake in making urls for this. Help would be appriciated.

http://127.0.0.1:8000//locate/ would be looking for a URL pattern that starts with "locate," but you don't have any URL patterns that start with locate. The URL should match the pattern, not the name you give it, or the view name.

Related

django - No User matches the given query. Page Not found 404: User post list view breaks post detail view

I'm fairly new to django and trying to build a message board app. Everything's been running smoothly up until I tried to add functionality to display a list of posts by author. I got it working but then my post detail view started throwing a 'No User matches the given query. Page Not found 404' error and I can't seem to figure out why. Can anyone help?
views.py
class UserPostList(generic.ListView):
model = Post
# queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'user_posts.html'
paginate_by = 6
def get_queryset(self):
"""
Method to return posts restricted to 'published' status AND to
authorship by the user whose username is the parameter in the
url.
"""
user = get_object_or_404(User, username=self.kwargs.get('username'))
return Post.objects.filter(
status=1, author=user
).order_by('-created_on')
class FullPost(View):
def get(self, request, slug, *args, **kwargs):
"""
Method to get post object.
"""
queryset = Post.objects.filter(status=1)
post = get_object_or_404(queryset, slug=slug)
comments = post.comments.order_by('created_on')
liked = False
if post.likes.filter(id=self.request.user.id).exists():
liked = True
return render(
request,
"full_post.html",
{
"post": post,
"comments": comments,
"liked": liked
},
)
# I'll be adding a comment form in here too
urls.py
urlpatterns = [
...
path('<slug:slug>/', views.FullPost.as_view(), name='boards_post'),
...
path('<str:username>/', views.UserPostList.as_view(), name='user_posts'),
...
]
Error message
(When trying to view a single post (previously working) after adding the UserPostList view and route)
Using the URLconf defined in mhcmsgboard.urls, Django tried these URL patterns, in this order:
1. admin/
2. summernote/
3. register/ [name='register']
4. profile/ [name='profile']
5. login/ [name='login']
6. logout/ [name='logout']
7. new/ [name='create_post']
8. <slug:slug>/update/ [name='update_post']
9. <slug:slug>/delete/ [name='delete_post']
10. <str:username>/ [name='user_posts']
The current path, test-post/, matched the last one.
for <str:name> in path "-" not allowed to use in name,
when you use Slug both paths are equal.
urlpatterns = [
...
path('<slug:slug>/', views.FullPost.as_view(), name='boards_post'),
...
path('<slug:username>/', views.UserPostList.as_view(), name='user_posts'),
]
there are 2 simple ways
use sub path for one or both paths : user_post/<slug:username>/
Use re_path and define the regex to change path
exp:
re_path(r'^(?P\<username>\w+)/$', views.UserPostList.as_view()),
The problem is that you match update_post, delete_post and user_posts URL's to the root. As the error message explains, the current request is made against user_posts. And it seems that you don't have a user called test-post.
You could solve it e.g. with the following URL conf:
urlpatterns = [
...
path('board/<slug:slug>/', views.FullPost.as_view(), name='boards_post'),
...
path('posts/<str:username>/', views.UserPostList.as_view(), name='user_posts'),
...
]
That way, each path is unique and Django knows which View it has to call.

Using double url tag in django

I got two urls.py file
first one is for project urls.py
urlpatterns = [
path('admin/', admin.site.urls , name = 'admin'),
path('',homeView, name='home'),
path('post/',post, name='post'),
path('post/',include('post.urls'), name='posturl'),
path('student/',studentM, name = 'student' ),
path('student/',include('student.urls') , name='studenturl'),
]
second one is url for app
urlpatterns = [
path('index', post_index, name = 'index'),
path('details/' + '<int:id>', post_detail, name = 'detail'),
path('create', post_create, name = 'create'),
path('update', post_update , name = 'update'),
path('delete', post_delete , name = 'delete'),
]
I am trying to reach the adress like
:8000/post/details/5
but when i try to use in html
=>> {{post.id}}
=>> {{post.id}}
=>> {{post.id}}
None of these are not working I got 404 error.
How can I reach the link which I want
def post(request):
context = {
}
return render(request,'post/post.html',context)
def post_detail(request,id):
post = get_object_or_404(Post,id=id)
context = {
'post' : post
}
return render(request,"post/details.html",context)
Im assuming that you are tryng to access this url pattern:
path('details/' + '<int:id>', post_detail, name = 'detail'),
which can be written like this:
path('details/<int:id>/', post_detail, name='detail'),
if im correct, you should use this in your html a tag:
text for the link
also, try not to do this:
path('post/',post, name='post'),
path('post/',include('post.urls'), name='posturl'),
it is better practice creating the post view inside your app, and then your urls.py are going to look like this:
# this is the project urls file
...
path('post/', include('post.urls')), # dont need a name here, you are not going to reference this
...
# this is the app urls file
...
path('', post, name='post'), # this is going to accessed as localhost:8000/post
path('index', post_index, name = 'index'),
path('details/<int:id>', post_detail, name = 'detail'), # this is going to accessed as localhost:8000/post/details/the_id_of_the_post
path('create', post_create, name = 'create'),
path('update', post_update , name = 'update'),
path('delete', post_delete , name = 'delete'),
...
Hope I've helped, if you still have any questions, feel free to contact me.

Django REST framework RetrieveAPIView gets empty "id" parameter and returns 404 error

I use Django 1.11 + Django REST Framework. I'm trying to get detailed data about distinct record using generic RetrieveAPIView from Django REST Framework and server returns "HTTP 404 Not Found" result, i.e. no data.
models.py file:
class TestPage( models.Model):
title = models.CharField( size = 120)
counter = models.IntegerField( default = 0)
def __unicode__(self):
return u'' + self.title
serializers.py file:
class TestPageSerializer(serializers.ModelSerializer):
class Meta:
fields = ('id', 'title', 'counter',)
model = models.TestPage
urls.py file:
urlpatterns = [
url( r'^admin/', admin.site.urls),
url( r'^api/', include( 'rest_framework.urls')),
url( r'^api/', include( 'testpages.urls')),
]
testpages/urls.py file:
urlpatterns = [
url( r'^$', views.TestPageList.as_view()),
url( r'^(?P<id>)\d+/$', views.TestPageDetail.as_view()),
]
and at last views.py file:
class TestPageList(generics.ListAPIView):
lookup_field = 'id'
queryset = TestPage.objects.all()
serializer_class = TestPageSerializer
class TestPageDetail(generics.RetrieveAPIView):
lookup_field = 'id'
queryset = TestPage.objects.all()
serializer_class = TestPageSerializer
# def get_object( self):
# print self.kwargs
If I request "http://127.0.0.1:8000/api/" for all records in the list, server returns all records. But if I want to get record by id using "http://127.0.0.1:8000/api/1/" for example, I get the empty result like in the photo below.
[![enter image description here][1]][1]
If I uncomment get_object()-function in last 2 lines, I can see {'id': u''} in terminal i.e. server gets empty parameter 'id'.
What wrong with this code?
The issue is your regular expression matching for id, you're putting \d+ outside of the matching group when it's actually what you want to match:
url(r'^(?P<id>\d+)/$', views.TestPageDetail.as_view())
By the way, to be good REST citizen, you shouldn't add the / at the end of a URL for a specific object.
Note: As mentioned by JPG, adding a name for the resource you're fetching (plural) would be proper RESTful:
url(r'^pages/(?P<id>\d+)$', views.TestPageDetail.as_view())
This way, you fetch page nr. 1 at /api/pages/1
The original problem was the closing parathesis (the regex expression), you were misplaced that.
urlpatterns = [
url(r'^$', views.TestPageList.as_view()),
url(r'^(?P<id>\d+)/$', views.TestPageDetail.as_view()),
^^^ here
]
Apart from that, You should change the urls patterns to a sensible form, as
#testpages/urls.py
urlpatterns = [
url(r'^test/$', views.TestPageList.as_view()),
url(r'^test/(?P<id>\d+)/$', views.TestPageDetail.as_view()),
]
then the list-api will be available on /api/test/ endpoint and the detail-api will be available on /api/test/{id}/

Adding urls/views to a model - Django Oscar?

I want to add some urls/views to dashboard app. So I forked the app using oscar_fork_app. I have created an app.py file in forked dashboardapp folder. Also added an app.py inside catalogue sub-app inside dashboard app. Following this.
My #dashboard/app.py
from oscar.apps.dashboard.app import DashboardApplication as CoreDashboardApplication
class DashboardApplication(CoreDashboardApplication):
name = 'dashboard'
permissions_map = {
'index': (['is_staff'], ['partner.dashboard_access']),
}
index_view = get_class('dashboard.views', 'IndexView')
catalogue_app = get_class('dashboard.catalogue.app', 'application')
def get_urls(self):
urls = [
url(r'^catalogue/', include(self.catalogue_app.urls)),
]
return self.post_process_urls(urls)
application = DashboardApplication()
My #dashboard/catalogue/app.py
from oscar.apps.dashboard.catalogue.app import CatalogueApplication as CoreCatalogueApplication
class CatalogueApplication(CoreCatalogueApplication):
name = None
csv_upload_view = get_class('dashboard.catalogue.views',
'CSVUpload')
def get_urls(self):
urls = [
url(r'^csvupload/$',
self.csv_upload_view.as_view(),
name='csvupload'),
]
return self.post_process_urls(urls)
application = CatalogueApplication()
when I hit /dashboard it says
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/dashboard/
Using the URLconf defined in teashop.urls, Django tried these URL patterns, in this order:
^i18n/
^admin/
^accounts/reviews/$ [name='review-list']
^accounts/subscriptions/$ [name='subscriptions']
^accounts/storecredit/$ [name='storecredit']
^catalogue/
^basket/
^checkout/
^accounts/
^search/
^dashboard/ ^catalogue/
^offers/
The current URL, dashboard/, didn't match any of these.
Do I have to copy paste all the urls in oscar.apps.dashboard.app to my forked_app ? What's the way to extend in the right way ?
I had to add all the urls of the parent class.
class DashboardApplication(CoreDashboardApplication):
...
catalogue_app = get_class('dashboard.catalogue.app', 'application')
def get_urls(self):
urls = super(DashboardApplication, self).get_urls()
urls += [
url(r'^catalogue/', include(self.catalogue_app.urls)),
]
return self.post_process_urls(urls)
Similarly for the other app.py
class CatalogueApplication(CoreCatalogueApplication):
name = None
csv_upload_view = get_class('dashboard.catalogue.views',
'CSVUpload')
def get_urls(self):
urls = super(CatalogueApplication, self).get_urls()
urls += [
url(r'^csvupload/$',
self.csv_upload_view.as_view(),
name='csvupload'),
]
return self.post_process_urls(urls)
application = CatalogueApplication()

url doesn't match with url file

I'm trying to deploy an app, but I'm getting Page not found (404) error for my login template/view. But the same code works on localhost.
This is the error message:
The current URL, accounts/profile/profile.html, didn't match any of these.
URLs file:
urlpatterns = patterns('',
# Examples:
url(r'^$', 'survey.views.home', name='home'),
url(r'^survey/(?P<id>\d+)/$', 'survey.views.SurveyDetail', name='survey_detail'),
url(r'^confirm/(?P<uuid>\w+)/$', 'survey.views.Confirm', name='confirmation'),
url(r'^privacy/$', 'survey.views.privacy', name='privacy_statement'),
url(r'^admin/', include(admin.site.urls)),
url(r'^piechart/$', 'survey.views.piechart', name = 'chart_code.html'),
url('^accounts/', include('registration.urls')),
url('^accounts/login/$', 'survey.views.login'),
url('^accounts/auth/$', 'survey.views.auth_view'),
**url('^accounts/profile/$', 'survey.views.profile'),**
url('^accounts/logout/$', 'django.contrib.auth.views.logout'),
url(r'^map/$','survey.views.javamap', name = 'chart_code.html'),
url(r'^charts', 'survey.views.charts', name='charts'),
url(r'^login/$', 'django.contrib.auth.views.login'),
url(r'^accounts/auth/profile', 'survey.views.profile', name = 'profile.html'),
url(r'^profile', 'survey.views.profile', name = 'profile.html'),
url(r'^accounts/auth/results', 'survey.views.survey_name', name = 'results.html'),
url(r'^answer_survey', 'survey.views.answer_survey'),
url(r'^results/(?P<id>\d+)/$', 'survey.views.SurveyResults', name='results'),
)
The profile views:
#login_required
def profile(request):
user = request.user
if user.is_authenticated():
n_survey = Survey.objects.filter(user = user)
if n_survey:
print "*---------- str " + str(n_survey)
for survey in n_survey:
print "survey id " + str(survey.id)
n = len(n_survey)
print "n " + str(n)
return render(request, 'profile.html')
else:
print("*---------- sem surveys para print")
return HttpResponseRedirect('profile.html')
else:
msg = "Usuario ou senha digitados incorretamente"
return HttpResponseRedirect('home.html', {'msg': msg})
In localhost, the URL accounts/profile matches because django doesn't incluse profile.html at the end. How to solve this?
You are doing a redirect to a relative URL:
return HttpResponseRedirect('profile.html')
That means, if you are currently at /accounts/profile/, you will be redirected to /accounts/profile/profile.html. If you want to redirect to the view named profile.html, you can, for example, use the redirect shortcut:
from django.shortcuts import redirect
# ...
return redirect("profile.html")
Which is roughly equivalent to HttpResponseRedirect(reverse("profile.html")).
There is another problem in your url configuration: it contains some lines like this:
url(r'^charts', 'survey.views.charts', name='charts'),
There are two problems with this line
There is no slash at the end of the URL. It is better to be consistent and have a slash at the end of all URLs
There is no end-of-line special character $ at the end of the pattern. This means that many different URLs will match the pattern, for example /charts, /charts/foo, /chartsarecool and so on..
Better write
url(r'^charts/$', 'survey.views.charts', name='charts')
^^