I am learning django and I really can't solve this error, I tried modifying every file but I can't find where the issue is.
Error:
OperationalError at /topics/
no such table: pizzas_topic
I have to mention that this exercise is from Python Crash Course 2nd Edition
Thanks
Here is the code from my project:
base.html:
<p>
Pizzeria -
Pizzas
</p>
{% block content %}{% endblock content %}
index.html
{% extends "pizzas/base.html"%}
{% block content %}
<p>Pizzeria</p>
<p>Hi</p>
{% endblock content%}
topic.html
{% extends 'pizzas/base.html' %}
{% block content %}
<p>Topic: {{topic}}</p>
<p>Entries:</p>
<ul>
{% for entry in entries %}
<li>
<p>{{entry.date_added|date:'M d, Y H:i'}}</p>
<p>{{entry.text|linebreaks}}</p>
</li>
{% empty %}
<li>There are no entries for this topic yet.</li>
{% endfor %}
</ul>
{% endblock content %}
topics.html
{% extends "pizzas/base.html" %}
{% block content %}
<p> Topics</p>
<ul>
{% for topic in topics %}
<li>
{{ topic }}
</li>
{% empty %}
<li>No topics have been addet yet.</li>
{% endfor %}
</ul>
{% endblock content %}
urls.py
"""Defines URL patterns for pizzeria."""
from django.urls import path
from . import views
app_name = 'pizzas'
urlpatterns = [
# Home page
path('',views.index, name='index'),
# Page that shows all pizzas.
path('topics/', views.topics, name='topics'),
# Detail page for a single topic.
path('topics/<int:topic_id>/', views.topic, name='topic'),
]
views.py
from django.shortcuts import render
from .models import Topic
def index(request):
"""The home page for Learning Log."""
return render(request, 'pizzas/index.html')
def topics(request):
"""Show all topics."""
topics = Topic.objects.order_by('date_added')
context = {'topics': topics}
return render(request,'pizzas/topics.html',context)
def topic(request, topic_id):
"""Show a single topic and all its entries."""
topic = Topic.objects.get(id=topic_id)
entries = topic.entry_set.order_by('-date_added')
context = {'topic': topic, 'entries': entries}
return render(request, 'pizzas/topic.html', context)
Run:
python manage.py migrate
python manage.py makemigrations
python manage.py migrate
Related
I am following the book Python Crash Course and am trying to do the Learning Logs app for Django. Everything was going well except when I tried to add entry forms for users on chapter 19. I am encountering the error
Reverse for 'new_entry' with arguments '('',)' not found.
1 pattern(s) tried: ['new_entry/(?P<topic_id>[0-9]+)/$']
My models.py look like this:
from django.db import models
# Create your models here.
class Topic(models.Model):
"""A topic the user is learning about"""
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
"""Return a string representation of the model."""
return self.text
class Entry(models.Model):
"""Something specific learned about a topic"""
topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
text = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'entries'
def __str__(self):
"""Return a string representation of the model."""
return self.text[:50] + "..."
My urls.py:
"""Defines url patterns for learning_logs"""
from django.urls import path
from . import views
urlpatterns = [
# Homepage
path('', views.index, name='index'),
path('topics/', views.topics, name='topics'),
#Detail page for single topic
path('topics/<int:topic_id>/', views.topic, name='topic'),
#page for adding a new topic
path('new_topic', views.new_topic, name='new_topic'),
#page for adding a new entry
path('new_entry/<int:topic_id>/', views.new_entry, name='new_entry'),
]
my views.py:
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
from .models import Topic
from .forms import TopicForm, EntryForm
def index(request):
"""The homepage for learning Log"""
return render(request, 'learning_logs/index.html')
def topics(request):
"""show all topics"""
topics = Topic.objects.order_by('date_added')
context = {'topics': topics}
return render(request, 'learning_logs/topics.html', context)
def topic(request, topic_id):
"""Show a single topic and all its entries"""
topic = Topic.objects.get(id=topic_id)
entries = topic.entry_set.order_by('date_added')
context = {'topic':topic, 'entries': entries}
return render(request, 'learning_logs/topic.html', context)
def new_topic(request):
"""Add a new topic"""
if request.method != 'POST':
#No date submitted then create a blank form
form = TopicForm()
else:
# POST data submitted; process date
form = TopicForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('topics'))
context = {'form': form}
return render(request, 'learning_logs/new_topic.html', context)
def new_entry(request, topic_id):
"""add a new entry for a particular topic"""
topic = Topic.objects.get(id=topic_id)
if request.method != 'POST':
#no data submitted; create a blank form
form = EntryForm()
else:
# POST data submitted; process data
form = EntryForm(data=request.POST)
if form.is_valid():
new_entry = form.save(commit=False)
new_entry.topic = topic
new_entry.save()
return HttpResponseRedirect(reverse('topic', args=[topic_id]))
context = {'topic': topic, 'form': form, 'topic_id':topic_id}
return render(request, 'learning_logs/new_entry.html', context)
my new_entry.html:
{% extends "learning_logs/base.html" %}
{% block content %}
<p>{{ topic }}</p>
<p>Add a new entry:</p>
<form action="{% url 'new_entry' topic.id %}" method='post'>
{% csrf_token %}
{{ form.as_p }}
<button name='submit'>add entry</button>
</form>
{% endblock content %}
my base.html:
<p>
Learning Log -
Topics
</p>
{% block content %}{% endblock content %}
index.html:
{% extends "learning_logs/base.html" %}
{% block content %}
<p>Learning Log helps you keep track of your learning, for any topic you're learning about. </p>
{% endblock content %}
my topics.html:
{% extends "learning_logs/base.html" %}
{% block content %}
<p>Topics</p>
<ul>
{% for topic in topics %}
<li>
{{ topic }}
</li>
{% empty %}
<li>No topics have been added yet.</li>
{% endfor %}
</ul>
Add a new topic
{% endblock content %}
my new_topic.html:
{% extends "learning_logs/base.html" %}
{% block content %}
<p>Topics</p>
<ul>
{% for topic in topics %}
<li>
{{ topic }}
</li>
{% empty %}
<li>No topics have been added yet.</li>
{% endfor %}
</ul>
Add a new topic
{% endblock content %}
my topic.html:
{% extends "learning_logs/base.html" %}
{% block content %}
<p>Topic: {{ topic }}</p>
<p>Entries:</p>
<p>
add new entry
</p>
<ul>
{% for entry in entries %}
<li>
<p>{{ entry.date_added|date:'M d, Y H:i' }}</p>
<p>{{ entry.text|linebreaks }}</p>
</li>
{% empty %}
<li>
There are no entries for this topic yet.
</li>
{% endfor %}
</ul>
{% endblock content %}
I'm not sure what's going on. I DID read on the existing threads and followed some suggestions stating that I needed to add 'topic_id':topic on context or provide arguments, and so on, but nothing seems to work. If you would be kind enough to give me an idea of what's going on I would appreciate it.
In your topic.html you have:
add new entry
But you have never passed any topic_id in the context, although you have passed the topic so you can change it to:
add new entry
Try to change this line as:
<form action="{% url 'new_entry' topic_id=topic.id %}" method='post'>
Working thru my 1st python/Django project. Need to let users add new topics to a blog page, but page only returns the bullet points, NO topic names. Works fine on admin back end which of course defeats purpose of user entry"
{% extends 'blog/base.html' %}
{% block content %}
<p>Add a new topic:</p>
<form action="{% url 'blog:new_topic' %}" method='post'>
{% csrf_token %}
{{ form.as_p }}
<button name='submit'>add topic</button>
</form>
{% endblock content %}
```
```
{% extends 'blog/base.html' %}
{% block content %}
<p>BlogPosts</p>
<ul>
{% for topic in blogposts %}
<li>
{{ topic }}
</li>
{% empty %}
<li>Nothing's yet been posted</li>
{% endfor %}
</ul>
Add a new topic:
{% endblock content %}
````
{% extends 'blog/base.html' %}
{% block content %}
<p>Topic: {{ topic }}</p>
<p>Entries:</p>
<ul>
{% for entry in entries %}
<li>
<p>{{ entry.date_added|date:'M d, Y H:i' }}</p>
<p>{{ entry.text|linebreaks }}</p>
</li>
{% empty %}
<li>
There are no entries for this post yet.
</li>
{% endfor %}
</ul>
{% endblock content %}
````
Here are the views:
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponseRedirect
from django.urls import reverse
from .models import BlogPost
from .forms import BlogPostForm
def index(request):
"""The home page for Road Ahead project."""
return render(request, 'blog/index.html')
def blogposts(request):
"""Show all blogposts (in reverse order)."""
blogposts = BlogPost.objects.order_by('-date_added')
context = {'blogposts': blogposts}
return render(request, 'blog/blogposts.html', context)
def topic(request, topic_id):
"""Show a single post and all its entries."""
topic = BlogPost.objects.get(id=topic_id)
entries = topic.entry_set.order_by('date_added')
context = {'topic': topic, 'entries': entries}
return render(request, 'blog/topic.html', context)
def new_topic(request):
"""Add a new topic."""
if request.method != 'POST':
# No data submitted; create a new blank form.
form = BlogPostForm()
else:
# Post data submitted; process data.
form = BlogPostForm(data=request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('blog:blogposts'))
context = {'form': form}
return render(request, 'blog/new_topic.html', context)
````
{% extends 'blog/base.html' %}
{% block content %}
<p>Topic: {{ topic }}</p>
<p>Entries:</p>
<ul>
{% for entry in entries %}
<li>
<p>{{ entry.date_added|date:'M d, Y H:i' }}</p>
<p>{{ entry.text|linebreaks }}</p>
</li>
{% empty %}
<li>
There are no entries for this post yet.
</li>
{% endfor %}
</ul>
{% endblock content %}
Besides the index and base=parent html pages, I have 3 other pages all copied above: blogposts, which lists all bulleted blog topics, topic, which displays topic name and entries, new_topic, which is supposed to allow user topic entry. New_topic appears to be the issue here-I can enter a new topic, and I've not gotten any error messages to troubleshoot, but all I get are bullet points, no topic name. Again it's possible to add topics and content on the back end; not what I want though. Thanks
What is your question, exactly?
Because as it stands, it looks like you're just trying to get us to do your programming for you.
I am learning django, I added a new app,
the link can be displayed in friendly_link.html,
the code is as follows:
admin.py
from django.contrib import admin
from .models import FriendlyLink
admin.site.register(FriendlyLink)
models.py
from django.db import models
class FriendlyLink(models.Model):
title = models.CharField(max_length=100, default='', verbose_name='title')
url = models.CharField(max_length=100, default='', verbose_name='url')
class Meta:
verbose_name_plural = 'links'
def __str__(self):
return self.title
views.py
from django.shortcuts import render
from .models import FriendlyLink
def friendly_link(request):
friendly_link = FriendlyLink.objects.order_by('title')
context = {'friendly_link': friendly_link}
return render(request, 'friendly_link.html', context)
urls.py
from django.urls import re_path
from . import views
urlpatterns = [
re_path(r'^links$', views.friendly_link, name='friendly_link'),
]
friendly_link.html
{% extends "base.html" %}
{% block title %}Links{% endblock %}
{% block content %}
<ul>
{% for link in friendly_link %}
<li>{{ link.title }}</li>
{% empty %}
{% endfor %}
</ul>
{% endblock %}
base.html
{% load i18n static %}<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
...
{% block content %}{% endblock %}
<footer>
<ul>
<!--This code doesn't work-->
{% for link in friendly_link %}
<li>{{ link.title }}</li>
{% empty %}
{% endfor %}
</ul>
</footer>
...
</body>
I want to put the link inside the <footer> element in base.html. How do I change the code? Thank you.
You should really read this documentation page:
https://django-adminlte2.readthedocs.io/en/latest/templates_and_blocks.html
Each block is clickable there and there's a detailed description on how to overwrite each one.
For your problem, you will probably nav_footer
{% block nav_footer %}
{{ block.super }}
...
{% endblock %}
{{ block.super }} is optional and will append your content to the block instead of overwriting it.
I'm trying to figure out a way to build a list of URLs for my content in my django app. I have the Models and Views setup properly, and I already figured out how to access this data in the Templates, but I'm not quite sure how I can start making URLs for them.
The data I have is continents and the countries of these continents. The template should render a list of the continents, but as links.
Here's an example with one continent:
<ul id="continentMenu">
<li>Scandinavia</li>
</ul>
My urls.py looks like
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', include('countrydata.urls')),
url(r'^', include('selectui.urls')),
]
and my index.html looks like
{% extends 'base.html' %}
{% block title %}Home{% endblock %}
{% block content %}
{% if user.is_authenticated %}
Hi {{ user.username }}!
<p>logout</p>
{% else %}
<p>You are not logged in</p>
login
{% endif %}
{% endblock %}
My continentmenu.html, which I'm trying to have the links for the continents in, looks like
{% extends "base.html" %}
{% load staticfiles %}
{% block content %}
<div class="container-fluid">
<div class="l">
{% for continent in all_continents %}
<h1> {{ continent.name }}</h1>
<p> {{ continent.code }}</p>
{% for country in continent.countries.all %}
<p> {{country.name}}</p>
{% endfor %}
{% endfor %}
</div>
</div>
{% endblock %}
At the moment, but I only made it print all the continents and countries as plain text to make sure that I was successfully parsing through the objects (which I was). I'm having trouble at figuring out what kind of instructions I need to put into {% url %}, as my first attempts lead to nothing but errors.
The ajax.js I've been given to work with looks like
/* Run once document ready. */
$(function() {
"use strict";
#continentMenu.
$("#continentMenu a").on("click", function(event) {
event.preventDefault();
var url = $(this).attr("href");
$("#continentName").text($(this).text());
$("#tableContainer").load(url);
});
});
and the views.py looks like
from django.shortcuts import render, get_object_or_404
from countrydata.models import Continent
def show_continent(request, continent_code=None):
context = {
"all_continents": Continent.objects.all()
}
if continent_code:
continent = get_object_or_404(Continent, code=continent_code)
context["continent"] = continent
return render(request, "selectui/index.html", context)
I am making a simple blog app in Django as a learning exercise. I am able to add posts, see them all on the front page, so it is working so far. Where I am having an issue is creating a view that shows the whole post on a separate page. I want to click the title, and go to a page at the url /post/primary key that has the title and body. When I click on the link, I get a page with just the base.html. Not sure where I am missing anything, here are urls.py, views.py, and post.html:
urls.py
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('blog.views',
url(r'^$', 'frontpage'),
url(r'^post/(\d+)/$', 'post'),
)
urlpatterns += patterns('',
url(r'^admin/', include(admin.site.urls)),
)
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404, render_to_response
from blog.models import *
views.py
def frontpage(request):
posts = Post.objects.all().order_by("-created")
paginator = Paginator(posts, 5)
page = request.GET.get('page', '1')
try:
posts = paginator.page(page)
except (InvalidPage, EmptyPage):
posts = paginator.page(paginator.num_pages)
return render_to_response("list.html", dict(posts=posts, user=request.user))
def post(request, pk):
"""Single Post"""
post = Post.objects.get(pk = pk)
d = dict(post=post, user=request.user)
return render_to_response("post.html", d)
post.html
{% extends "base.html" %}
{% block content %}
<div class ="main">
<ul>
{% for post in posts.object_list %}
<div class = "title">{{ post.title }}</div>
<ul>
<div class="time"> {{ post.created }}</div>
<div class ="body"> {{ post.body|linebreaks }}</div>
</ul>
{% endfor %}
</ul>
</div>
{% endblock %}
Thanks in advance for your help.
I am assuming the page.html is actually the post.html you have in yoru codes sample???You no longer have a collection of posts but instead just have 1 post
This needs to change from: (which is looping through your posts)
{% extends "base.html" %}
{% block content %}
<div class ="main">
<ul>
{% for post in posts.object_list %}
<div class = "title">{{ post.title }}</div>
<ul>
<div class="time"> {{ post.created }}</div>
<div class ="body"> {{ post.body|linebreaks }}</div>
</ul>
{% endfor %}
</ul>
</div>
{% endblock %}
To something like (which just displays your single post):
{% extends "base.html" %}
{% block content %}
<div class ="main">
{{ post.title }}
{{ post.created }}
{{ post.body }}
</div>
{% endblock %}
You have to change urls.py to go to a page at the url /post/primary key.
urlpatterns = patterns('blog.views',
url(r'^$', 'frontpage'),
url(r'^post/(?P<pk>\d+)/$', 'post'),
)