Django finding URLs for templates - python

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)

Related

python - Django Operational Error, No such table

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

Keep getting "Page not found". What to do?

**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.....

Using page slug to open a specific tab in django template

I'm trying to open a specific bootstrap tab on a webpage using page slugs. For example:
www.mysite.domain/profile/#my_courses
will open profile page with courses history tab active
Here is my code:
urls.py
urlpatterns = [
url(r'^profile/$', views.profile, name='profile'),
url(r'^profile/(?P<page_slug>[\w-]+)/$', views.profile, name='profile'),
]
view.py profile
#login_required
def profile(request, page_slug=None):
profile = UserProfile.objects.get(user__username=request.user.username)
courses = Course.objects.filter(trainer__in = [profile]).order_by('start_time')
trainings = Course.objects.filter(students__in = [profile]).order_by('start_time')
return render(request, 'accounts/profile.html', context = {'courses': courses,
'trainings': trainings,
'page_slug': page_slug,})
profile.html
{% extends 'base.html' %}
{% load staticfiles %}
{% load i18n %}
{% block headers %}
{{ block.super }}
<link rel='stylesheet' href='{% static "accounts/css/profile.css" %}'/>
{% endblock %}
{% block content %}
<ul class='nav nav-tabs navbar-inverse'>
<li class='active'><a href= '#profile' data-toggle='tab'>{% trans 'Profile' %}</a></li>
<li><a href='#trainings' data-toggle='tab'>{% trans 'My Trainings' %}</a></li>
{% if user.profile.is_trainer %}
<li><a href='#courses' data-toggle='tab'>{% trans 'My Courses' %}</a></li>
{% endif %}
</ul>
<div id='content' class='tab-content'>
<div class='tab-pane fade active in' id='profile'></div>
<div class='tab-pane fade' id='my_trainings'>
<ul class='courses__container'></ul>
</div>
{% if user.profile.is_trainer %}
<div class='tab-pane fade' id='courses'>
<ul class='courses__container'></ul>
</div>
{% endif %}
</div>
{% endblock %}
Since javascript on user-side can't understand django template tags I can't do this in javascript. How can I add/remove active class in <li> and <div> tags in django template?
In the URL
www.mysite.domain/profile/#my_courses
#my_courses is a fragment, not a slug. URL fragments only exist in the browser, they are not sent to the web server, and so you URL routing and templates will never see them.
When the user visits that url, what is sent to the server is
www.mysite.domain/profile/
And that's the page that is returned. You'd need JavaScript on the page to inspect the full URL (through document.location.href) and update the page accordingly.
A slug, on the other hand, is not separated by a # character, and forms part of the URL that is sent to the server. That can be seen by Django, and inform the view as to what to render in the template. You would need to redesign your URLs to take advantage of that, though.

Python template include a page if condition

i'm developing a small app with Python and Google app engine. I'm using boilerplate (https://github.com/coto/gae-boilerplate) as front-end which follows gae direction and python templates, so nothing diffrent than plain stuff.
Now, what i would like to have is this.
When a user logged in, if the field of name and last name are not filled in i would like to have, in the home page, the profile editing.
The page for editing the profile is a template (which extend the base.html), called edit_profile.html which works well.
The homepage is a template as well (extend the base.html) called home.html.
Now, can i include the edit_profile.html in home.html? how can i do it?
this is what i've, i don't know what to put instead of ???? i tried with
{% block edit_profile.html %} {% endblock %}
but does not work
{% if user_info.name and user_info.last_name %}
..
{% else %}
????
{% endif %}
thanks.
So you want to include only some block of given template. There are two solutions:
1) Create template just for profile editing form and include it into edit_profile.html. Then include it also into home.html to if condition branch:
profile_form.html:
<form action="{% url some-action %}">
{{ form }}
<input type="submit" value="save"/>
</form
profile_edit.html
{% extends "base.html" %}
{% block main %}
{% include "profile_form.html" %}
{% endblock %}
home.html
{% if user_info.name and user_info.last_name %}
{% include "profile_form.html" %}
{% endif %}
2) use variable for extended template:
profile_form.html
{% extend BASE_TEMPLATE %}
and set it into context w/ different value as needed:
in home.html (let's say included_form.html is some basic template)
{% if user_info.name and user_info.last_name %}
{% with "included_form.html" as BASE_TEMPLATE %}
{% include "edit_profile.html" %}
{% endwith %}
{% endif %}
and if you want show form as a standalone page, set BASE_TEMPLATE to base.html

Problem with django urls which have a hyphen in them

I have a simple set of urls in a Django url conf file which points to some object detail generic views.
urlpatterns = patterns('',
url(r'^projects/(?P<slug>[\w-]+)/$', ProjectDetailView.as_view(), name='view_project'),
url(r'^roles/(?P<slug>[\w-]+)/$', RoleDetailView.as_view(), name='view_role'),
)
The problem is whenever there's a hyphen in the urls (eg:-/projects/new-project/) slug, Djangos development server get stuck. I've checked with pdb and there isn't a problem with parsing the url and getting the object from the database based on the slug. But it gets stuck somewhere when the template gets rendered. I can't figure out the source of the problem. any idea what the problem is?
The view code is,
class ProjectDetailView(DetailView):
model=Project
context_object_name='project_obj'
slug_field='slug'
#method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(ProjectDetailView, self).dispatch(*args, **kwargs)
The template code is,
{% extends "base.html" %}
{% load static %}
{% block static %}
<link rel="stylesheet" type="text/css" href="{% get_static_prefix %}css/demo_table.css">
<script type="application/javascript" src="{% get_static_prefix %}js/users-index.js"></script>
{% endblock %}
{% block content %}
<div id="itemlist">
{% if project_obj %}
<div>
<p>{{ project_obj.title }}</p>
<p>{{ project_obj.description }}</p>
</div>
{% else %}
<p>No Details available.</p>
{% endif %}
<div>
{% endblock %}
After removing some of the tags from the template it started working,
<div id="itemlist">
{% if project_obj %}
<div>
<p>{{ project_obj.title }}</p>
<p>{{ project_obj.description }}</p>
</div>
{% else %}
<p>No Details available.</p>
{% endif %}
<div>
Change [\w-]+ to [-\w]+. For me [\w-]+ never works with python regexp's.
My guess is that you wrote a custom template tag, but it's broken. You're using it in base.html :P

Categories

Resources