Still needs working answer.
I have added three apps to my django website: application, blog, and feedback. All three have the same problem: when I click a link, or enter a URL, to any of them, I get a 404 error.
I'm attaching code and other documentation below for one of the problem addons. For further context, if necessary, my full code can be found at https://github.com/kkerwin1/pensdnd.
Directory structure
(venv) kris#adjutant:~/venv/pensdnd$ tree -if
.
./application
./application/admin.py
./application/apps.py
./application/forms.py
./application/__init__.py
./application/migrations
./application/models.py
./application/templates
./application/templates/application.html
./application/templates/application_thanks.html
./application/tests.py
./application/urls.py
./application/views.py
./blog
./blog/admin.py
./blog/apps.py
./blog/models.py
./blog/templates
./blog/templates/blog_list.html
./blog/templates/blog_post.html
./blog/tests.py
./blog/urls.py
./blog/views.py
./feedback
./feedback/admin.py
./feedback/apps.py
./feedback/forms.py
./feedback/models.py
./feedback/templates
./feedback/templates/feedback.html
./feedback/templates/feedback_thanks.html
./feedback/tests.py
./feedback/urls.py
./feedback/views.py
./manage.py
./pensdnd
./pensdnd/settings.py
./pensdnd/static
./pensdnd/static/css
./pensdnd/static/css/main.css
./pensdnd/static/html
./pensdnd/static/html/arvon_rules.html
./pensdnd/static/html/be_a_dm.html
./pensdnd/static/html/community_rules.html
./pensdnd/static/html/guild_rules.html
./pensdnd/static/html/index.html
./pensdnd/static/html/volunteer.html
./pensdnd/static/img
./pensdnd/static/img/carbon_fibre.png
./pensdnd/static/img/github_icon.png
./pensdnd/static/js
./pensdnd/static/misc
./pensdnd/static/templates
./pensdnd/static/templates/base.html
./pensdnd/static/templates/partials
./pensdnd/static/templates/partials/blogbar.html
./pensdnd/static/templates/partials/feedback.html
./pensdnd/static/templates/partials/footer.html
./pensdnd/static/templates/partials/navbar.html
./pensdnd/static/templates/partials/newsbar.html
./pensdnd/static/vid
./pensdnd/urls.py
./pensdnd/views.py
./pensdnd/wsgi.py
./requirements.txt
./pensdnd/urls.py
from django.contrib import admin
from django.urls import path, include
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.HomePageView.as_view()),
path('admin/', admin.site.urls),
path('be_a_dm/', views.BeADM.as_view()),
path('blog/', include('blog.urls')),
path('feedback/', include('feedback.urls')),
path('application/', include('application.urls')),
path('guild_rules/', views.GuildRules.as_view()),
path('community_rules/', views.CommunityRules.as_view()),
path('arvon_rules/', views.ArvonRules.as_view()),
path('volunteer/', views.Volunteer.as_view()),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
./blog/urls.py
from . import views
from django.urls import path
urlpatterns = [
path('blog/', views.PostList.as_view()),
path('blog/<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
]
./blog/views.py
from django.shortcuts import render
from .models import Post
from django.views import generic
# Create your views here.
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'templates/blog_list.html'
class PostDetail(generic.DetailView):
model = Post
template_name = 'templates/blog_post.html'
./blog/models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
STATUS = (
(0,"Draft"),
(1,"Publish")
)
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
updated_on = models.DateTimeField(auto_now= True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
./blogs/templates/blog_list.html
{% extends 'static/templates/base.html' %}
<!doctype html>
<html lang="en">
<head>
<title>
{% block title %}
PensiveDND :: Blog Posts
{% endblock %}
</title>
</head>
<body>
{% block pagecontent %}
<section>
{% for post in post_list %}
<article>
<h3>{{ post.title }}</h3>
<p>{{ post.author }} | {{ post.created_on }}</p>
<p>{{ post.content|slice:":200" }}
Read More
</article>
</section>
{% endblock %}
</body>
</html>
./blogs/templates/blog_post.html
{% extends 'static/templates/base.html' %}
<!doctype html>
<html lang="en">
<head>
<title>
{% block title %}
PensiveDND :: Blog :: {{ post.title }}
{% endblock %}
</title>
</head>
<body>
{% block pagecontent %}
<section>
<h2>{{ post.title }}</h2>
<p>{{ post.author }} | {{ post.created_on }}</p>
<p>{{ post.content | safe }}</p>
</section>
{% endblock %}
</body>
</html>
In "pensdnd/urls.py", you are missing the trailing slashes after your app name
for example
path('feedback', include('feedback.urls')),
should be
path('feedback/', include('feedback.urls')),
Unable to access html files. There are no errors in your urls.py file. At least for the blog app. When I run the code, I don't get a 404 error with different edits. According to the Github codes, I changed the DIRS section in the templates field under settings.py to 'templates' and moved the html files you used in your blog application here. There was no problem. Editing all your code can be difficult, but that's where the problem lies.(Note that I only control the blog app.)
also, you will get an error because you don't use {% endfor %}.
{% for post in post_list %}
<article>
<h3>{{ post.title }}</h3>
<p>{{ post.author }} | {{ post.created_on }}</p>
<p>{{ post.content|slice:":200" }}
Read More
</article>
If you have set templates location, you should just use template_name = 'blog_list.html instead of template_name = 'templates/blog_list.html'.
Please check these things again. As I said, the problem is caused by the use of static and templates. not urls.
Related
I'm trying to get my django model to be shown in the footer of my base.html but I can't get it to show up. I've looked at a few videos and I can't figure out where I'm going wrong. I know that the model works as I've made 4 entries in my database and I can view them on the admin page. The code also doesn't show any errors so I have nothing to go off of there. Here it is:
Models.py
class SocialMediaPlatform(models.Model):
name = models.CharField(max_length=50, blank=True, null=True)
font_awesome_class = models.CharField(max_length=50, blank=True, null=True)
base_url = models.CharField(max_length=50, blank=True, null=True,
default='https://instagram.com/ or https://tiktok.com/#')
def __str__(self):
return self.base_url
Views.py
def social_media_base_view(request):
context = {}
smbase = SocialMediaPlatform.objects.all()
context['smbase'] = smbase
return render(request, 'base.html', context)
Urls.py
urlpatterns = [
path('', views.social_media_base_view),
]
Admin.py
#admin.register(SocialMediaPlatform)
class SocialPlatformAdmin(admin.ModelAdmin):
list_display = ('name', 'font_awesome_class', 'base_url')
base.html
{% for smlink in smbase %}
<a href="{{ smlink.name }}">
<i class="{{ smlink.font_awesome_class }}">
</a>
{% endfor %}
Look what you are passing as context:
def social_media_base_view(request):
...
smbase = SocialMediaPlatform.objects.all()
context['smbase'] = smbase
return ...
It's QuerySet of SocialMediaPlatform objects. It means, that you can render them one by one with for loop:
{% for smlink in smbase %}
{{ smlink.name }}
{% endfor %}
You don't need to call SocialMediaPlatform model additionaly.
in your view you use:
return render(request, 'index.html', context)
i can not see, if you are defined index.html
Somethere in index you should have
{% extends base.htm %}
The second, i am agree with #Shabble:
{% for smlink in smbase %}
<a href="{{ smlink.name }}">
<i class="{{ smlink.font_awesome_class }}">
</a>
{% endfor %}
The last:
Try to use Django-GCBV TemplateView. Or ListView, in your case it is better:
somethere in views.py
Class MyListView(ListView):
model = SocialMediaPlatform
template_name = index.html
somethere in urls.py
urlpatterns = [
path('', MyListView.as_view()),
]
somethere in index.html
{% for smlink in object_list %}
<a href="{{ smlink.name }}">
<i class="{{ smlink.font_awesome_class }}">
</a>
{% endfor %}
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
hey im new to django so don't be harsh !.im trying to make a blog in django . i need to map the posts in home page to the post page. for that .i have defined a function called get_absulute_url(self) in models.py but it is not recognized in index.html.
when i click on Links nothing happens...i'm not where did i made the mistake !
model.py
from django.db import models
from django.urls import reverse
import posts
# Create your models here.
class post(models.Model):
title=models.CharField(max_length=500)
content=models.TextField()
timestamp=models.DateTimeField(auto_now=False,auto_now_add=True)
updated= models.DateTimeField(auto_now=False,auto_now_add=True)
def get_absulute_url(self):
return reverse("posts:detail", kwargs={'id': self.id})
# return reverse(viewname=posts.views.posts_list,urlconf=any, kwargs={"id": self.id})
views.py
def posts_list(request):#list items
queryset=post.objects.all()
context={
"objectsList":queryset,
"title":"list"
}
return render(request,"index.html",context)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
{% for obj in objectsList %}
Link<br>
{{ obj.title }} <br>
{{ obj.content }} <br>
{{ obj.timestamp }} <br>
{{ obj.updated }} <br>
{{ obj.id }} <br>
{{ obj.pk }} <br>
{% endfor %}
</body>
</html>
url.py
from django.contrib import admin
from django.urls import path
from posts import views as posts_views
urlpatterns = [
path('create/',posts_views.posts_create),
path('<int:id>/', posts_views.posts_detail,name="detail"),
path('',posts_views.posts_list),
path('update/', posts_views.posts_update),
path('delete/', posts_views.posts_delete),
]
Change posts:detail to detail
return reverse("detail", kwargs={'id': self.id})
href="{% url "detail" id=obj.id %}"
Mapping may be the problem but it will throw error before execution.
Still add app_name = 'posts' in urls.py file of your app and try this may work or just use DetailView builtin class still getting error you better add post_detail view to the question above so we can get indepth picture of what you are looking for.
I have created a class in the models.py containing the information of articles I want to insert in a website
from django.db import models
from django.urls import reverse
class Article(models.Model):
"""
Model representing an article.
"""
title = models.CharField(max_length=200)
authors = models.CharField(max_length=200)
summary = models.TextField(max_length=1000, help_text='Enter a brief description of the article')
content = models.TextField(max_length=100000)
def __str__(self):
"""
String for representing the Model object.
"""
return self.title
def get_absolute_url(self):
"""
Returns the url to access a detail record for this article.
"""
return reverse('article-detail', args=[str(self.id)])
After that, I have inserted an article using the admin panel of Django and saved it.
Then, I have created the index.html shown below calling the articles in the database
<!DOCTYPE html>
<html lang="en">
<head>
{% block title %}{% endblock %}
</head>
<body>
{% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %}
{% block content %}<!-- default content text (typically empty) -->
<!-- Articles -->
<div class="articles">
<h1>Titolo: {{ article.title }}</h1>
<p><strong>Autori:</strong> {{ article.authors }}</p>
<p><strong>Riepilogo:</strong> {{ article.summary }}</p>
<p><strong>Testo:</strong> {{ article.content }}</p>
</div>
{% endblock %}
</body>
</html>
But the article is not shown despite being in the database (see prints below)
EDIT1: inserted views.py as requested
from django.shortcuts import render
from .models import Article
# Create your views here.
def index(request):
"""
View function for home page of site.
"""
# Render the HTML template index.html with the data in the context variable
return render(
request,
'index.html',
)
You are not including any articls in your template context:
return render(
request,
'index.html',
)
You could include the articles in the template context with:
articles = Article.objects.all()
return render(
request,
'index.html',
{'articles': articles}
)
Then in the template you need to loop through the articles.
<!-- Articles -->
<div class="articles">
{% for article in articles %}
<h1>Titolo: {{ article.title }}</h1>
<p><strong>Autori:</strong> {{ article.authors }}</p>
<p><strong>Riepilogo:</strong> {{ article.summary }}</p>
<p><strong>Testo:</strong> {{ article.content }}</p>
{% endfor %}
</div>
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!