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
Related
I am newbie Django dev, I have a bit problem about urls config. I want to make url http://localhost:8000/user-auth/register/
In my project, there is user_auth app with below urls:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^register$', views.register),
]
In register this url within urls in my site:
from django.conf.urls import include, url
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^polls/', include('polls.urls')),
url(r'^user-auth/', include('user_auth.urls')),
]
In my view user_auth/views.py:
from django.shortcuts import render
from django.http import HttpResponse
from .forms import RegisterForm
def register(request):
if request.method == 'POST':
response = HttpResponse()
response.write("<h1>Thanks for registering</h1></br>")
response.write("Your username:" + request.POST['username'])
response.write("Your email" + request.POST['email'])
return response
registerForm = RegisterForm()
return render(request, 'user_auth/register.html', {'form':registerForm})
In my user_auth/forms.py
from django import forms
class RegisterForm(forms.Form):
username = forms.CharField(label='Username', max_length=100)
password = forms.CharField(widget=forms.PasswordInput)
email = forms.EmailField(label='Email')
When I access to the link http://localhost:8000/user-auth/register/, the console announce "Not Found: /user-auth/register/". I dont know reason why and where. Could you please help me on this problem?. Tks
I am attempting to access a page in my application but I keep getting this error :
Page not found (404) Request Method: GET Request
URL: http://127.0.0.1:8000/nesting/Identity-nest/%7B%25%20url%20'nesting:Symptoms_nest_list'%7D
Using the URLconf defined in Identity.urls, Django tried these URL
patterns, in this order:
^admin/ ^Identity/
^nesting/ ^$[name='nesting']
^nesting/ ^Identity-nest/$[name='Identity_nest_list']
^nesting/ ^Symptoms-document/$[name='Symptoms_nest_list']
^$ [name='login_redirect']
The current URL, nesting/Identity-nest/{% url
'nesting:Symptoms_nest_list'}, didn't match any of these.
This is my main urls.py
from django.conf.urls import url, include
from django.contrib import admin
from Identity import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^Identity/', include('Identities.urls', namespace = 'Identities')),
url(r'^nesting/', include('nesting.urls', namespace = 'nesting')),
url(r'^$', views.login_redirect, name = 'login_redirect'),
]
This is my nesting urls.py
from django.conf.urls import url
from nesting.views import Identity_view, Identity_nest_list_view, Symptoms_document_view
from . import views
urlpatterns = [
url(r'^$', Identity_view.as_view(), name = 'nesting'),
url(r'^Identity-nest/$', Identity_nest_list_view.as_view(), name = 'Identity_nest_list'),
url(r'^Symptoms-document/$', Symptoms_document_view.as_view(), name = 'Symptoms_nest_list')
]
This is my views.py
class Symptoms_document_view(TemplateView):
model = Symptoms
template_name = 'nesting/Symptoms_list.html'
def get(self, request):
form = Symptom_Form()
Symptoms_desc = Symptoms.objects.all()
var = {'form':form, 'Symptoms_desc':Symptoms_desc}
return render(request, self.template_name, var)
def post(self, request):
form = Symptom_Form(request.POST or None)
Symptom_content = None
if form.is_valid():
Symptoms_description = form.save(commit = False)
Symptoms_description.user = request.user
Symptoms_description.save()
Symptoms_content = form.cleaned_data['Symptoms_description']
form = Symptom_Form()
redirect('nesting:nesting')
var = {'form': form, 'Symptoms_content': Symptoms_content}
return render(request, self.template_name, var)
This is the line in the HTML template that is the link the Symptoms_document_view view
<li class = "list-group-item"><a class = "nav-link" href="{%url 'nesting:Symptoms_nest_list'%}">{{Identity.First_Name}} {{Identity.Last_Name}} </a> <p>NIS: {{ Identity.NIS }}</p></li>
You need spaces around the url tag in your template:
href="{% url 'nesting:Symptoms_nest_list' %}">
Django's template parser is pretty basic and won't recognise a tag without the spaces.
Page not found (404)
Request Method: POST
Request URL: http://127.0.0.1:8000/accounts/register/accounts/register
views.py :
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from custom_user.forms import CustomUserCreationForm
from django.contrib import auth
from django.http import HttpResponseRedirect
#Create your views here
def home(request):
return render(request, "home.html")
def login(request):
c = {}
c.update(csrf(request))
return render(request, "login.html", c)
def about(request):
context = locals()
template = 'about.html'
return render(request,template,context)
#login_required
def userProfile(request):
user = request.user
context = {'user': user}
template = 'profile.html'
return render(request,template,context)
def auth_view(request):
username = request.POST.get['username', '']
password = request.POST.get['password', '']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return HTTpResponseRedirect('account/login')
else:
return HTTpResponseRedirect('account/login')
def register(request):
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect ('accounts/register_success.html')
else:
form = CustomUserCreationForm()
args = {'form': form}
return render(request, 'accounts/register.html', args)
def register_success(request):
return render(request, 'accounts/register_success.html')
def logout(request):
auth.logout(request)
return render(request, 'logout.html')
when i try to register a new user this error is raised . i manage to create my own custom registration form. i still cannot register any new user . is this error means that my registration form is not authenticate ? can someone explain why i get this error please ? im confused . help me please :(
urls.py :
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url, include
from django.contrib import admin
from profiles import views as profiles_views
from contact import views as contact_views
from checkout import views as checkout_views
from register import views as register_views
urlpatterns = [
url(r'^admin/',include(admin.site.urls)),
url(r'^$', profiles_views.home, name='home'),
url(r'^profile/$', profiles_views.userProfile, name='profile'),
url(r'^about/$', profiles_views.about, name='about'),
url(r'^checkout/$', checkout_views.checkout, name='checkout'),
url(r'^contact/$', contact_views.contact, name='contact'),
url(r'^accounts/register/$', register_views.register, name='register'),
url(r'^accounts/register_success/$', register_views.register_success, name='register_success'),
url(r'^accounts/', include('allauth.urls')),
url(r'^auth/', include('django.contrib.auth.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root= settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT)
Form.valid() should be inside the post indentation
So, I'm trying to create a table filled with contacts in Python/Django. When I attempt to run the program, I get the above error message ("ImportError: Could not import 'edit_contact'. The path must be fully qualified.")
Here is the views.py I'm using:
from contacts.models import Contact
#, Address, Telephone
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404, render
from django.template import Context, loader
from django.forms.models import inlineformset_factory
from django.template import loader, Context, RequestContext
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
# Create your views here.
def index(request):
#return HttpResponse("Hey! You can see contacts here!")
contact_list = Contact.objects.all().order_by('last_name')
return render_to_response('contacts/index.html', {'contact_list': contact_list},
RequestContext(request))
def detail(request, contact_id):
c = get_object_or_404(Contact, pk=contact_id);
def new_contact(request):
print "new_contact"
#AddressInlineFormSet = inlineformset_factory(Contact,
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
contact = form.save()
return HttpResponseRedirect(reverse('contacts.views.detail', args=(contact.pk,)))
else:
form = ContactForm()
return render_to_response("contacts/form.html",{
"form": form,
}, RequestContext(request))
def edit_contact(request, contact_id):
contact = Contact.objects.get(pk=contact_id)
if request.method == "POST":
form = ContactForm(request.POST, instane=contact)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('contacts.views.detail', args=(contact.pk,)))
else:
form = ContactForm(instance = contact)
return render_to_response("contacts/form.html", {
"form": form,
}, RequestContext(request))
This is the urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<contact_id>\d+)/$', 'detail', name='contactdetailsurl'),
url(r'^new/$', 'new_contact', name='newcontacturl'),
url(r'^(?P<contact_id>\d+)/edit/$','edit_contact', name='editcontacturl'),
]
And the error is pointing to this line in my site_base.html file:
<li id="tab_first"><a href="
{% url contacts.views.index %}
"><i class="icon-book"></i> Contacts</a></li>
Let me know if you need any more info. Thanks!
The error is telling you that you should use the full path to the view, for example 'contacts.views.edit_contact' (assuming the app is called contacts).
However, using strings in your URL patterns is deprecated in Django 1.8, and not supported in Django 1.10+. You should using callables instead. You are already using the callable views.index for your index URL pattern.
I would convert the rest of your URL patterns as follows:
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<contact_id>\d+)/$', views.detail, name='contactdetailsurl'),
url(r'^new/$', views.new_contact, name='newcontacturl'),
url(r'^(?P<contact_id>\d+)/edit/$', views.edit_contact, name='editcontacturl'),
]
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'))
]