I need help with {% url (url to template) %} when i try to open another view i see a NoRewerseMatch error.
here is my html file:
{% load static %}
<head>
<link href='{% static "navbar_style.css" %}' rel="stylesheet", type="text/css">
</head>
<header>
<nav class="headlist">
--->
<ul>
<li>O nas</li>
<li>Kontakt</li>
<li><a>Zajęcia</a></li>
</ul>
</nav>
</header>
my app(pages)/urls.py
from django.contrib import admin
from django.urls import path
from . import views
app_name = 'pages'
urlpatterns = [
path('', views.home_view, name='home_view'),
path('index/', views.index_view, name='index_view'),
]
views.py
import...
# Create your views here.
def home_view(request):
listoftexts = Text.objects.order_by('-pub_date')
context = {
'listoftexts': listoftexts
}
return render(request, 'pages/home.html', context)
def index_view(request):
listoftexts = Text.objects.order_by('-pub_date')
context = {
'listoftexts': listoftexts
}
return render(request, 'pages/index.html', context)
You can do it like this.
The name of the view is home_view:
path('', views.home_view, name='home_view'),
so you can use the {% url … %} template tag [Django-doc] with:
<a href="{% url 'home_view' %}">
If you use an app_name in the urls.py, you also need to prefix this in the url:
<a href="{% url 'pages:home_view' %}">
The url_name should be home_view not home. The name parameter in the path function is what you use to refernce the view.
Related
My Django site is working fine locally. I am pushing it to my website but one of the links is not working and I can not for the life of me see why as similar things are working fine.
Here is my urls.py:
from . import views
app_name = 'sitepages'
urlpatterns = [
path('', views.greeting_page_def, name='greeting_page_html'),
path('home/', views.home_def, name='home_html'),
path('specs/', views.specs_def, name='specs_html'),
path('about/', views.about_def, name='about_name'),
path('faq/', views.faq_def, name='faq_name'),
path('howTos/', views.howTos_def, name='howTos_name'),
path('howTos/puller', views.howTosPuller_def, name='howTosPuller_name'),
path('howTos/conformer', views.howTosConformer_def, name='howTosConformer_name'),
path('howTos/general', views.howTosGeneral_def, name='howTosGeneral_name'),
path('howTos/submitter', views.howTosSubmitter_def, name='howTosSubmitter_name'),
]
And my views.py:
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
# Create your views here.
def greeting_page_def(request):
return render(request, 'sitepages/greeting_page_html.html')
def about_def(request):
return render(request, 'sitepages/about.html')
def faq_def(request):
return render(request, 'sitepages/faq.html')
def home_def(request):
return render(request, 'sitepages/home.html')
def specs_def(request):
return render(request, 'sitepages/specs.html')
def howTos_def(request):
return render(request, 'sitepages/howTos.html')
def howTosPuller_def(request):
return render(request, 'sitepages/howTosPuller.html')
def howTosConformer_def(request):
return render(request, 'sitepages/howTosConformer.html')
def howTosGeneral_def(request):
return render(request, 'sitepages/howTosGeneral.html')
def howTosSubmitter_def(request):
return render(request, 'sitepages/howTosSubmitter.html')
and the html template that has the links.
{% extends 'base.html' %}
{% block content %}
{% load static %}
<a class="link-primary" href="{% url 'sitepages:howTosPuller_name' %}"} >How Tos - Puller</a>
<a class="link-primary" href="{% url 'sitepages:howTosSubmitter_name' %}"} >How Tos - Submitter</a>
<a class="link-primary" href="{% url 'sitepages:howTosGeneral_name' %}"} >How Tos - General</a>
<a class="link-primary" href="{% url 'sitepages:howTosConformer_name' %}"} >How Tos - Conformer</a>
{% endblock %}
all the links here work except for
<a class="link-primary" href="{% url 'sitepages:howTosGeneral_name' %}"} >How Tos - General</a>
when I click that I get
NoReverseMatch at /sitepages/howTos/
Reverse for 'howTosGeneral_name' not found. 'howTosGeneral_name' is not a valid view function or pattern name.
the other thing is it works locally but not on my site and I am pushing it via git and it looks the same.
Where am I going wrong?
All links have extra } at the end before closing of opening anchor tag.
So, the template should be:
{% extends 'base.html' %}
{% block content %}
{% load static %}
<a class="link-primary" href="{% url 'sitepages:howTosPuller_name' %}">How Tos - Puller</a>
<a class="link-primary" href="{% url 'sitepages:howTosSubmitter_name' %}">How Tos - Submitter</a>
<a class="link-primary" href="{% url 'sitepages:howTosGeneral_name' %}">How Tos - General</a>
<a class="link-primary" href="{% url 'sitepages:howTosConformer_name' %}">How Tos - Conformer</a>
{% endblock %}
Note: Always add / at the end of every route, so:
Urls.py:
from . import views
app_name = 'sitepages'
urlpatterns = [
path('', views.greeting_page_def, name='greeting_page_html'),
path('home/', views.home_def, name='home_html'),
path('specs/', views.specs_def, name='specs_html'),
path('about/', views.about_def, name='about_name'),
path('faq/', views.faq_def, name='faq_name'),
path('howTos/', views.howTos_def, name='howTos_name'),
path('howTos/puller/', views.howTosPuller_def, name='howTosPuller_name'),
path('howTos/conformer/', views.howTosConformer_def, name='howTosConformer_name'),
path('howTos/general/', views.howTosGeneral_def, name='howTosGeneral_name'),
path('howTos/submitter/', views.howTosSubmitter_def, name='howTosSubmitter_name'),
]
when i run my code (its for a project) i get this error: "no such table: encyclopedia_article". The error appears to come from 9 line of views.py (obj = article.objects.get(id=1). here is the code:
views.py
from django.shortcuts import render
from django.http import HttpResponse
from . import util
import random
from .models import article
from .forms import ArticleForm
def index(request):
obj = article.objects.get(id=1) #THIS IS WHAT APPERS TO CAUSE THE ERROR
context = {
'object': obj
}
entries = util.list_entries()
random_page = random.choice(entries)
return render(request, "encyclopedia/index.html", {
"entries": util.list_entries(),
"random_page": random_page,
})
def CSS(request):
return render(request, "encyclopedia/css_tem.html", {
"article_css": "css is slug and cat"
})
def Python(request):
return render(request, "encyclopedia/python_tem.html", {
"article_python": "python says repost if scav"
})
def HTML(request):
return render(request, "encyclopedia/HTML_tem.html", {
"article_HTML": "game theory: scavs are future humans"
})
def Git(request):
return render(request, "encyclopedia/Git_tem.html", {
"article_Git": "github is git"
})
def Django(request):
return render(request, "encyclopedia/Django_tem.html", {
"article_Django": "this is a framework"
})
def new_article(request):
form = ArticleForm(request.POST or None)
if form.is_valid():
form.save()
context = {
'form': form
}
return render(request, "encyclopedia/new_article_tem.html", context)
models.py:
class article(models.Model):
title = models.CharField(max_length = 120)
description = models.TextField(blank=True, null = False)
forms.py:
from django import forms
from .models import article
class ArticleForm(forms.ModelForm):
class Meta:
model = article
fields = [
'title',
'description'
]
urls:
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("", views.CSS, name="CSS"),
path("", views.Python, name="Python"),
path("", views.HTML, name="HTML"),
path("", views.Git, name="Git"),
path("", views.Django, name="Django"),
path("", views.new_article, name="new_article")
]
second urls (in other directory (there is encyclopedia and wiki this one is in wiki the last one in encyclopedia)):
"""wiki URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path
from encyclopedia import views
from encyclopedia.views import index
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("encyclopedia.urls")),
path('CSS/', views.CSS, name="CSS"),
path('Python/', views.Python, name="Python"),
path('HTML/', views.HTML, name="HTML"),
path('Git/', views.Git, name="Git"),
path('Django/', views.Django, name="Django"),
path('new_article/', views.new_article, name="new_article"),
path('main/', index)
]
new_article_tem.html:
{% extends "encyclopedia/layout.html" %}
{% block title %}
New Article
{% endblock %}
{% block body %}
<h1>Create Article</h1>
<form method = 'POST' action = "{% url 'index' %}"> {% csrf_token %}
<input type = 'submit' value='Save'>
</form>
{% endblock %}
IM NOT SURE IF THIS ONES ARE USEFULL BUT STILL IM PUTTING ALMOST EVERYTHING:
index.html:
{% extends "encyclopedia/layout.html" %}
{% block title %}
Encyclopedia
{% endblock %}
{% block body %}
<h1 id="demo" onclick="add_article()">Add article</h1>
<ul>
{% for entry in entries %}
<li><a href = /{{entry}}>{{ entry }}</a></li>
{% endfor %}
{% for article_title in created_articles %}
<li>{{article_title}}</li>
{% endfor %}
<li>{{title}}</li>
</ul>
{% endblock %}
layout.html:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet">
</head>
<body>
<div class="row">
<div class="sidebar col-lg-2 col-md-3">
<h2>Wiki</h2>
<form>
<input class="search" type="text" name="q" placeholder="Search Encyclopedia">
</form>
<div>
Home
</div>
<div>
<a href = "/new_article" >Create New Article</a>
</div>
<div>
Random Page
</div>
{% block nav %}
{% endblock %}
</div>
<div class="main col-lg-10 col-md-9">
{% block body %}
{% endblock %}
</div>
</div>
</body>
</html>
Try to use this :-
python manage.py makemigrations
and then
python manage.py migrate
I'm learning to make some chat website, and i cannot quite get how to use urls correctly. The problem is that when I get to "http://127.0.0.1:8000/chat", links into the header became like "http://127.0.0.1:8000/chat/main" instead of "http://127.0.0.1:8000/main"
project urls:
from django.contrib import admin
from django.urls import path
from django.urls import include, path
from chat import views as chat_views
from mainapp import views as mainapp_views
urlpatterns = [
path('admin/', admin.site.urls),
path('', mainapp_views.index),
path('chat/', include('chat.urls')),
]
chat app urls:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('<str:room_name>/', views.room, name='room'),
]
chat app views:
from django.shortcuts import render
def index(request):
return render(request, 'chat/chatindex.html')
def room(request, room_name):
return render(request, 'chat/room.html', {
'room_name': room_name
})
index.html
<!DOCTYPE html>
{% load static %}
<html>
<head>
<meta charset="utf-8"/>
<link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"/>
<title>{% block title %}{% endblock title %}</title>
</head>
<body>
<header>
<div class="navbar navbar-dark bg-dark shadow-sm">
Главная
Поиск собеседников
Контакты
FAQ
Регистрация/Вход
</div>
</div>
</header>
<main>
<div>{% block content%}{% endblock content %}</div>
</main>
<footer class="footer mt-auto py-3 bg-light">
<div class="container">
<span class="text-muted">Давай общаться!</span>
</div>
</footer>
</body>
</html>
chatindex.html
{% extends "index.html" %}
{% block title %}Контакты{% endblock title %}
{% block header %}{% endblock header %}
{% block content %}
В какую комнату хотите зайти?
<br>
<input id="room-name-input" type="text" size="100">
<br>
<input id="room-name-submit" type="button" value="Enter">
<script>
document.querySelector('#room-name-input').focus();
document.querySelector('#room-name-input').onkeyup = function(e) {
if (e.keyCode === 13) { // enter, return
document.querySelector('#room-name-submit').click();
}
};
document.querySelector('#room-name-submit').onclick = function(e) {
var roomName = document.querySelector('#room-name-input').value;
window.location.pathname = '/chat/' + roomName + '/';
};
</script>
{% endblock content%}
I'm pretty sure that the problem is about "path('<str:room_name>/', views.room, name='room')", but i can't understand how to fix it and save opportunity to enter rooms with chat-page.
Thanks a lot!
Very likely you make relative paths. Indeed, if you visit a page like some.domain.com/foo, and the link is link, then it will visit some.domain.com/foo/bar, since that is a relative path: relative to the current path.
You can solve this by specifying an absolute path, which has a leading slash, so:
<!-- ↓ leading slash -->
FAQ
But it is better not to generate URLs manually. If you later for example change the URL paths, you will need to alter all URLs. You can give your views a name, like:
path('faq', views.faq, name='faq')
and in the template work with the {% url … %} template tag [Django-doc]:
<!-- ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ url template tag -->
FAQ
Django will then look for a view with the given name, and automatically generate the corresponding URL.
I'm trying to select a random page with Django but I don't know how to call the function.
I tried to call it with an URL but it didn't work.
views.py:
def random_page(request):
entries = util.list_entries() # list of wikis
selected_page = random.choice(entries)
return render(request, "encyclopedia/layout.html", {
"random_page": selected_page
})
urls.py:
from . import views
app_name = "encyclopedia"
urlpatterns = [
path("", views.index, name="index"),
path("wiki/<str:page_title>", views.wiki_page, name="wiki_page"),
path("create", views.add_entry, name="add_entry"),
path("search", views.search, name="search"),
path("wiki/edit/<str:page_title>", views.edit_page, name="edit_page")
]
layout.html:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet">
</head>
<body>
<h2>Wiki</h2>
<form action="{% url 'encyclopedia:search' %}" method="POST">
{% csrf_token %}
<input class="search" type="text" name="q" placeholder="Search Encyclopedia">
</form>
Home
Create New Page
<a href=wiki/{{ random_page }}>Random Page</a>
{% block body %}
{% endblock %}
</body>
</html>
Why not redirect to a given page. You thus redirect the browser to a page with a given page title. The advantage is that you make it simpler and only have to write the redirect logic once.
from django.shortcuts import redirect
def random_page(request):
entries = util.list_entries() # list of wikis
selected_page = random.choice(entries)
return redirect('encyclopedia:wiki_page', page_title=selected_page)
You then specify a path in your urls.py:
urlpatterns = [
path("", views.index, name="index"),
path("random/", views.random_page, name="index"),
path("wiki/<str:page_title>", views.wiki_page, name="wiki_page"),
path("create", views.add_entry, name="add_entry"),
path("search", views.search, name="search"),
path("wiki/edit/<str:page_title>", views.edit_page, name="edit_page")
]
If you then visit /random it will redirect to a random page.
I wrote the view in this way
def random_page(request):
entries = util.list_entries()
selected_page = random.choice(entries)
return HttpResponseRedirect(reverse('wiki', args=[selected_page]))
If i have a url that is "someurl/report/1/" where "report" is an app and "1" corresponds to a certain id of a model in my SQL database, how would i substitute the variables in the template with that specific models data?
In my case I am writing a website that displays a surf report for different beaches. I have set it up so each SQL model id corresponds to a different beach. So if I wanted to use the data of beach "3" in the template, how would i display those in the html template?
TRACEBACK
Using the URLconf defined in surfsite.urls, Django tried these URL patterns, in this order:
^admin/
^report/ ^$ [name='index']
^report/ (?P[0-9]+)$ [name='get_report']
The current URL, report/1/, didn't match any of these.
#URLS.PY
from django.conf.urls import url
from django.conf.urls.static import static
from . import views
urlpatterns = [
# /index/
url(r'^$', views.index, name='index'),
# /report/
url(r'(?P<beach_id>[0-9]+)$', views.get_report, name='get_report'),
]
#MY TEMPLATE
<!DOCTYPE html>
<html>
{% load staticfiles %}
<link rel="stylesheet" type="text/css"
href="{% static 'report/css/style.css' %}"/>
<link href="https://fonts.googleapis.com/css?family=Biryani:300,400,800"
rel="stylesheet"/>
<head>
<title>REALSURF</title>
</head>
<body>
<h1>
<form id="search">
<input id="search" type="text">
</form>
</h1>
<div class="container">
<div class="column">
<div class="text">Wind</div>
<div class="number">{{Break.wind}}</div>
</div>
<div class="column">
<div class="text">Wave Height</div>
<div class="number">{{Break.low}}-{{Break.high}}</div>
</div>
<div class="column">
<div class="text">Tide</div>
<div class="number">{{Break.tide}}</div>
</div>
</div>
<h2>
REALSURF
</h2>
<h3>
A simple site by David Owens
</h3>
</body>
</html>
#MY MODEL
from __future__ import unicode_literals
from django.db import models
class Beach(models.Model):
name = models.CharField(max_length=50)
high = models.SmallIntegerField()
low = models.SmallIntegerField()
wind = models.SmallIntegerField()
tide = models.DecimalField(max_digits=3, decimal_places=2)
def __str__(self):
return self.name
#MY VIEWS
from django.http import Http404
from django.shortcuts import render
from .models import Beach
def index(request):
allBeaches = Beach.objects.all()
context = {
'allBeaches': allBeaches,
}
return render(request, 'report/index.html', context)
def get_report(request, id):
try:
beach = Beach.objects.get(id=id)
except Beach.DoesNotExist:
raise Htpp404("404")
return render(request, 'report/index.html', {'beach': beach})
If i understand you right, you want to create view, that render beach separately
You can do something like this, your view:
def get_beach(request, id)
beach = Beach.objects.get(id=id)
return render(request, 'path/to/your/template', {'beach':beach})
urls:
url(r'^someurl/report/(?P<id>[0-9]+)$', views.get_beach(), name='get_beach'),
template url to this page:
beach
Edited
Its your view, as i understand, this is detail view, but select all objects(Break.objects.all())
def detail(request, break_id):
try:
allBreaks = Break.objects.all()
except Break.DoesNotExist:
raise Http404("404")
return render(request, 'report/index.html', {'allBreaks': allBreaks})
so you have to change this on this:
def detail(request, break_id):
try:
break_detail = Break.objects.get(id=break_id)
return render(request, 'path/to/your/template', {'break_detail':break_detail})
except Break.DoesNotExist:
raise Http404("404")
then your url should look like this:
url(r'^someurl/report/(?P<break_id>[0-9]+)$', views.detail(), name='detail'),
or you can use get_object_or_404:
def detail(request, break_id):
break_detail = get_object_or_404(Break, id=break_id)
return render(request, 'path/to/your/template', {'break_detail':break_detail})
Url is the same.
So if you want to access to wind field, you just write this tempalte tag {{break_detail.wind}}
UPD2
change place from this
^admin/
^report/ ^$ [name='index']
^report/ (?P<beach_id>[0-9]+)$ [name='get_report']
to this:
^admin/
^report/(?P<beach_id>[0-9]+)$ [name='get_report']
^report/^$ [name='index']
and delete spaces in urls after report/