I'm fairly new to django. I completed the django project tutorial, and took away a good understanding of it, at least I thought I did. My understanding of how urls.py and views.py are related is urls.py points to the function of views.py and looks for a file to execute based on a page.
Here is my file structure:
The root folder is right above the "friendfinder" folder called "ff"
The 404 error I have shows on all 3 static html pages: index, friends, and contacts.
Here is what my urls.py page looks like:
from django.conf.urls import url
from gather import views
urlpatterns = [
url(r'^interest/', views.InterestView.as_view(), name="interest"),
url(r'^$', views.index, name="index"),
url(r'^friends/', views.friends, name="friend"),
url(r'^contact/', views.contact, name="contact"),
]
This is my views.py page:
import json
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from gather.models import Interest
def index(request):
all_interests = Interest.objects.all()
return render(
request,
' gather/index.html',
{
'stuff': 'TEST',
'interests': all_interests
}
)
def friends(request):
return render(request, 'gather/friends.html')
def contact(request):
return render(request, 'gather/contact.html')
class InterestView(View):
def post(self, request):
try:
json_data = json.loads(request.body.decode('utf-8'))
new_interest = Interest(
name=json_data['name'],
description=json_data['description'],
approved=False
)
new_interest.save()
return HttpResponse('ok')
except ValueError:
return HttpResponse('Fail', status=400)
def get(self, request):
try:
search = request.GET.get("search", None)
interests = Interest.objects.filter(name__icontains=search)
interest_json = []
for interest in interests:
interest_json.append({
'name': interest.name,
'description': interest.description
})
return JsonResponse({'search_result': interest_json})
except ValueError:
return HttpResponse('404 Page Not Found', status=400)
On the settings.py page I have under installed apps, I added the app named 'gather', and
ROOT_URLCONF = friendfinder.urls
I also took a look at this page:urls.py and views.py information
I thought maybe my problem was a file structure issue.
Any pointers, hints, tips,and/or explanations of why the urls.py and views.py page are not matching each other's information would be greatly appreciated.
EDIT: Code for Friendfinder/urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('gather.urls', namespace='gather', app_name='gather'))
]
Related
I'm making a django project and whenever I run "python manage.py runserver". I see the above error.
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import ToDoList, Item
# Create your views here.
def index(response, id):
ls = ToDoList.objects.get(id=id)
return render(response, "main/base.html", {})
def home(response):
return render(response, "main/home.html", {})
main/url.py
from django.urls import path
from main import views
from . import views
urlpatterns = [
path("<int:id>", views.index, name="index"),
path("", views.home, name="home")
]
mysite/url.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("main.urls")),
]
Thank you for the help.
main/urls.py
from django.urls import path
from main import views
from . import views
Those last two imports both import the name views, so the first one is overwritten by the second one.
Your home function is indented wrongly, it's currently a function inside the index function, not in the global scope.
Change it to the following
views.py
def index(response, id):
ls = ToDoList.objects.get(id=id)
return render(response, "main/base.html", {})
def home(response): # Don't indent this!
return render(response, "main/home.html", {})
There must be a configuration issue but if you want to see if website is working or def Home(): is working. Change your code to
def home(request):
return HttpResponse('<h1>Blog Home</h1>')
Using the URLconf defined in todo.urls, Django tried these URL patterns, in this order:
^admin/
^todoapp/
The empty path didn't match any of these.
404 error is showing when I run my code which you can find below. This code is app url:
from django.contrib import admin
from django.conf.urls import url
from todoapp import views
urlpatterns = [
#url(r'^admin/', admin.site.urls),
url(r'^$',views.index,name='index'),
#todoapp/1
url(r'^(?P<task_id>[0-9]+)/$',views.detail, name='detail'),
]
And it is the main url.py
from django.contrib import admin
from django.conf.urls import url, include
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^todoapp/',include('todoapp.urls')),
]
views.py is here:
from django.shortcuts import render
from django.http import HttpResponse
from .models import Task
from django.template import loader
# Create your views here.
def index(request):
task_list = Task.objects.all()
template = loader.get_template('todoapp/index.html')
context = {
'task_list': task_list
}
return render(request, 'todoapp/index.html',context)
def detail(request, task_id):
task = Task.objects.get(pk=task_id)
context = {
'task': task,
}
return render(request,'todoapp/detail.html',context)
Why it is not working, I could not find a problem. How can I fix it?
I am trying to show a blogpost on the site.
Below is details of urls and view file details but still it showing a 404 not found page
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="ShopHome"),
path("blogpost/", views.blogpost, name="blogpost")
]
views.py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
def index(request):
return render(request, 'blog/index.html')
def blogpost(request):
return render(request, 'blog/blogpost.html')
Showing:
404 not found page
you should include urls.py of your application to project urls.py
actually if your project name is "mysite" and your application name is "blogspot", you should include mysite/blogspot/urls.py on this file mysite/mysite/urls.py like this:
from django.urls import path, include
urlpatterns = [
path('', include('blogspot.urls')),
]
Actually, i forget to add the slash at the time of registering the url of this app in urls
please i need help, no matter how much i try, my site keep returning a
404 error due to fault in urls setup
my views
from django.shortcuts import get_object_or_404, render_to_response
from catalog.models import Category, Product
from django.template import RequestContext
from untitled13.cart import cart
from django.http import HttpResponseRedirect
from untitled13.catalog.forms import ProductAddToCartForm
def index(request, template_name='catalog/index.html'):
page_title = 'online shop for all items'
return render_to_response(template_name, locals(),
context_instance=RequestContext(request))
def show_category(request, category_slug, template_name='catalog/category.html'):
c = get_object_or_404(Category, slug=category_slug)
products = c.product_set.all()
page_title = c.name
meta_keywords = c.meta_keywords
meta_description = c.meta_description
return render_to_response(template_name, locals(),
context_instance=RequestContext(request))
def show_product(request, product_slug, template_name='catalog/product.html'):
p = get_object_or_404(Product, slug=product_slug)
categories = p.categories.filter(is_active=True)
page_title = p.name
meta_keywords = p.meta_keywords
meta_description = p.meta_description
if request.method == 'POST':
postdata = request.POST.copy()
form = ProductAddToCartForm(request, postdata)
if form.is_valid():
cart.add_to_cart()
if request.session.test_cookie_worked():
request.session.delete_test_cookie()
url = 'show_cart'
return HttpResponseRedirect(url)
else:
form = ProductAddToCartForm(request=request, label_suffix=':')
form.fields['product_slug'].widget.attrs['value'] = product_slug
request.session.set_test_cookie()
return render_to_response(template_name, locals(),
context_instance=RequestContext(request))
my urls
"""untitled13 URL Configuration
from django.contrib import admin
from django.urls import path, include
from django.views import static
urlpatterns = [
path('admin/', admin.site.urls),
path('catalog/', include('catalog.urls')),
path('static/', static.serve),
path('cart/', include('cart.urls')),
]
my cart view
from django.shortcuts import render_to_response
from django.template import RequestContext
from untitled13.cart import cart
def show_cart(request, template_name="cart/cart.html"):
cart_item_count = cart.get_cart_items(request)
page_title = 'Shopping Cart'
return render_to_response(template_name, locals(),
context_instanc=RequestContext(request))
the error page
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/site
Using the URLconf defined in untitled13.urls, Django tried these URL patterns, in this order:
admin/
catalog/
static/
cart/
The current path, site, 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.
You need to add path('site/', views.index) to your urlpatterns if you want '/site' to link to your index view. The error it gives you is really straight forward.
You would also need to import the views.py file containing the index view.
from your_app import views
I am trying to catch all URLs from the safer app and send them to a catch all view; for example:
http://127.0.0.1:8000/saferdb/123
http://127.0.0.1:8000/saferdb/12
I think I have an issue with my reg ex in url.py:
from django.conf.urls import url
from . import views
app_name = 'saferdb'
urlpatterns = [
url(r'^/$', views.index, name='index'),
url(r'^(?P<pk>[0-9]+)/$', views.detail, name='detail'),
]
Views.py is the sample code from the django tutorial:
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from .models import Question
def index(request):
latest_question_list = Question.objects.all()[:5]
output = ', '.join([q.DOT_Number for q in latest_question_list])
return HttpResponse(output)
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
I noticed that /saferdb/ will not work unless the reg ex contains a slash:
r'^/$' instead of r'^$' as shown in the django tutorial.
Please add '/' at the end of url in root urls.py of 'safer' app, something similar to this:
url(r'^saferdb/', include('saferdb.urls', namespace='saferdb'))