I am using Django 1.8.3 and Python 3.4, I'm facing the below issue when clicking on a link on my website.
This is the error page :
Project Directory:
* cacademy:
* __pycache__
* __init__
* settings
* urls
* wsgi
* Classes:
* __pycache__
* migrations
* static
* __init__
* admin
* models
* tests
* urls
* views
* templates:
* cacademy:
* base.html
* classes_list.html
* courses_detail.html
* db.sqlite3
* manage.py
My Models:
from django.db import models
from django.utils import timezone
class Course(models.Model):
title = models.CharField(max_length=200)
text = models.TextField()
teachername = models.TextField(max_length=200)
teacherinfo = models.TextField()
started_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
My Views:
from django.shortcuts import render
from django.utils import timezone
from .models import Course
from django.shortcuts import render, get_object_or_404
def classes_list(request):
courses = Course.objects.filter(started_date__lte=timezone.now()).order_by('started_date')
return render(request, 'cacademy/classes_list.html', {'courses': courses})
def course_detail(request, pk):
course = get_object_or_404(Course, pk=pk)
return render(request, 'cacademy/courses_detail.html', {'course': course})
My Urls:
from django.conf.urls import include, url
from Classes import views
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.classes_list, name='classes_list'),
url(r'^(?P<pk>[0-9]+)/Course/$', views.course_detail, name='Course_detail'),
]
classes_list.html:
{% extends "cacademy/base.html" %}
{% load staticfiles %}
{% block content %}
<div>
<h2> Remember you can only register 3 Courses at once!</h2>
</div>
{% for course in courses %}
<div course="post">
<div course="date">
{{ course.started_date }}
</div>
<h1>{{ course.title }}</h1>
<p>Taught by: {{ course.teachername|linebreaks }}</p>
</div>
{% endfor %}
{% endblock content %}
Change your template url tag to
{% url 'course_detail' course.id %}
and in your urls.py
url(r'^(?P<pk>[0-9]+)/course/$', views.course_detail, name='course_detail')
Firstly, you have assigned reverse name for courses detail url as Course_detail in urls.py but you are using the reverse name as course_detail in your template. It should have been Course_detail in the template.
Secondly, you are passing pk as Course.pk in your template. It should have been course.pk instead as you are using course variable when iterating over courses objects.
Instead use reverse name with lowercase initial to remove the case-sensitive issues.
urls.py
from django.conf.urls import include, url
from Classes import views
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.classes_list, name='classes_list'),
url(r'^(?P<pk>[0-9]+)/Course/$', views.course_detail, name='course_detail'), # assign reverse name with lowercase initial letter
]
Then in your template, you can do this:
classes_list.html
{% extends "cacademy/base.html" %}
{% load staticfiles %}
{% block content %}
<div>
<h2> Remember you can only register 3 Courses at once!</h2>
</div>
{% for course in courses %}
<div course="post">
<div course="date">
{{ course.started_date }}
</div>
<h1>{{ course.title }}</h1>
<p>Taught by: {{ course.teachername|linebreaks }}</p>
</div>
{% endfor %}
{% endblock content %}
Related
I have been facing this issue. And I have a url name post-page-detail but then also getting error please
See the error screenshot below.
My singlepost.html html page
<a href="{% url "post-detail-page" slug=post.slug %}">
<h2>{{post.tractor_company}} || {{post.tractor_model}}</h2>
<pre><h5>{{post.implimentaion}}</h5>
{{post.farmer}}
Uplode Date : {{post.date}}</pre>
</a>
</div>
URLs.py
from . import views
urlpatterns = [
path("",views.starting_page,name = "starting-page"),
path("posts",views.posts,name = "post-page"),
path("posts/<slug:slug>",views.post_detail,name="post-detail-page"),
]
View.py
from django import forms
from django.contrib.auth.models import User
from django.shortcuts import render, redirect ,get_object_or_404
from .models import Post, Farmer
# Create your views here.
from django.http import HttpResponseRedirect
# Create your views here.
def starting_page(request):
return render(request,"tractor/index.html")
def posts(request):
qs = Post.objects.all()
context = {"posts":qs}
return render(request,"tractor/all-post.html",context)
def add_post(request):
pass
def post_detail(request,slug):
indentified_post = get_object_or_404(Post,slug=slug)
return render(request,"blog/post-detail.html",{'post':indentified_post})
i am iterating through posts and using the post-detail.html page
all-post.html.
{% load static %}
{% block title %}
All Tractors
{% endblock %}
{% block content%}
<section id="all_events">
<br>
<h1 style="text-align:center;">All Tractors</h1>
<ul>
{% for post in posts %}
<br>
{% include "tractor/includes/singlePost.html" %}
{% endfor %}
</ul>
</section>
{% endblock %}
Root urls.py
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path("",include(("tractor.urls","tractor"))),
]
The 'tractor' part in the path('', include(('tractor.urls', 'tractor'))) in the include(…) function [Django-doc] specifies the app_namespace. This means that for all URLs you use in the tractor.urls urls, you should prefix this with tractor::
<a href="{% url 'tractor:post-detail-page' slug=post.slug %}">
…
</a>
I am trying to create webpages that link to each other with Django. I created a model with several elements: title, summary, description01, description02. On the first page, the home page, I display the title and summary, this seems to work fine. However, I want a link after the title and summary that links to a page with description01 and then a link to a page with description02. This is where I am having issues. I created a file for description01.html, I created a function for it in views.py, a path in urls.py, and added a link to home. When I try to open the home page, I get error: NoReverseMatch at /
Reverse for 'description01' with arguments '(3,)' not found. 1 pattern(s) tried: ['articles/$']
Code and Screenshots:
home.html
<h1>home</h1>
{% for outline in outline %}
{{ outline.title }}<br>
{{ outline.summary }}<br>
LInk
{% endfor %}
viwes.py
from django.shortcuts import render
from .models import Outline
def home(request):
outline = Outline.objects.all()
return render(request, 'articles/home.html', {'outline': outline})
def description01(request):
outline = Outline.description01
return render(request, 'articles/description01.html', {'outline': outline})
urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
from articles import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('articles/', views.description01, name='description01'),
]
models.py
from django.db import models
class Outline(models.Model):
title = models.CharField(max_length=100)
summary = models.CharField(max_length=250, default="")
description01 = models.CharField(max_length=250, default="")
description02 = models.CharField(max_length=250, default="")
description01.html
<h1>description01</h1>
{% for outline in outline %}
{{ outline.description01 }}<br>
{% endfor %}
enter image description here
{% for outline in outline %} may give you an error, because you could be calling the inner outline or the global one. Try changing it to:
{% for otlne in outline %}
{{ otlne.description01 }}<br>
{% endfor %}
Also, there is probably something wrong with outline = Outline.description01, don't you mean:
def description01(request):
outline_objs = Outline.objects.all()
context = {
'd_01': [outline.description01 for outline in outline_objs]
}
return render(request, 'articles/description01.html', context=context)
and then:
{% for d in d_01 %}
{{ d }}<br>
{% endfor %}
This way, the d_01 key that would be accessed in the HTML files would be only a list of the description01 in all Outlines objects.
I'm trying to display information from my model Administrateur into my HTML Template login.html, but nothing is happening.
This my Model:
from django.db import models
class Administrateur(models.Model):
nom = models.CharField(max_length=30)
prenom = models.CharField(max_length=30)
mdp = models.CharField(max_length=30)
mail = models.CharField(max_length=30)
def _str_(self):
return self.name
This is my view:
def Pseudo(request):
administrateurs = Administrateur.objects.all()
context={'administrateurs':administrateurs}
return render(request, "login.html",context)
This is my HTML:
{% extends "base.html" %}
{% load static %}
{% block content %}
{% for n in administrateurs %}
{{ n.nom }}
{{ n.prenom }}
{% endfor %}
{% endblock %}
I'm not sure what to do with urls.py
Do this step if you have not done it yet:
Add this to the file urls.py in the project's base directory:
from django.urls import include
urlpatterns = [
# your urls
path('login/', include('appname.urls')), #change appname to your app's name
]
now in your app make a new file called urls.py and add this to the file:
from django.urls import path
from .views import Pseudo
urlpatterns = [
path('', Pseudo, name="pseudo"),
]
then check when you go to login page (in url bar) what happens
Still newbie in django, please help me
Urls.py :
from django.conf.urls import url
from . import views
app_name = 'lostfound'
urlpatterns = [
# /lostfound/
url(r'^$', views.IndexView.as_view(), name='index'),
# /lostfound/lostitems
url(r'lostitems/', views.LostItemsView.as_view(), name='lost_items'),
this is the main problem of my url, i can't display my register_lost.html
# /lostfound/lostitems/addlostitems
url(r'/addlostitems/$', views.RegisterLostView.as_view(), name='register_lost'),`
Views.py :
from django.views import generic
from .models import Wallet
class IndexView(generic.ListView):
model = Wallet
template_name = 'lostfound/index.html'
class LostItemsView(generic.ListView):
model = Wallet
template_name = 'lostfound/lost_items.html'
class RegisterLostView(generic.ListView):
model = Wallet
template_name = 'lostfound/register_lost.html'
lost_items.html :
<div class="menu-button z-depth-3 right">
<a class="waves-effect waves-light btn" href="{% url 'lostfound:register_lost' %}">
<i class="medium material-icons right">playlist_add</i>Tambah Data
</a>
</div>
this is my register_lost.html that i want process
register_lost.html :
{% extends 'lostfound/base.html' %}
{% extends 'lostfound/lost_items.html' %}
{% block title %}Register Lost Items{% endblock %}
{% block content %}
{% load staticfiles %}
{% block sign_in %}
{% endblock %}
<h1>Hello</h1>
{% endblock %}
Try to switch lines in the urlpatterns list
this:
url(r'/addlostitems/$', views.RegisterLostView.as_view(), name='register_lost'),
before this:
url(r'lostitems/', views.LostItemsView.as_view(), name='lost_items'),
I'm new to Django and have been stuck on this for a few days now. Hoping to find some help here. I've searched stackoverflow and read through the django docs but haven't been able to grasp this. I'm using Django 1.6.2 and Python 2.7.
I'm setting up a simple news app in which article has a ManyToMany relationship with category. I'm running into trouble trying to display articles from a specific category. I have the index working displaying all articles and also the single page view is working e.g. clicking on article title from index brings you to the article itself. Once in the article I am displaying the article category. Up to here all is well. When I try to link the category and display an index for all posts in that category I get a NoReverseMatch for the url 'category-archive'.
Should I do this in a view like I'm trying or would the Manager work better? Open to all suggestions and answers. Like I said I'm new so would like to know best practice. Here is my code and thank you in advance for dealing with a noobie.
models.py
from django.db import models
from tinymce import models as tinymce_models
class ArticleManager(models.Manager):
def all(self):
return super(ArticleManager, self).filter(active=True)
class Category(models.Model):
title = models.CharField(max_length=65)
slug = models.SlugField()
def __unicode__(self, ):
return self.title
class Article(models.Model):
title = models.CharField(max_length=65)
slug = models.SlugField()
description = models.CharField(max_length=165)
content = tinymce_models.HTMLField()
categories = models.ManyToManyField(Category)
image = models.ImageField(upload_to='article/images')
active = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
objects = ArticleManager()
def __unicode__(self, ):
return self.title
class Meta:
ordering = ['-timestamp',]
views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, RequestContext, get_object_or_404
from .models import Article, Category
def all_articles(request):
articles = Article.objects.all()
return render_to_response('news/all.html', locals(), context_instance=RequestContext(request))
def single_article(request, slug):
article = get_object_or_404(Article, slug=slug)
return render_to_response('news/single.html', locals(), context_instance=RequestContext(request))
def category_archive(request, slug):
articles = Article.objects.filter(category=category)
categories = Category.objects.all()
category = get_object_or_404(Category, slug=slug)
return render_to_response('news/category.html', locals(), context_instance=RequestContext(request))
single.html - for single article view
{% extends 'base.html' %}
{% block content %}
<h1>{{ article.title }}</h1>
<img src='{{ MEDIA_URL }}{{ article.image }}' class="article-image img-responsive"/>
<p>{{ article.content|safe }}</p>
<p class='small'>
**this next line gets an error for the url 'category-archive'**
{% for category in article.categories.all %}Category: <a href='{% url "category-archive" %}{{ category.slug }}'>{{ category }}</a>{% endfor %}</p>
{% endblock %}
category.html - display all articles in specific category
{% extends 'base.html' %}
{% block content %}
{% for article in articles %}
<h1><a href='{% url "articles" %}{{ article.slug }}'>{{ article }}</a></h1>
<a href='{% url "articles" %}{{ article.slug }}'><img src='{{ MEDIA_URL }}{{ article.image }}' class="img-responsive"/></a>
{{ article.description }}
{% if forloop.counter|divisibleby:4 %}
<hr/>
<div class='row'>
{% endif %}
{% endfor %}
</div>
{% endblock %}
urls.py - project urls
from django.conf.urls import patterns, include, url
from django.conf import settings
from filebrowser.sites import site
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^tinymce/', include('tinymce.urls')),
(r'^admin/filebrowser/', include(site.urls)),
(r'^grappelli/', include('grappelli.urls')),
(r'^static/(?P<path>.*)$', 'django.views.static.serve',{
'document_root': settings.STATIC_ROOT
}),
(r'^media/(?P<path>.*)$', 'django.views.static.serve',{
'document_root': settings.MEDIA_ROOT
}),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'dl.views.home', name='home'),
(r'^news/', include('news.urls')),
(r'^guides/', include('guides.urls')),
)
urls.py - news urls
from django.conf import settings
from django.conf.urls import patterns, include, url
urlpatterns = patterns('news.views',
url(r'^$', 'all_articles', name='articles'),
url(r'^(?P<slug>[-\w]+)/$', 'single_article'),
**This next one is giving me the problem I suspect - should be url to category with articles**
url(r'^chive/(?P<slug>[-\w]+)/?', 'category_archive', name='category-archive'),
)
I would have post it as a comment but i don't have the reputation.
I think that the thing is that the URL Dispatcher expects the category-archive to also get the slug. so you should change the URL in the template to:
{% url "category-archive" category.slug %}
hope this helps!