How to go from one page to another in django - django

I'm new to Django and python (infact my first language which I've only been learning for 3 months)
I'm creating this website using Django and I'm not able to go from one page to another using the href tag. it throws at me a 404 error saying "current path didn't match any of these"
This is my code
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .models import off
# Create your views here.
def homepage(request):
return render(request=request,
template_name='main/home.html',
context={'toll' : off.objects.all})
def secondpage(request):
return render(request = request,
template_name = 'main/next.html')
main/urls.py
from django.urls import path
from . import views
app_name = 'main'
urlpatterns = [
path('',views.homepage,name='homepage'),
path('',views.secondpage,name='secondpage')
]
templates/mains/home.html
<div class="topnav">
Link
Link
Link
</div>
I also request the helper to simply it for me as I wouldn't be able to handle complex and advanced python terminology
Thanks In Advance From a Friend
Arvind

I think you should read this to start with Django.

Related

Page not found (404) on django

I am using django 3.2 to build a personal e-commerce project, Got Error-Page not found (404) on visiting my products page url Method:GET URL:http://127.0.0.1:8000/products Using the URLconf defined in main.urls. I have followed all the conventions and the other pages are all working but this one is giving me a[urls[\views][1][browser display] hard time as i feel everything is correct, i might be wrong, pls help and if u need to see more of my code, please let me know.
This is my code for urls
from django.urls import path
from django.views.generic.detail import DetailView
from django.views.generic import *
from main import models, views
app_name = 'main'
urlpatterns = [
path('', views.home, name='home'),
path('about_us/', views.about_us, name='about_us'),
path('contact-us/', views.ContactUsView.as_view(), name='contact_us'),
path(
"products/<slug:tag>/",
views.ProductListView.as_view(),
name="products"
),
path("product/<slug:slug>/", DetailView.as_view(model=models.Product), name='product'),
]
my code for views
from django.views.generic.edit import FormView
from .forms import ContactForm
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.shortcuts import get_object_or_404
from main import models
class ProductListView(ListView):
template_name = "main/product_list.html"
paginate_by = 4
def get_queryset(self):
tag = self.kwargs['tag']
self.tag = None
if tag != "all":
self.tag = get_object_or_404(
models.ProductTag, slug=tag
)
if self.tag:
products = models.Product.objects.active().filter(
tags=self.tag
)
else:
products = models.Product.objects.active()
return products.order_by("name")
then my browser
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/products
Using the URLconf defined in booktime.urls, Django tried these URL patterns, in this order:
admin/
[name='home']
about_us/ [name='about_us']
contact-us/ [name='contact_us']
products/<slug:tag>/ [name='products']
product/<slug:slug>/ [name='product']
^media/(?P<path>.*)$
The current path, products, didn’t match any of these.
You have to create a path to url ending with "products/". You create url just to sent with parameter "tags". "products/slug:tag/"
So, add 'products/' to your urls path the url below and you'll access with 'http://127.0.0.1:8000/products/'
path(
"products/",
views.ProductListView.as_view(),
name="products"
)

Generate Django sitemap while using site framework

I am using sites framework with RequestSite (no SITE_ID set) to generate content based on domain. I need to generate sitemaps for each domain with different results but I didnt find a way how to make this two frameworks work together. Is there any way to get Site of the current request in Sitemap? (getting it from SITE_ID config is not an option for me).
Here is an example of what I would like to do:
from django.contrib.sitemaps import Sitemap
from blog.models import Entry
class BlogSitemap(Sitemap):
def items(self, request):
return Entry.objects.filter(is_draft=False, site=request.site)
But its not possible because there is no request in items(). Is there any other way how to filter items in sitemap based on site?
Try following example:
from django.contrib.sitemaps import Sitemap
from django.contrib.sitemaps.views import sitemap
from blog.models import Entry
class BlogSitemap(Sitemap):
_cached_site = None
def items(self):
return Entry.objects.filter(is_draft=False, site=self._cached_site)
def get_urls(self, page=1, site=None, protocol=None):
self._cached_site = site
return super(BlogSitemap, self).get_urls(page=page, site=site, protocol=protocol)
And in urls.py
urlpatterns = [
url('sitemap.xml', sitemap, {
'sitemaps': {'blog': BlogSitemap}
}, name='django.contrib.sitemaps.views.sitemap'),
# ...
# other your urls
]
This should work now. Let me know if you'll have any questions.

Can I print just the content of a html template in django?

I am using Django with python to create a web application, I am a beginner in this. I hope that you can help me.
I want to print this page by clicking a button.
Now, I am just trying to generate the pdf first.
I want just to print the content, like that
I tried these functions.
#views.py
from django.views.generic.detail import DetailView
from MagasinProject.views import PdfMixin
from MagasinProject.utils import generate_pdf, render_to_pdf_response, pdf_decorator
from django.contrib.auth.models import User
from django.shortcuts import render
def test_view(request):
resp = HttpResponse(content_type='application/pdf')
result = generate_pdf('demande/demande.html', file_object=resp)
return result
#urls.py
from django.urls import path
from . import views
from django.conf.urls import url
urlpatterns=[
path('demande',views.index, name='demande'),
url(r'^test_view$', views.test_view),
]
This is what I got
You can print the HTML page with a print button like this (see w3schools):
<button onclick="window.print()">Print this page</button>

How to add Django statements to Javascript

I'm trying to implement some JS code in django so anytime i click a button, it returns the current year.. how do i do this
I've tried using some JS events handler in my django based templates
from datetime import datetime
from django.template import Template, Context
from django.http import HttpResponse as toHTML
cont = Context({'dat':datetime.now()})
def say_year(request):
htm = Template("<button onclick='alert({dat})'>click me</button>")
htm = htm.render(cont)
return toHTML(htm)
i'm expecting an alert box showing full datetime.now() methods
I prefer that you do it that way in order to have full control over the template.
1 - make the views.py that way :
from datetime import datetime
from django.template import Template, Context
from django.shortcuts import render
def say_year(request):
context = {
'dat': datetime.now()
}
return render(request, 'mytemplate.html', context)
2- The urls.py should look that way :
from django.contrib import admin
from django.urls import path
from your_app import views
urlpatterns = [
path('admin/', admin.site.urls),
path('my_template/', views.say_year )
]
3- You create a templates folder in the root directory of your project where all your templates will live.
For your question i have create my_template.html and it should be that way :
<button onclick="alert('{{dat}}')">click me</button>
If you have more questions please let me know.

Could not parse the remainder: '-save' from 'waypoints-save'

I am trying a simple app in geodjango by following http://invisibleroads.com/tutorials/geodjango-googlemaps-build.html.
My view function is
# Import django modules
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template.loader import render_to_string
# Import system modules
import json
# Import custom modules
from waypoints.models import Waypoint
def save(request):
'Save waypoints'
for waypointString in request.POST.get('waypointsPayload', '').splitlines():
waypointID, waypointX, waypointY = waypointString.split()
waypoint = Waypoint.objects.get(id=int(waypointID))
waypoint.geometry.set_x(float(waypointX))
waypoint.geometry.set_y(float(waypointY))
waypoint.save()
return HttpResponse(simplejson.dumps(dict(isOk=1)), mimetype='application/json')
And urls.py is
from django.conf.urls import patterns, include, url
urlpatterns = patterns('waypoints.views',
url(r'^$', 'index', name='waypoints-index'),
url(r'^save$', 'save', name='waypoints-save'),
)
It is showing an error http://dpaste.com/3EJVX0G
Template index.html is here http://pastebin.com/125Dm6Bz
Please help me.I am new to django.
The parameter to the {% url %} tag must always be in quotes if it's a literal string (this has been the case since version 1.5, which is quite a long time).
The one that's causing the error is this:
$.post("{% url waypoints-save %}"
which should be:
$.post("{% url "waypoints-save" %}"
but you make the same mistake several times in that template.