I have a ran into a difficulty when navigating between different templates in a Django (v3.2) application. The app is called 'manage_remittance'.
The default landing page (which uses template manage_remittance/templates/manage_remittance/view_remittance.html) for the app should show a list of items (list is not relevant at the moment), and at the top of that list there should be a link, leading to another page in the same app, which would allow to add new items to the list.
The form that is invoked first is here:
manage_remittance/templates/manage_remittance/view_remittance.html
{% extends "root.html" %}
{% load static %}
{% load crispy_forms_tags %}
{% url 'manage_remittance:remittance_add' as remittance_add %}
{% block title %}
VIEW REMITTANCES PAGE
{% endblock title %}
{% block content %}
<div class="list-group col-6">
Click here to add remittance data
</div>
I want to be able to get to another template (manage_remittance/templates/manage_remittance/remittance_add.html), but the {{ remittance_add }} has no value.
In addition, when I specify exact name of the html file (remittance_add.html) in the a href (see above), and click on it, I get a following error:
Using the URLconf defined in sanctions_project.urls, Django tried these URL patterns, in this order:
admin/
[name='login']
login/ [name='login']
logout/ [name='logout']
manage_remittance/ [name='view_remittance']
manage_remittance/ remittance_add/ [name='create_remittance']
^static/(?P<path>.*)$
^media/(?P<path>.*)$
The current path, manage_remittance/remittance_add.html, didn’t match any of these.
What am I doing wrong here?
fragment of urls.py for the project:
urlpatterns = [
path('admin/', admin.site.urls),
path('', login_view, name='login'),
path('login/', login_view, name='login'),
path('logout/', logout_view, name='logout'),
path('manage_remittance/', include('manage_remittance.urls')), # namespace='manage_remittance'
]
urls.py at manage_remittance app:
from .views import (
CreateRemittanceInfo,
RemittanceListView
)
app_name = 'manage_remittance'
urlpatterns = [
path('', RemittanceListView.as_view(), name='view_remittance'),
path('remittance_add/', CreateRemittanceInfo.as_view(), name='create_remittance'),
]
views.py at manage_remittance app:
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from django.views.generic import ListView
from django.views.generic.edit import CreateView
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import Remittance
class CreateRemittanceInfo(LoginRequiredMixin, CreateView):
model = Remittance
fields = ['remittance_text']
template_name_suffix = '_add'
class RemittanceListView(ListView):
model = Remittance
template_name = 'manage_remittance/view_remittance.html'
It seems that you have an issue in your urls:
manage_remittance/ remittance_add/ [name='create_remittance']
the name does not match with
manage_remittance:remittance_add
It seems quite simple: in your template, you should display a list, which is not the case. Have a look at Django User Guide: https://docs.djangoproject.com/fr/3.2/ref/class-based-views/generic-display/
It should look like
{% for object in object_list %}
<p>{{object.remittance_text}}</p>
{% endfor %}
Related
i have one project andromeda where is 2 apps. 1 is blog and seccond one is blogmenu
but when I want to get information from the blog app there is no problem and i can get all information. but when I want to get a menu item from blogmenu I'm getting now error but there is empty navigation bar.
blogmenu urls.py
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
path('', include('blogmenu.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
blogmenu views.py
from django.shortcuts import render
def Blog_Menu(request):
Menu_items = Menu.objects.all()
template_name = 'front/index.html'
return render(request, template_name, {"Menu_items":Menu_items})
blogmenu models.py
from django.db import models
class Menu(models.Model):
Menu_name = models.CharField(max_length=100,blank=True)
Menu_slug = models.SlugField(name="სლაგი",blank=True)
Menu_image = models.ImageField(upload_to="menuimages")
Menu_url = models.CharField(name="url",max_length=100,blank=True,null=True)
class Meta:
verbose_name = "მენიუ"
def __str__(self):
return self.Menu_name
sample html template code
{% for menu in Menu_items %}
<li class="main-menu-item">
just text
</li>
{% endfor %}
When iteration items in loop you should post something. You can do the below in your template.
{% for menu in Menu_items %}
<li class="main-menu-item">
{{ menu.Menu_name }}
</li>
{% endfor %}
Seems to me that you just forgot to use the object from the for loop.
This is probably what your looking for:
{% for menu in Menu_items %}
<li class="main-menu-item">
{{ menu.Menu_name }}
</li>
{% endfor %}
If this isn't working either then I would suggest putting a print(Menu_items) after you make the query in your blogmenu views.py and see if your getting your data there.
Also don't forget to import your model in your views.py.
I just started with a Django project using django-allauth, I configured the basic settings, without using any 3rd party provider. I have set up the urls.py of my project and urls.py of my app.
But on going to http://localhost:8000, I am getting to 'home.html' but how do I remove the navigation of allauth
The following is the urls.py of my project :
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('allauth.urls')),
path('ckeditor/',include('ckeditor_uploader.urls')),
path('',include('blog.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
And this my urls.py of app :
from django.urls import path, include
from . import views
urlpatterns = [
path("", views.PostListView.as_view(), name = 'post_list'),
path("post/add", views.CreatePostView.as_view(), name = "create_new_post"),
]
views.py
from django.shortcuts import render
from django.views.generic import ListView, View
# Create your views here.
from .forms import PostForm, CommentForm
from .models import Post, Comment
class PostListView(ListView):
queryset = Post.objects.filter(is_published=True)
template_name = 'home.html'
class CreatePostView(View):
form_class = PostForm()
template_name = 'create_post.html'
model = Post
home.html
{% extends 'base.html' %}
{% block content %}
<h1>Hello World</h1>
{% for post in post_list %}
<h1>{{post.post_title}}</h1>
<p>{{post.post_body|safe}}</p>
{% endfor %}
{% endblock %}
path("post/add/", views.CreatePostView.as_view(), name = "create_new_post"),
add trailing slash to your url
your global urls.py:
path('',include('blog.urls')),
add something in your app urls.py:
path('test/',views.PostListView.as_view()),
after adding this to your urls.py, run your app again
the extended base.html file may contain the navigation. make changes there to remove or simply remove it
{% extends 'base.html' %}
I'm learning Chapter 18 18.4.2 in Python Crash Course,when i open http://localhost:8000/topics ,I'm using Django 3.0 and python 3.8
shows
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/topics
Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order:
admin/
[name='index']
The current path, topics, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
and this is my code
learning_log\urls.py
from django.contrib import admin
from django.urls import path
from learning_logs import views
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.index,name = 'index')
]
learning_logs\urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',views.index,name = 'index'),
url(r'^topics/$',views.topics,name='topics')
]
views.py
from django.shortcuts import render
from .models import Topic
# Create your views here.
def index(request):
return render(request,'learning_logs/index.html')
def topics(request):
topics = Topic.objects.order_by('date_added')
context = {'topics':topics}
return render(request,'learning_logs/topics.html',context)
base.html
<p>
Learning Log-
Topics
</p>
{% block content %}{% endblock content %}
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>
{% endblock content %}
and runserver shows:
Not Found: /topics
[06/Jan/2020 17:53:15] "GET /topics HTTP/1.1" 404 2077
enter image description here
First of all, good question. Love the detail.
The error is the following
Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order
This means that the url /topics cannot be found. You need to import that url from the app specific urls.py into the main urls.py. This is usually done by something along the lines of
# in main urls.py
from learning_logs.urls import urlpatterns as ll_urlpatterns
# other patterns ...
urlpatterns += ll_urlpatterns
Use below code replace 'app' with your appname.
from django.contrib import admin
from django.urls import path
from learning_logs import views
from django.conf.urls import url, include
urlpatterns = [
path('admin/', admin.site.urls),
url(r'', include(('app.urls', 'app'), namespace='app')),
]
I have looked around and can't really find a solution to my problem. Here is the error django throws. This error is being thrown when on my homepage I have a fiew links that upon clicking should direct you to a details view of said link.
Using the URLconf defined in untitled.urls, Django tried these URL patterns, in this order:
^$
^index/ ^$ [name='index']
^index/ ^(?P<distro_id>[0-9]+)/$ [name='distro_id']
^admin/
The current URL, index//, didn't match any of these.
To my knowledge I don't understand why this error is being thrown.
Here is my urls.py
from django.conf.urls import include, url
from django.contrib import admin
import index.views
urlpatterns = [
url(r'^$', index.views.index),
url(r'^index/', include('index.urls', namespace='index')),
url(r'^admin/', admin.site.urls),
]
My index/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
# /index/
url(r'^$', views.index, name='index'),
#/distro/123/
url(r'^(?P<distro_id>[0-9]+)/$', views.detail, name='distro_id'),
]
My views.py
from django.shortcuts import get_object_or_404, render
from django.template import loader, RequestContext
from django.http import Http404
from .models import Distros
def index(request):
all_distros = Distros.objects.all()
context = {'all_distros': all_distros, }
return render(request, 'index/index.html', context)
def detail(request, distro_id,):
distro_id = get_object_or_404 (Distros, pk=distro_id)
return render(request, 'index/detail.html', {'distro_id': distro_id})
template code:
{% extends 'index/base.html' %}
{% block body %}
<ul>
{% for distro in all_distros %}
<li>{{ index.distro_id }}</li>
{% endfor %}
</ul>
{% endblock %}
I believe those are all the relevent files. I believe everything is setup correctly so I am not sure why the error is being thrown. I'm sure im missing something simple that i'm just overlooking.
Please don't use hardcoded URLs as they are error prone as in your situation. Instead of:
<a href="/index/{{ index.distro.id }}/">
use the url template tag with your namespace (index) and view name (distro_id):
<a href="{% url 'index:distro_id' index.id %}">
Note that you also have an error with index.distro.id as index is actually a Distros object. It has an id field, but not distro.id.
So far I have been able to Create a project and setup a Homepage. So far I have had success with styling the page and getting my nav areas setup. I have also created an app that pulls a list of category names from my database and displays it in a right-justified list. When I point my browser to the app url, it works perfectly, but when I try to include the view in my project it displays the base panel with an error, and the dictionary I passed to the view does not appear to be available.
This is what I get when I load the home url localhost:8000/ in my browser:
This is what I get when I load the app url localhost:8000/categories/ in my browser:
Why am I not able to push the results of my app into my template? Both appear to work but not together?
base_right_panel.html
{% block content %}
<div style="float: right;">
<div id="base_categories" style="margin: 10px; padding-bottom: 10px;">
{% block base_categories %}
{% include "base_categories.html" %}
{% endblock %}
</div>
</div>
{% endblock %}
base_categories.html
{% block content %}
<div class="section" style="float: right;">
<h4 class="gradient">Category List</h4>
<ul>
{% if categories %}
{% for category in categories %}
<li>{{ category.title }}</li>
{% endfor %}
{% else %}
<p>no data! {{ categories|length }}</p>
{% endif %}
</ul>
</div>
{% endblock %}
CategoryList/views.py
from django.views.generic import TemplateView
from CategoryList.models import CategorylistCategorylist #<-- Changed to match inspectdb result
class IndexView(TemplateView):
template_name="base_categories.html" #<-- Changed name from index.html for clarity
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context["categories"] = CategorylistCategorylist.objects.all()
return context
CategoryList/models.py
from django.db import models
class CategorylistCategorylist(models.Model): #<-- Changed to match inspectdb
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=255L, unique=True)
base_url = models.CharField(max_length=255L, unique=True)
thumb = models.ImageField(upload_to="dummy", blank=True) #<-- Ignored inspectdb's suggestion for CharField
def __unicode__(self):
return self.name
# Re-added Meta to match inspectdb
class Meta:
db_table = 'categorylist_categorylist'
CategoryList/urls.py
from django.conf.urls.defaults import patterns, url, include
from django.contrib import admin
from django.conf import settings
from CategoryList import views
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='base_categories'),
)
if settings.DEBUG:
urlpatterns = patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
url(r'', include('django.contrib.staticfiles.urls')),
) + urlpatterns
MySite/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from home import views as home_view
from CategoryList import views as index_view
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', home_view.HomeView.as_view(), name="home"),
url(r'^categories/$', index_view.IndexView.as_view(), name='base_categories'),#include('CategoryList.urls')),
url(r'^admin/', include(admin.site.urls)),
#url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
)
if settings.DEBUG:
urlpatterns = patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
url(r'', include('django.contrib.staticfiles.urls')),
) + urlpatterns
I have another open question which has the relevant code examples but the question differs from what I am asking here.
Is there a simple way to display mysql data in Django template without creating an app?
You need to add the category queryset to your context in your HomeView. Remember, the view uses the templates to build the response - including a template that you also use in a different view (IndexView) does not cause any interaction with IndexView.
HomeView produces its response by rendering a template. If that template uses {% include %} tags to pull in pieces of other templates, those pieces will be rendered using the context established by HomeView. Nothing you do in IndexView has any effect on HomeView, and vice versa.
Continuing to reason by analogy to string interpolation, pretend your templates are global string variables instead of files on disk. Your situation is something like this:
base_categories = "My categories are: %(categories)s."
base_right_panel = "This is the right panel. Here are other fields before categories."
Using the {% include %} tag is something like string concatenation:
base_right_panel = base_right_panel + base_categories
Then your two views are analogous to this:
def home_view(request):
context = {}
return base_right_panel % context
def index_view(request)
context = {'categories': ['a', 'b', 'c']}
return base_categories % context
Unless you add the categories queryset to the context in HomeView, it will not be available to the template engine when rendering the response.
Your HomeView class should include the get_context_data method that you currently have in your IndexView. I am not sure you actually need IndexView at all, unless you want to have something that serves that page with just the categories list.