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.
Related
I want to make urls with GET url pattern
example.com/blog/?id=1
my current code
views.py
def home(request,blog_uuid):
blogs = Blog.objects.get(pk=blog_uuid)
return render(request,'home.html',{'blogs':blogs})
url pattern
path('blog/<blog_uuid>/',views.home,name='Blog'),
my current url now like this example.com/blog/1
Change your url pattern to,
urlpatterns = [
path('blog/', views.home, name='Blog'),
...,
]
thrn change your view as
from django.shortcuts import get_object_or_404
def home(request):
blog_uuid = int(request.GET.get("id", "-1"))
blog = get_object_or_404(Blog, pk=blog_uuid)
return render(request, 'home.html', {'blogs': blog})
i have a redirect url problem when the user complete editing his profile informations ,i want to redirect to the profile page , but it display to me 404 error
this is My view.py file :
def ProfileView(request, pk=None):
prof = Profile.objects.all()
if pk:
pr = User.objects.get(pk=pk)
else:
pr = request.user
context= {
'pro':prof,
'profile':pr
}
return render(request,'profile.html',context)
def update_profile(request,id):
profile = get_object_or_404(Profile,id=id)
form = ProfileForm(request.POST or None ,request.FILES or None,instance=profile)
if request.method=='POST':
if form.is_valid:
form.save()
return redirect(reverse('profile-detail'))
context = {
'form':form
}
return render(request,'profile_update.html',context)
thi is my url.py file :
urlpatterns = [
path('admin/', admin.site.urls),
path ('',index),
path ('events_details/<id>',events_details,name="events_details"),
path ('evenements/',evenements,name="events"),
path ('projets/',projets,name="project"),
path ('project_detail/<id>/',project_detail,name="project-detail"),
path ('create_post',create_post,name="create_post"),
path ('project_detail/<id>/update_post',update_post,name="update_post"),
path ('project_detail/<id>/delete_post',delete_post,name="delete_post"),
#------------------------------------------------------------
path ('profile/',ProfileView,name="profile-detail"),
path ('profile_update/<id>',update_profile,name="profile-update"),
path('tinymce/', include('tinymce.urls')),
path('accounts/', include('allauth.urls')),
path('api-auth/', include('rest_framework.urls'))
]
The Error i got :
Request Method: POST
Request URL: http://127.0.0.1:8000/profile_update/
.
.
.
The current path, profile_update/, didn't match any of these.
The problem is that your url expects an id with the url (ie localhost:8000/profile_update/12), but when you are making a post request, you are not sending one.
So I am guessing you need to update the code like this:
def update_profile(request,id):
profile = get_object_or_404(Profile,id=id)
form = ProfileForm(request.POST or None ,request.FILES or None,instance=profile)
if request.method=='POST':
if form.is_valid:
form.save()
return redirect(reverse('profile-detail'))
context = {
'form':form,
'pk': id
}
return render(request,'profile_update.html',context)
And update the template as well:
<form name="form" method="post" action="{% url 'profile-update' pk %}">
Try changing the redirect line from
return redirect(reverse('profile-detail'))
to
return redirect('app-name:profile-detail')
where app-name is the name of your django app.
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 have this fragment of code in Flask
#app.route('/search', methods = ['POST'])
def search():
if request.method == 'POST':
results_arr = []
img_path = request.form.get('img')
How to make this in Django or where I can read about it?
The route in the flask fragment will be put up in the urls.py with an entry which might look as follows
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index , name='index'),
url(r'^search/$', views.search, name='search'),
]
and in the views.py you'll have a function which will look as follows assuming the corresponding HTML form has enctype multipart/form-data and the html is a file upload.
<input type="file" name="myimage">
The corresponding function assuming you've set the MEDIA_URL and MEDIA_ROOT in the settings can be translated as:
from django.shortcuts import render
from django.conf import settings
from django.core.files.storage import FileSystemStorage
def search(request):
if request.method == 'POST' and request.FILES['myimage']:
results_arr = []
imagefile = request.FILES['myimage']
fs = FileSystemStorage()
filename = fs.save(imagefile.name, imagefile)
file_url = fs.url(filename)
return render(request, 'templateToRender.html', { 'filepath': file_url }) # in case you want to show the user the URL of the upload.
You could also use forms.py an example is provided in their documentation here
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'),
]