Change URL paramaters parameters in request by id - python

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})

Related

Django return home page in get absolute url

My PostCreateView
class PostCreateView(CreateView):
model = Posts
template_name = "blog/post_form.html"
fields = ["author", "title", "content"]
My urls
urlpatterns = [
path('', views.home, name='blog-home'),
path('about/', views.about, name='blog-about'),
path("post/new/", PostCreateView.as_view(), name="post-create"),
]
Once I do a post my site crashes since I need to specify a get_absolute_url. I just want to return to the home page but trying
redirect("") fails with error
NoReverseMatch at /post/new/
Reverse for '' not found. '' is not a valid view function or pattern name.
How can I return to the homepage ?
You need to redirect to the view with the given name, so:
redirect('blog-home') # since name='blog-home'
or if you work with a class-based view which has a FormMixin like a CreateView, UpdateView, etc. you reverse with:
from django.urls import reverse
class PostCreateView(CreateView):
# …
def get_success_url(self):
return reverse('blog-home')

Django views rendering just one page and wont render the rest

So im using django 1.8 on macosx and i have problem while configuring html, namely when i try to load another page except one that is set at default one(index is the default one), it just refreshes the default one i have set in urls.py and i cant access any other page except that one but in the url bar i can see that im accesing the proper html file because it says so but the page is not changing....heres my code:
app/urls.py-----------
urlpatterns = [
url(r'^contact/', views.contact, name='contact'),
url(r'^projects/', views.projects, name='projects'),
url(r'^services/', views.services, name='services'),
url(r'^', views.index, name='index'),
url(r'^about/', views.about, name='about'),
these are all the pages im trying to install
main urls.py-------------
from app import views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^',include('app.urls')),
]
and this is my views.py-----------
def contact(request):
return render(request, 'app/template/contact.html',{})
def about(request):
return render(request, 'app/template/about.html',{})
def projects(request):
return render(request, 'app/template/projects.html',{})
def services(request):
return render(request, 'app/template/services.html',{})
def index(request):
return render(request, "app/template/index.html",{})
https://docs.djangoproject.com/en/1.8/intro/tutorial03/
you need $ to end the string. In your case he link all thats starts with all.
url(r'^$', views.index, name='index'),
you views.py:
def contact(request):
return render(request, 'app/contact.html',{})
def about(request):
return render(request, 'app/about.html',{})
def projects(request):
return render(request, 'app/projects.html',{})
def services(request):
return render(request, 'app/services.html',{})
def index(request):
return render(request, "app/index.html",{})

Django 2.1 urls returning error

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

Fixing this "Page not found (404)" error

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.

Django - urls.py and views.py and resolving error 404

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'))
]

Categories

Resources