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.
Related
I have 2 models named "developer" and "skill". I made a page for all the developers that have their respective information. Now, I want to make a page that lists all the developers with links that navigate to their respective information page.
The page that shows all the developers' URLs is 'developers/' and its name is "developers". The URL of the second page is 'developers/id' and its name is developer, however it instead navigates to 'developers/developers/id'.
I tried the page that shows the information of a certain developer and it was ok but I have problem with this one cause it won't navigate.
here are my codes :
views.py
from django.shortcuts import render
from .models import Developer, Skill
# Create your views here.
def show_developers(request):
query = Developer.objects.all()
context = {'devs': query}
return render(request, 'users/devs.html', context=context)
def show_single_developer(request, pk):
query = Developer.objects.get(id=pk)
context = {'dev': query}
return render(request, 'users/single_dev.html', context=context)
models.py
from django.db import models
# Create your models here.
class Skill(models.Model):
choices = (
('Beginner', 'Beginner'),
('Junior', 'Junior'),
('Senior', 'Senior'),
)
name = models.CharField(max_length=50)
level = models.CharField(choices=choices, max_length=10)
class Developer(models.Model):
full_name = models.CharField(max_length=50)
username = models.CharField(max_length=50)
intro = models.TextField(blank=True, null=True)
image = models.ImageField()
skills = models.ForeignKey(Skill, on_delete=models.CASCADE)
urls.py
from django.urls import path
from .views import show_developers, show_single_developer
urlpatterns = [
path('developers/', show_developers, name='developers'),
path('developers/<str:pk>/', show_single_developer, name='developer'),
]
devs.html
{% include 'navbar.html' %}
<table>
<tr>
<th>FullName</th>
<th>Username</th>
<th>details</th>
</tr>
{% for dev in devs %}
<tr>
<td>{{dev.full_name}}</td>
<td>{{dev.username}}</td>
<td>View</td>
</tr>
{% endfor %}
</table>
{% include 'footer.html' %}
single_dev.html
{% include 'navbar.html' %}
<h2>{{dev.full_name}}</h2>
<hr>
<h3>Intro</h3>
<h4>{{dev.intro}}</h4>
{% for skill in dev.sills.all %}
<div>
<p>{{skill.name}}</p>
<p>{{skill.level}}</p>
</div>
{% endfor %}
{% include 'footer.html' %}
TraceBack Section
and I add the structures of this app too
Error page
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
I am new in Django and Wagtail and I am facing little problem.
I want to assess Wagtail Site Setting using Django inclusion_tag.
in short, {{ settings.app_1.SimpleHtmlSettings.heading }} and {{ settings.app_1.SimpleHtmlSettings.body }} in index.html is not printing any thing.
I tried total two solutions but non of them is working
app_1_extras.py (simple_html = SimpleHtmlSettings.for_site(context['request'].site))
app_1_extras.py (simple_html = SimpleHtmlSettings.objects.first)
models.py
from django.db import models
from wagtail.contrib.settings.models import BaseSetting, register_setting
# Create your models here.
#register_setting
class SimpleHtmlSettings(BaseSetting):
heading = models.CharField(
max_length=255, help_text='Enter heading')
body = models.CharField(
max_length=255, help_text='Enter body content')
views.py
from django.shortcuts import render
from app_1.models import SimpleHtmlSettings
from django.http import HttpResponse
# Create your views here.
def index(request):
return render(request, 'app_1/test.html')
app_1_extras.py
from django import template
from app_1.models import SimpleHtmlSettings
register = template.Library()
#register.inclusion_tag('app_1/index.html', takes_context=True)
def show_results(context):
# simple_html = SimpleHtmlSettings.for_site(context['request'].site)
simple_html = SimpleHtmlSettings.objects.first
return {'simple_html': simple_html}
index.py
{% load wagtailsettings_tags %}
<h1>{{ settings.app_1.SimpleHtmlSettings.heading }}</h1>
<p>{{ settings.app_1.SimpleHtmlSettings.body }}</p>
<p>Check</p>
test.py
{% load wagtailsettings_tags %}
{% load app_1_extras %}
{% show_results %}
test.html only printing "Check"
Thanks!!!
You're setting up the variable simple_html to be available in your index.html template, and then never using that variable. index.html should become:
<h1>{{ simple_html.heading }}</h1>
<p>{{ simple_html.body }}</p>
<p>Check</p>
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 %}
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!