404 Page not found Django even though it is in urls.py - python

I don't know why I am getting a 404 error on the page flights/1 when clearly, I have a url pattern for
<int:flight_id> (flights is a app). Help!
My urls.py for the project
from django.contrib import admin
from django.urls import path
from django.urls import include
urlpatterns = [
path('admin/', admin.site.urls),
path('flights/', include('flights.urls'))
]
My urls.py for the flights app
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("<int:flight_id>", views.flight, name="flight"),\
]
And the views.flight
def flight(request, flight_id):
flight = Flight.objects.get(id=flight_id)
return render(request, "flights/flight.html", {
"flight": flight,
"passengers": flight.passengers.all(),
"non_passengers": Passenger.objects.exclude(flights=flight).all()
})
Template
{% extends "flights/layout.html" %}
{% block body %}
<h1>Flight {{ flight.id }}</h1>
<ul>
<li>Origin: {{ flight.origin }}</li>
<li>Destination: {{ flight.destination }}</li>
<li>Duration: {{ flight.duration }}</li>
</ul>
<h2>Passengers</h2>
<ul>
{% for passenger in passengers %}
<li>{{ passenger }}</li>
{% empty %}
<li>No passengers.</li>
{% endfor%}
</ul>
<h2>Add Passenger</h2>
<form method="POST" action="{% url 'flight' flight.id book %}">
{% csrf_token %}
<select name="passengers">
{% for passenger in non_passengers %}
<option value="{{ passenger.id }}">{{ passenger }}</option>
{% endfor %}
</select>
</form>
Back to Flight List
{% endblock %}
With layout.html being html boilerplate code

Related

django.contrib.auth.urls change redirect path

I am coding a basic login and register page app in Django/Python
Currently, after someone logs in, it redirects them back to the register page. I am trying to change the redirect path to "home/"
Please see the following code:
URLS.PY:
from django.contrib import admin
from django.urls import path , include
from accounts import views as v
from main import views as views
urlpatterns = [
path('admin/', admin.site.urls),
path('home/' , views.home , name = 'home'),
path('', v.register , name='register'),
path('' , include('django.contrib.auth.urls') , name = 'login'),
]
Views.py:
from django.shortcuts import render , redirect
from .forms import RegisterForm
# Create your views here.
def register(response):
if response.method == "POST":
form = UserCreationForm(response.POST)
if form.is_valid():
form.save()
return redirect("/home")
else:
form = RegisterForm()
return render(response, "registration/register.html", {"form":form})
Login.html
{% extends "main/base.html"%}
{% block title %}
Login here
{% endblock %}
{% load crispy_forms_tags %}
{% block content %}
<form class="form-group" method="post">
{% csrf_token %}
{{ form|crispy }}
<p>Don't have an account ? Create one </p>
<button type="submit" class="btn btn-success">Login</button>
</form>
{% endblock %}
Register.html
{% extends "main/base.html"%}
{% block title %}Create an Account{% endblock %}
{% load crispy_forms_tags %}
{% block content %}
<form method="POST" class="form-group">
{% csrf_token %}
{{ form|crispy }}
<p>Already have an account? Login here</p>
<button type="submit" class="btn btn-success">Register</button>
</form>
{% endblock %}
You can use this in settings.py file to redirect user after login :-
LOGIN_REDIRECT_URL = 'home/'

module 'search.views' has no attribute 'search'

I'm using the wagtail cms to do a search. I'm using the default search in the /search folder. When I preform a search I get the following exception thrown at me.
AttributeError at /search/
module 'search.views' has no attribute 'search'
This is my views.py
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.shortcuts import render
from wagtail.core.models import Page
from wagtail.search.models import Query
def search(request):
search_query = request.GET.get('query', None)
page = request.GET.get('page', 1)
# Search
if search_query:
search_results = Page.objects.live().search(search_query)
query = Query.get(search_query)
# Record hit
query.add_hit()
else:
search_results = Page.objects.none()
# Pagination
paginator = Paginator(search_results, 10)
try:
search_results = paginator.page(page)
except PageNotAnInteger:
search_results = paginator.page(1)
except EmptyPage:
search_results = paginator.page(paginator.num_pages)
return render(request, 'search/search.html', {
'search_query': search_query,
'search_results': search_results,
})
This is my template/search/search.html
{% extends "base.html" %}
{% load static wagtailcore_tags %}
{% block body_class %}template-searchresults{% endblock %}
{% block title %}Search{% endblock %}
{% block content %}
<h1>Search</h1>
<form action="{% url 'search' %}" method="get">
<input type="text" name="query"{% if search_query %} value="{{ search_query }}"{% endif %}>
<input type="submit" value="Search" class="button">
</form>
{% if search_results %}
<ul>
{% for result in search_results %}
<li>
<h4>{{ result }}</h4>
{% if result.search_description %}
{{ result.search_description }}
{% endif %}
</li>
{% endfor %}
</ul>
{% if search_results.has_previous %}
Previous
{% endif %}
{% if search_results.has_next %}
Next
{% endif %}
{% elif search_query %}
No results found
{% endif %}
{% endblock %
}
I'm getting the following error when I preform a search
AttributeError at /search/
module 'search.views' has no attribute 'search'
URLS.py
from search import views as search_views
urlpatterns = [
url(r'^django-admin/', admin.site.urls),
url(r'^admin/', include(wagtailadmin_urls)),
url(r'^documents/', include(wagtaildocs_urls)),
url(r'^search/$', search_views.search, name='search'),
url(r'sitemap.xml', sitemap),
url(r'^wagtail-transfer/', include(wagtailtransfer_urls)),
]
Directory Structure
I don't see any error. What I'm assuming you have a django package by the same name 'search' installed. So I think changing your app name would resolve your problem.
On the other hand you can separate app urls from main urls and use relative import.
To do that you have to do
create a file named urls.py in your search app.
from django.urls import path
from . import views as search_view
urlpatterns = [
path('', search_views.search, name='search')
]
include urls.py(form search) in your main urls.py
#from search import views as search_views
urlpatterns = [
url(r'^django-admin/', admin.site.urls),
url(r'^admin/', include(wagtailadmin_urls)),
url(r'^documents/', include(wagtaildocs_urls)),
url(r'^search/', include('search.urls')),
url(r'sitemap.xml', sitemap),
url(r'^wagtail-transfer/', include(wagtailtransfer_urls)),
]

Unclosed for tag in django. Looking for one of: empty, endfor

The error references {% for film in form %} not being closed in: form-template.html:
{% for field in form %}
{{field.errors}}
<label>{{ field.label_tag }}</label>
{{ field }}
{$ endfor %}
My comment_form.html:
<form action="" method="post">
{$ csrf_token %}
{% include 'films/form-template.html' %}
<button type="submit">Submit</button>
</form>
urls.py:
app_name = 'films'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
# path('<int:film_id>/comment', views.add_comment, name='add_comment'),
path('<int:pk>', views.DetailView.as_view(), name='detail'),
path('<int:film_id>/add/$', views.CommentCreate.as_view(), name='add_comment'),
]
You have an error in the end tag of your for loop.
{$ endfor %}
Should be
{% endfor %}

Syntax error in urls.py

I was trying to add an editing/deleting function for a bookmarks app.
I get the following error:
My Urls.py file is the following:
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('',
# Examples:
# url(r'^$', 'myproject.views.home', name='home'),
# url(r'^myproject/', include('myproject.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'bookmarks.views.index', name='home'),
url(r'^bookmarks/$', 'bookmarks.views.index', name='bookmarks_view'),
url(r'^tags/([\w-]+)/$', 'bookmarks.views.tag'),
url(r'^login/$', 'django.contrib.auth.views.login'),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'})
url(r'^delete/(\d+)/$', 'bookmarks.views.delete'),
url(r'^edit/(\d+)/$', 'bookmarks.views.edit'),
)
The views.py file:
...remaining code
def delete(request, bookmark_id):
if request.method == 'POST':
b = get_object_or_404(Bookmark, pk=int(bookmark_id))
b.delete()
return redirect(index)
def edit(request, bookmark_id):
b = get_object_or_404(Bookmark, pk=int(bookmark_id))
context = {
'form' : BookmarkForm(instance=b),
}
return render(request, 'edit.html', context)
The bookmark widget in index.html
{% block bookmark_widget %}
{% if request.user %}
<div id="new-bookmark-widget">
<form method="post" action="{% url bookmarks.views.index %}">
{% csrf_token %}
<h3>Bookmark</h3>
{{ form.as_p }}
<p><button id="new-bookmark-submit">Submit</button>Submit</button>
</form>
</div>
{% endif %}
{% endblock %}
The relevant div in base.html
<div id="container">
<div id="header">
{% block bookmark_widget %}
{% endblock %}
<div id="authentication">
{% if user.is_authenticated %}
Hi {{user}}! Logout
{% else %}
Login
{% endif %}
</div>
<h1>My bookmarking app</h1>
</div>
<div id="content">
<h2>{% block subheader %}{% endblock %}</h2>
{% block content %}
Sample content -- you should never see this, unless an inheriting template fails to have any content block!
{% endblock %}
</div>
<div id="footer">
All copyrights reserved
</div>
</div>
The complete bookmark.html file:
<li>
<a class="bookmark-link" href="{{ bookmark.url }}">{% if bookmark.title %}{{ bookmark.title }}{% else %}{{ bookmark.url }}{% endif %}</a>
<div class="metadata"><span class="author">Posted by {{ bookmark.author }}</span> | <span class="timestamp">{{ bookmark.timestamp|date:"Y-m-d" }}</span>
{% if bookmark.tag_set.all %}| <span class="tags">
{% for tag in bookmark.tag_set.all %}
{{ tag.slug }}</span>
{% endfor %}
{% endif %}
</div>
{% if request.user.is_authenticated %}
<div class="actions"><form method=="POST" action="{% url bookmarks.view.delete bookmark.id %}>
{% csrf_token %}
<input type="submit" value="Delete">
</form> </div>
{% endif %}
I am new to Django, how do I handle error mistakes and how do I find the problem? I couldnt see it from the error message.
Thank you!
missing a comma on the following line:
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}), <-add here
I presume your comments section also lines up with the rest of your code and it is formatted incorrectly in your question
You're missing a comma at the end of this line:
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'})

Reverse for '' with arguments '(1L,)' and keyword arguments '{}' not found

I'm new to Django and faced with next problem: when I turn on the appropriate link I get next error:
NoReverseMatch at /tutorial/
Reverse for 'tutorial.views.section_tutorial' with arguments '(1L,)' and keyword arguments '{}' not found.
What am I doing wrong? and why in the args are passed "1L" instead of "1"? (when i return "1" i get same error.) I tried to change 'tutorial.views.section_tutorial' for 'section-detail' in my template but still nothing has changed. Used django 1.5.4, python 2.7; Thanks!
tutorial/view.py:
def get_xhtml(s_url):
...
return result
def section_tutorial(request, section_id):
sections = Section.objects.all()
subsections = Subsection.objects.all()
s_url = Section.objects.get(id=section_id).content
result = get_xhtml(s_url)
return render(request, 'tutorial/section.html', {'sections': sections,
'subsections': subsections,
'result': result})
tutorial/urls.py:
from django.conf.urls import patterns, url
import views
urlpatterns = patterns('',
url(r'^$', views.main_tutorial, name='tutorial'),
url(r'^(?P<section_id>\d+)/$', views.section_tutorial, name='section-detail'),
url(r'^(?P<section_id>\d+)/(?P<subsection_id>\d+)/$', views.subsection_tutorial, name='subsection-detail'),
)
urls.py:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^tutorial/$', include('apps.tutorial.urls')),
)
main.html:
{% extends "index.html" %}
{% block content %}
<div class="span2" data-spy="affix">
<ul id="menu">
{% for section in sections %}
<li>
{{ section.name }}
<ul>
{% for subsection in subsections%}
{% if subsection.section == section.id %}
<li><a href=#>{{ subsection.name }}</a></li>
{% endif %}
{% endfor %}
</ul>
{% endfor %}
</li>
</ul>
</div>
<div class="span9">
<div class="well">
{% autoescape off%}
{{ result }}
{% endautoescape %}
</div>
</div>
{% endblock %}
You don't need $ identifier in url regex in your main urls file when including app urls:
url(r'^tutorial/$', include('apps.tutorial.urls')),
should be:
url(r'^tutorial/', include('apps.tutorial.urls')),

Categories

Resources