polls/templates/polls/index.html
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li>{{ question.question_text }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
The above index.html is from Tutorial #3 from Django 1.8. My question is where/how does index.html know which domain to use?
The index.html file will be associated with a view and that view will be associated to a url that will be configured in the urls.py file.
When you upload your project to a server, you will then configure the servers configuration, linking your project to a domain.
Example: myawesomedomain.com
views.py
def HomeView(request):
return render(request, 'index.html', {context})
def ContactView(request):
return render(request, 'contact.html', {context})
urls.py
from django.conf.urls import patterns, include, url
from . import views
urlpatterns = patterns('',
url(r'^$', views.HomeView), # http://myawesomedomain.com
url(r'^contact$', views.ContactView), # http://myawesomedomain.com/contact
)
Related
I am trying to limit the amount of time a user can stay logged in for using the settings.py and using Sessions.
settings.py
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
SESSION_COOKIE_AGE = 60
SESSION_SAVE_EVERY_REQUEST = True
home.html
{% extends 'base.html' %}
{% block title %}Home{% endblock %}
{% block content %}
{% if user.is_authenticated %}
Hi {{ user.username }}!
<p>Log Out</p>
{% else %}
<p>You are not logged in</p>
Log In
{% endif %}
{% endblock %}
urls.py
from django.urls import path
from django.views.generic.base import TemplateView # new
urlpatterns = [
path('', TemplateView.as_view(template_name='home.html'), name='home')
]
views.py
from django.shortcuts import render
def index(request):
# now the index function renders the home page
return render(request,'home.html')
Currently it stays logged in and displays the Hi user.username no matter how long the time passes. However refreshing the page after 60 seconds shows not logged in.
I have problems to link my custom button from change_form.html to my view function.
pic : admin change form custom button
change_form.html
{% extends "admin/change_form.html" %}
{% load i18n %}
{% block title %} Send Email {% endblock %}
{% block content %}
{% if request.resolver_match.url_name == 'requests_requests_change' %}
<div class="submit-row">
{% csrf_token %}
<a href="{% url 'requests:send-email' original.pk %}"
class="button" style="background-color: #F08000;float: left">Request Subscription
</a>
</div>
{% endif %}
{{ block.super }}
{% endblock %}
views.py
from django.shortcuts import render, redirect
def send_email(request, requests_id):
return redirect('') # or whatever to test the url
urls.py
from django.urls import path
from . import views
app_name = 'requests'
urlpatterns = [
path('<int:pk>/send-email/', views.send_email, name='send-email'),
]
main project urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', admin.site.urls), # admin site administration
path('requests/', include('requests.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
pic: error message
Any help would be great! Thanks!
I have found the solution on my own.
The issue was the url inside the template.
Worked with this one:
Template :
<a href="{% url 'admin:requests_requests_change' original.pk %}send-email/"
And the URL path:
path('<int:pk>/change/send-email/', views.send_email, name='send-email')
I was following the django documentation and making a simple poll app. I have come across the following error :
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^polls/
^admin/
The current URL, , didn't match any of these."
settings.py
ROOT_URLCONF = 'mysite.urls'
mysite/mysite/urls.py
from django.conf.urls import include,url
from django.contrib import admin
urlpatterns = [
url(r'^polls/',include('polls.urls')),
url(r'^admin/', admin.site.urls),]
mysite/polls/urls.py
from django.conf.urls import url
from . import views
app_name= 'polls'
urlpatterns=[
url(r'^$',views.IndexView.as_view(),name='index'),
url(r'^(?P<pk>[0-9]+)/$',views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/results/$',views.ResultsView.as_view(),name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$',views.vote,name='vote'),]
mysite/polls/views.py
from django.shortcuts import get_object_or_404,render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone
from django.template import loader
from .models import Choice,Question
from django.template.loader import get_template
#def index(request):
# return HttpResponse("Hello, world. You're at the polls index")
class IndexView(generic.ListView):
template_name='polls/index.html'
context_object_name='latest_question_list'
def get_queryset(self):
"""Return the last five published questions."""
return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[5:]
class DetailView(generic.DetailView):
model=Question
template_name='polls/detail.html'
def get_queryset(self):
"""
Excludes any questions that aren't published yet.
"""
return Question.objects.filter(pub_date__lte=timezone.now())
class ResultsView(generic.DetailView):
model= Question
template_name ='polls/results.html'
def vote(request, question_id):
question=get_object_or_404(Question, pk=question_id)
try:
selected_choice= question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/details.html',
{
'question':question,
'error_message' : "You didn't select a choice" ,
})
else:
selected_choice.votes+=1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
index.html
<!DOCTYPE HTML >
{% load staticfiles %}
<html>
<body>
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'polls:detail' question.id %}">{{question.question_test }}
</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
</body>
</html>
This link http://127.0.0.1:8000/polls/ shows a blank page with 3 bullets. (I have 3 questions in my database and their id's are 5,6,7 because I have been deleting and adding the questions.)
My admin works fine!
I'm new to Django and have been searching and asking around and have been stuck on it for a while now.
You get the 404 on http://127.0.0.1:8000/ because you have not created any URL patterns for that url. You have included the url http://127.0.0.1:8000/polls/, because you have included the polls urls with
url(r'^polls/',include('polls.urls')),
The empty bullets suggest that there is a problem with your polls/index.html template. It looks like you have a typo and have put {{ question.question_test }} instead of {{ question.question_text }}. Make sure that it exactly matches the template from the tutorial 3:
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li>{{ question.question_text }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
Make sure there is no typo in your code. Putting space between inverted commas can also lead to this error. Just make sure you have put path('',include('home.urls')) and not path(' ',include('home.urls'))
Note: here home.urls is the name of my app in Django
I was following the django documentation and making a simple poll app. I have come across the following error :
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^polls/
^admin/
The current URL, , didn't match any of these."
settings.py
ROOT_URLCONF = 'mysite.urls'
mysite/mysite/urls.py
from django.conf.urls import include,url
from django.contrib import admin
urlpatterns = [
url(r'^polls/',include('polls.urls')),
url(r'^admin/', admin.site.urls),]
mysite/polls/urls.py
from django.conf.urls import url
from . import views
app_name= 'polls'
urlpatterns=[
url(r'^$',views.IndexView.as_view(),name='index'),
url(r'^(?P<pk>[0-9]+)/$',views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/results/$',views.ResultsView.as_view(),name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$',views.vote,name='vote'),]
mysite/polls/views.py
from django.shortcuts import get_object_or_404,render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone
from django.template import loader
from .models import Choice,Question
from django.template.loader import get_template
#def index(request):
# return HttpResponse("Hello, world. You're at the polls index")
class IndexView(generic.ListView):
template_name='polls/index.html'
context_object_name='latest_question_list'
def get_queryset(self):
"""Return the last five published questions."""
return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[5:]
class DetailView(generic.DetailView):
model=Question
template_name='polls/detail.html'
def get_queryset(self):
"""
Excludes any questions that aren't published yet.
"""
return Question.objects.filter(pub_date__lte=timezone.now())
class ResultsView(generic.DetailView):
model= Question
template_name ='polls/results.html'
def vote(request, question_id):
question=get_object_or_404(Question, pk=question_id)
try:
selected_choice= question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/details.html',
{
'question':question,
'error_message' : "You didn't select a choice" ,
})
else:
selected_choice.votes+=1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
index.html
<!DOCTYPE HTML >
{% load staticfiles %}
<html>
<body>
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'polls:detail' question.id %}">{{question.question_test }}
</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
</body>
</html>
This link http://127.0.0.1:8000/polls/ shows a blank page with 3 bullets. (I have 3 questions in my database and their id's are 5,6,7 because I have been deleting and adding the questions.)
My admin works fine!
I'm new to Django and have been searching and asking around and have been stuck on it for a while now.
You get the 404 on http://127.0.0.1:8000/ because you have not created any URL patterns for that url. You have included the url http://127.0.0.1:8000/polls/, because you have included the polls urls with
url(r'^polls/',include('polls.urls')),
The empty bullets suggest that there is a problem with your polls/index.html template. It looks like you have a typo and have put {{ question.question_test }} instead of {{ question.question_text }}. Make sure that it exactly matches the template from the tutorial 3:
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li>{{ question.question_text }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
Make sure there is no typo in your code. Putting space between inverted commas can also lead to this error. Just make sure you have put path('',include('home.urls')) and not path(' ',include('home.urls'))
Note: here home.urls is the name of my app in Django
I have this view function for my blog posts.
def home(request):
posts = Post.objects.all().order_by("-pub_date")
paginator = Paginator(posts, 5)
try: page = int(request.GET.get("page", 1))
except ValueError: page = 1
try: posts = paginator.page(page)
except (InvalidPage, EmptyPage):
posts = paginator.page(paginator.num_page)
return render_to_response("home.html",
dict(posts=posts, user=request.user))
In my main urls.py file, I have the following:
urlpatterns = patterns('',
url(r'^', 'blog.views.home', name='home'),
url(r'^admin/', include(admin.site.urls)),
)
Also, I didn't create a urls.py file under my app folder.
And I have this in my home.html file.
{% block footer %}
<ul class="pager">
{% if posts.object_list and posts.paginator.num_pages > 1 %}
{% if posts.has_previous %}
<li>Previous</li>
{% endif %}
{% if posts.has_next %}
<li>Next</li>
{% endif %}
</ul>
{% endif %}
</div><!-- /.blog-main -->
{% endblock %}
Up to this point, the homepage (home.html) renders properly on my local server. However, when I click on next page link, it sends me to
127.0.0.1:8000/2
and shows the same page. Also, the previous button is not showing.
Question: Have I done anything wrongly? And how do I direct my views to page 2 properly in the url dispatcher?
Help appreciated. Thank you.
you can use the documentation's version of pagination view.
https://docs.djangoproject.com/en/dev/topics/pagination/