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]))
Related
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 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.
Hello Stackoverflow community,
I am having trouble with my form not rendering in Django.
Here's my attempt to render an empty form in views.py.
class SearchSite(forms.Form):
query = forms.CharField(label="New Item",
help_text="Search for any article located on the site.")
def search(request):
form = SearchSite()
context = {
"form": form,
"query_matches": query_matches
}
response = render(request, "encyclopedia/layout.html", context)
return response
Here's what my urls.py file looks like:
urlpatterns = [
path("", views.index, name="index"),
path("wiki/<str:page_title>", views.page, name="wiki"),
path("wiki/", views.search, name="site_search")
]
My layout.html file:
{% 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 action="{% url 'site_search' %}" method="get">
{% csrf_token %}
There should be something here
{{ form }}
<input type="submit">
</form>
<div>
Home
</div>
<div>
Create New Page
</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>
I have noticed two particular problems in above screenshot. Firstly, my form does not render when inside my index.html webpage, which extends layout.html. Secondly, when I click the submit button, I get routed to a webpage that has my CSRF token in the url ... and then finally renders my form.
How can I fix this? Thanks everyone.
I have noticed two particular problems in above screenshot. Firstly,
my form does not render when inside my index.html webpage, which
extends layout.html.
Yes. You aren't passing form to index.html. Pass that in the view which renders the homepage. Even if it extends from layout.html, you need to pass it in the context for it to work.
def index(request):
# Your code.
return render(request, 'index.html', {'form': SearchSite()})
Secondly, when I click the submit button, I get routed to a webpage
that has my CSRF token in the url ... and then finally renders my
form.
That's because, in index.html, there is a blank form with a csrf_token, with an action set to /wiki, which calls search when the submit button is pressed. And search gives you layout.html, with the form, and as the form method is GET, it shows it in the url. I suggest changing it to POST if there is confidential data (and even otherwise. Why is there a csrf_token if it is not a POST request? Not needed. If you really want a GET request, then remove the csrf_token).
Here's my solution to the problem I had earlier for any future people visiting the post.
I wrote a form called SearchSite and defined a view called search in my views.py.
class SearchSite(forms.Form):
query = forms.CharField(
help_text="Search for any article located on the site.")
def search(request):
form = SearchSite()
is_substring_of_queries = []
if request.method == "GET":
form = SearchSite(request.GET)
if form.is_valid():
for entry in util.list_entries():
existsIdenticalResult = form.cleaned_data["query"].casefold() == entry.casefold()
existsResult = form.cleaned_data["query"].casefold() in entry.casefold()
if existsIdenticalResult:
return HttpResponseRedirect(reverse("wiki",
kwargs={"page_title": entry}))
elif existsResult:
is_substring_of_queries.append(entry)
context = {
"form": SearchSite(),
"is_substring_of_queries": is_substring_of_queries
}
response = render(request, "encyclopedia/search.html", context)
return response
When my view.search is requested, it will send the response of either an empty form (if accessed by index.html or if there are no results with a message saying there are no results) , an empty form and all the queries that are substrings of the markdown entries or route the client to an exact entry if the query matched.
Here's the routing down in my urls.py so far:
urlpatterns = [
path("", views.index, name="index"),
path("wiki/<str:page_title>", views.page, name="wiki"),
path("search/", views.search, name="site_search")
]
In my layout.html, I have the following form:
<form action="{% url 'site_search' %}" method="get">
{{ form }}
<input type="submit">
</form>
as well as in my search.html the queries that are substrings of the markdown entries:
{% if is_substring_of_queries %}
<h1>Search Results</h1>
{% for query in is_substring_of_queries%}
<li> {{ query }} </li>
{% endfor %}
{% else %}
<h1>No Results! Try again.</h1>
{% endif %}
If there are any mistakes, please let me know.
My url path finder doeds not find result.html page when i click on submit button it will not find that result.html page . it can not find the second url path.Iam trying to add two numbers in Django a basic django Programmge in first it will open the home.html page then on click submit it will not open the result.html page on which the result is displaed
i have tried to import pattrens but it will show errors pattrens can not be imported somethig like i have also tried to direct the page from
This is my url.py file
from django.conf.urls import include, url
from django.contrib import admin
from . import views
admin.autodiscover()
urlpatterns = [
url('', views.home,name='home'),
url(r'^add/', views.add, name ='add'),
]
##this is my home.html file
{% extends 'base.html' %}
{% block content %}
<body>
<h1> Hello {{name}} !!!!!!! </h1>
<form action="add">
Enter First Number : <input type="text" name ="first">
Enter Second Number : <input type="text" name ="second">
<input type ="submit">
</form>
</body>
## this is my view.py file
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
return render(request,'home.html',{'name': 'Harsh'})
def add(request):
val1= int(request.GET['first'])
val2= int(request.GET['second'])
res = val1 + val2
return render(request,'result.html',{'result':res})
## this is my result.html file
{% extends 'base.html' %}
{% block content %}
Result : {{result}}
{% endblock %}
#this is base .html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Tisraa</title>
</head>
<body bgcolor="cyan">
{% block content %}
{% endblock %}
i did't understand where the proble is because when i rub or erase the
first url code that is url('', views.home,name='home'),
it will show the result page but it will not coonect when i push the submit buttonenter code here
Change your url of home to:
url(r'^$', views.home, name='home'),
otherwise all cases will be handled by home.
Or move your add url above to make django see it first. Sequence of urls matters in django.
url(r'^add/', views.add, name ='add'),
url('', views.home,name='home'),
perhaps the / is causing the issue
try this:
<form action="add/">
and the url is missing the beginning/end regex
url('^$', views.home,name='home'),