**Can someone please help me solve this problem I just started learning Django.
I keep getting getting "PAGE NOT FOUND " whenever i open/click the list/entries
In my "entries" folder i have
Css.md
Django.md
Git.md
Python.md
HTML.md**
screenshot of "Page not found"
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("wiki/<str:entry>", views.entry, name="entry"
views.py
from django import forms
class NewEntryForm(forms.Form):
title = forms.CharField(max_length=100)
content = forms.CharField(widget=forms.Textarea)
def index(request):
return render(request, "encyclopedia/index.html", {
"entries": util.list_entries()
})
def entry(request, entry):
entries = util.get_entry(entry)
if entries is None:
return render(request, "encyclopedia/error.html", {
"message1": "Sorry",
"message2": "your requested page was not found "
})
return render(request, "encyclopedia/index.html", {
"content": entries,
"form": NewEntryForm
})
index.html
{% extends "encyclopedia/layout.html" %}
{% block title %}
Encyclopedia - {{title}}
{% endblock %}
{% block body %}
<h1>All Pages</h1>
<ul>
{% for entry in entries %}
<li></li>
{% endfor %}
</ul>
{% endblock %}
entry.html
{% extends "encyclopedia/layout.html" %}
{% block title %}
Encyclopedia - {{title}}
{% endblock %}
{% block body %}
<div class="container">
<div class="row">
{% if not content%}
<div>Sorry, your requested page was not found </div>
{% else %}
{{ content | safe }}
<div>Edit this entry</div>
{% endif %}
</div>
</div>
{% endblock %}
edit anchor tag in entry.html. URL is given wrong, Do this
<div><a href="{% url 'entry' entry %}>Edit this entry</a></div>
instead of
<div><a href="{% url 'edit' entry %}>Edit this entry</a></div>
you forget to close "".
write this:
<div>Edit this entry</div>
simple.....
Related
I aim to redirect the view after the form has been saved. However django keeps throwing a NoReverseMatch error. Is there a step that I've missed or a misconfiguration?
views.py
def add_carpet(request):
context_dict = {}
carpet_form = forms.CarpetForm()
if request.method == "POST":
carpet_form = forms.CarpetForm(request.POST)
if carpet_form.is_valid():
carpet = carpet_form.save()
return redirect(reverse(
"dashboard_add_images",
kwargs={
"model_type": "carpet",
"id": carpet.id
}
))
context_dict["carpet_form"] = carpet_form
return render(
request,
'dashboard/add_carpet.html',
context_dict
)
def add_images(request, model_type, id):
...
add_images.hml
{% extends 'layouts/dashboard_base.html' %}
{% load django_bootstrap5 %}
{% load static %}
{% block title %}Add Images{% endblock title %}
{% block content %}
<div class="row">
<div class="col justify-content-end">
<h1 class="heading half_space text-muted">
Add Images for the {model}
<span class="divider-left"></span>
</h1>
</div>
</div>
{# Load CSS and JavaScript #}
{% bootstrap_css %}
{% bootstrap_javascript %}
{# Display django.contrib.messages as Bootstrap alerts #}
{% bootstrap_messages %}
{# Display a form #}
<form enctype="multipart/form-data" action="{% url 'dashboard_add_images' %}" method="post" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% bootstrap_button button_type="submit" content="OK" %}
</form>
{% endblock content %}
From above you can see I added the enctype on the form but still no change.
urls.py
urlpatterns = [
path('add_carpet', views.add_carpet, name="dashboard_add_carpet"),
path('add_images/<str:model_type>/<uuid:id>', views.add_images, name="dashboard_add_images"),]
An example redirect url after a form has been submitted is this:
http://127.0.0.1:8000/dashboard/add_images/carpet/97afd259-6ec4-48fc-869f-2a00bbe29c70
Error:
Reverse for 'dashboard_add_images' with no arguments not found. 1 pattern(s) tried: ['dashboard/add_images/(?P<model_type>[^/]+)/(?P<id>[^/]+)$']
I have a view in views.py:
def simple_upload(request):
if request.method == 'POST' and request.FILES['myfile']:
myfile = request.FILES['myfile']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
print(uploaded_file_url)
context = {
'uploaded_file_url': uploaded_file_url
}
return render(request, 'simple_upload.html', context)
return render(request, 'simple_upload.html')
Then, a url in urls.py:
urlpatterns = [
path('', views.project_index, name='project_index'),
path('<int:pk>/', views.project_detail, name='project_detail'),
path('upload/', views.simple_upload, name='upload')
]
And when I hit the route /projects/upload, instead of a form I get an empty page. However, the simple_upload.html route has this structure:
{% extends "base.html" %}
<h1>H</h1>
{% load static %}
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile">
<button type="submit">Upload</button>
</form>
{% if uploaded_file_url %}
<p>File uploaded at: {{ uploaded_file_url }}</p>
{% endif %}
<p>Return to home</p>
{% endblock %}
You can see, I'm getting a blank page.
No errors are occurred.
I figured out the problem. You have to write {% block page_content %} in the template instead of {% block content %}, because in the base.html I have this line:
{% block page_content %}{% endblock %}
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'm spending hours on this thing.
I have a category page, and inside that page there's list of posts that leads to single post page if I click a particular one.
Single post page is working, single category page is working, but a page inside category page is not working, does this make sense?
def post(request, slug):#this is my view
single_post = get_object_or_404(Post, slug=slug)
single_post.views += 1 # increment the number of views
single_post.save() # and save it
t = loader.get_template('main/post.html')
context_dict = {
'single_post': single_post,
}
c = Context(context_dict)
return HttpResponse(t.render(c))
def category(request, category_name_slug):
context_dict = {}
try:
category = Category.objects.get(slug=category_name_slug)
context_dict['category_name'] = category.name
posts = Post.objects.filter(category=category)
context_dict['posts'] = posts
context_dict['category'] = category
except Category.DoesNotExist:
pass
return render(request, 'main/category.html', context_dict)
this is my url
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<slug>[\w|\-]+)/$', views.post, name='post'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/$', views.category, name='category')
]
And this is my category html
{% extends 'base.html' %}
{% block content %}
<h1>{{category_name}}</h1>
{% if category %}
{%if posts %}
<ul>
{% for post in posts %}
<h3>{{ post.title }}</h3>
{% endfor %}
</ul>
{%else%}
<strong>No Pages </strong>
{% endif %}
{% else %}
{{category_name}} does not exist
{% endif %}
{% endblock %}
Finally post.html
<html>
<head>
<title></title>
<head>
<body>
<h2>{{single_post.title}}</h2>
<p>{{single_post.content}}</p>
<p> Views: {{single_post.views}}
<br>
<p>
{% if single_post.image %}
<img src="/media/{{single_post.image}}">
{% endif %}
</p>
<body>
it gives me 404 error, interesting thing is url that's giving me error is 127.0.0.1:8000/category/hello/adele but 127.0.0.1:8000/adele doesn't give me error. so inside category page, i want the access for 127.0.0.1:8000/adele –
replace {{ post.title }} with {{ post.title }}
The issue is if the reference in anchor doesnt starts with / it means its a relative url and that reference is added to current url. Hope this helps you. Also for further reference please use absolute_url feature of django. Please read this :)
Use the url template tag:
{% for post in posts %}
<h3>{{ post.title }}</h3>
{% endfor %}
This reconstruct the url based on your url configuration, ensuring it is a valid url. Here, 'post' is the name of the url you defined in your urlconf, and slug=post.slug is the parameter you pass to the capturing group in your url regex.
I am having trouble getting thumbnails working with sorl.thumbnails.
I am getting no errors.
What I have done:
settings.py
INSTALLED_APPS = {
...
'sorl.thumbnail',
}
THUMBNAIL_DEBUG = True
...
models.py
...
from sorl.thumbnail import ImageField
...
class Upload(models.Model):
article = models.ForeignKey(Article, related_name="uploads")
image = models.ImageField(upload_to=get_image_path, blank=True)
template
{% extends 'layouts/base.html' %}
{% block title %}Home - {{ block.super }}{% endblock %}
{% load staticfiles %}
{% load thumbnail %}
{% block content %}
<section class="main clearfix">
{% for article in articles %}
<div class="work">
<a href="{% url 'article_detail' slug=article.slug %}">
{% for upload in article.uploads.all %}
{% thumbnail article.image "200x200" as im %}
<img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}"class="media" alt=""/>
{% endthumbnail %}
{% endfor %}
<div class="caption">
<div class="work_title">
<h1>{{ article.name }}</h1>
</div>
</div>
</a>
</div>
{% endfor %}
</section><!-- end main -->
{% endblock %}
views.py
...
def index(request):
articles = Article.objects.all().order_by('-featured')
return render(request, 'index.html', {
'articles': articles,
})
def article_detail(request, slug):
#grab the object
article = Article.objects.get(slug=slug)
#grab all object Images
uploads = article.uploads.all()
# pass to the template
return render(request, 'articles/article_detail.html', {
'article': article,
'uploads': uploads,
})
...
urls.py
...
if settings.DEBUG:
urlpatterns += [
url(r'^media/(?P<path>.*)$','django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
]
...
I have been stuck on this for a while. Any help would be greatly appreciated.
Check the following:
does {{ article.image.url }} output anything?
does {{ im.url }} output anything?
is any thumnail created when you load the page? Check your media folder.
are you sure THUMBNAIL_DEBUG is True?
./manage.py shell
from django.conf import settings
print settings.THUMBNAIL_DEBUG
pip freeze => double check the doc for the version you're using
Also, you have an optional image:
image = models.ImageField(upload_to=get_image_path, blank=True)
so you probably want to check if there is an image:
{% if article.image %}
THE THUMBNAIL
{% else %}
A PLACEHOLDER?
{% endif %}
Ah, the image is on your Upload model !
Replace:
{% thumbnail article.image "200x200" as im %}
With:
{% thumbnail upload.image "200x200" as im %}
My other answer stay true though. You need to check if there is an image:
{% if upload.image %}