Im currently following a Django tutorial to learn views and URLs. I have watched the tutorial over and over and cant see what I am doing wrong.
I receive the error:
Exception Value:
Reverse for 'list-events' not found. 'list-events' is not a valid view function or pattern name.
Views.py
from django.shortcuts import render, redirect
import calendar
from calendar import HTMLCalendar
from datetime import datetime
from .models import Event, Venue
from .forms import VenueForm, EventForm
from django.http import HttpResponseRedirect
# Create your views here.
# all events is listed in the urls.py hence why the function is named all_events
def update_event(request, event_id):
event = Event.objects.get(pk=event_id)
form = EventForm(request.POST, instance=event)
if form.is_valid():
form.save()
return redirect('list-events')
return render(request, 'events/update_event.html',
{'event': event,
'form':form})
def add_event(request):
submitted = False
if request.method == 'POST':
form = EventForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/add_event?submitted=True')
else:
form = EventForm
if 'submitted' in request.GET:
submitted = True
return render(request, 'events/add_event.html', {'form': form, 'submitted': submitted})
def update_venue(request, venue_id):
venue = Venue.objects.get(pk=venue_id)
form = VenueForm(request.POST, instance=venue)
if form.is_valid():
form.save()
return redirect('list-venues')
return render(request, 'events/update_venue.html',
{'venue': venue,
'form': form})
def search_venues(request):
if request.method == "POST":
searched = request.POST['searched']
venues = Venue.objects.filter(name__contains=searched)
return render(request,
'events/search_venues.html',
{'searched': searched,
'venues': venues})
else:
return render(request,
'events/search_venues.html',
{})
def show_venue(request, venue_id):
venue = Venue.objects.get(pk=venue_id)
return render(request, 'events/show_venue.html',
{'venue': venue})
def list_venues(request):
venue_list = Venue.objects.all()
return render(request, 'events/venue.html',
{'venue_list': venue_list})
URLS.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('<int:year>/<str:month>/', views.home, name="home"),
path('events', views.all_events, name='list_events'),
path('add_venue', views.add_venue, name='add-venue'),
path('list_venues', views.list_venues, name='list-venues'),
path('show_venue/<venue_id>', views.show_venue, name='show-venue'),
path('search_venues', views.search_venues, name='search-venues'),
path('update_venue/<venue_id>', views.update_venue, name='update-venue'),
path('add_event', views.add_event, name='add-event'),
path('update_event/<event_id>', views.update_event, name='update-event'),
event_list.html:
{% extends 'events/base.html' %}
{% block content %}
<h1>Event </h1>
<br />
{% for event in event_list %}
<div class="card">
<div class="card-header">
{{Event}}
</div>
<div class="card-body">
<h5 class="card-title">Venue: {{ event.venue }}</h5>
<p class="card-text">
<ul>
<li>Date: {{ event.event_date }}</li>
<li>Event Venue: {{ event.venue.web }}</li>
<li>Manager: {{ event.manager }}</li>
<li>Desc: {{ event.description }}</li>
<li>Attendees:<br />
{% for user in event.attendees.all %}
{{ user }}<br/>
{% endfor %}
</li>
</ul>
</p>
</div>
<div class="card-footer text-muted">
Update Event
</div>
</div>
<br /><br />
{% endfor %}
{% endblock %}
You have defined your url in the "urls.py" file with the name of "list_events" (note the underscore). In the views you have used it as "list-events" (note the hyphen).
You can fix that by following one of these options:
1.You can change that in the views (by using underscore instead of hyphen):
return redirect('list_events')
2.Or changing it in the url (by using hyphen instead of underscore):
path('events', views.all_events, name='list-events'),
Related
In my ToDoApp, I couldn't send the ID to my function. Not sure what mistake I'm making.
Seems my function is correct because when I tested the form action with "datechange/1". It worked.
Here is my code:
Index.html
{% extends 'base.html' %}
{% block content %}
<h3 style = "margin-bottom: 20px"><strong>To Do List App</strong></h3>
<form method="POST" action="datechange/{{task.id}}">
{%csrf_token%}
<ul class="list-group">
{% for task in tasklist %}
<li class="list-group-item d-flex justify-content-between align-items-center">
<input type='hidden' name = {{task.id}}>{{task.tasks}}
<span class="badge bg-primary rounded-pill">{{task.duedate}}
<input type="date" name="datepick"/>
<input type='submit' value = 'Update'>
</span>
</li>
{% endfor %}
</form>
Views.py
def index(request):
tasklist = Task.objects.all()
return render(request, 'index.html', {'tasklist':tasklist})
def datechange(request,id):
# taskid = request.POST.get(id='task.id')
# task = Task.objects.get(id=taskid)
task = Task.objects.get(id=id)
datepick = request.POST.get('datepick')
task.duedate = datepick
task.save()
return HttpResponseRedirect(reverse('index'))
Urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.index,name='index'),
path('datechange/<int:id>',views.datechange,name='datechange'),
]
Don't use action in form like that, Django has a better behaviour for such simple forms. The view datechange is also not needed. Just put everything from that view into if request.method == "POST" like that:
def index(request):
if request.method == "POST":
task_id = request.POST.get("task_id")
task = Task.objects.get(id=task_id)
datepick = request.POST.get('datepick')
task.duedate = datepick
task.save()
tasklist = Task.objects.all()
return render(request, 'index.html', {'tasklist':tasklist})
And delete action from your form in template:
<form method="POST">
{%csrf_token%}
<input type="hidden" name="task_id" value="{{ task.id }}">
...
Submitting the form will render index again, but also will process everything in POST you have inside that view. If you just open it (GET method) it will ignore that processing opening the view in a standard way.
This is the error I get when clicking on Edit post under any one of the posts. Would appreciate any help as all this django stuff is confusing me but trying my best to learn. My new post function works and clicking blog/posts to go to the overview page for the blog or to look at all the posts works as well.
NoReverseMatch at /edit_post/1/
Reverse for 'posts' with arguments '(1,)' not found. 1 pattern(s) tried: ['posts/$']
Error during template rendering
In template C:\Users\seng\Desktop\Python projects\c19\nineteen_one\blogs\templates\blogs\base.html, error at line 0
urls.py
"""Defines url paterns for blogs"""
from django.urls import path
from . import views
app_name = 'blogs'
urlpatterns =[
#Home page
path('', views.index, name='index'),
# Page that shows all posts/
path('posts/', views.posts, name='posts'),
#Page for adding a new blogpost
path('new_post/', views.new_post, name='new_post'),
#Page for editing a post
#maybe remove the id?
path('edit_post/<int:post_id>/', views.edit_post, name='edit_post'),
]
views.py
from django.shortcuts import render, redirect
from .models import BlogPost
from .forms import BlogPostForm
# Create your views here.
def index(request):
"""The home page for blogs"""
return render(request, 'blogs/index.html')
def posts(request):
"""Show all blogposts"""
posts = BlogPost.objects.order_by('date_added')
context = {'posts': posts}
return render(request, 'blogs/posts.html', context)
def new_post(request):
"""Add a new blogpost"""
if request.method != 'POST':
#No data submitted; create a blank form.
form = BlogPostForm()
else:
#POST data submitted, process data
form = BlogPostForm(data=request.POST)
if form.is_valid():
form.save()
return redirect('blogs:posts')
#Display a blank or invalid form
context = {'form': form}
return render(request, 'blogs/new_post.html', context)
def edit_post(request, post_id):
"""Edit existing post"""
post = BlogPost.objects.get(id=post_id)
if request.method != "POST":
#Initial request, pre-fill form with the current post
form = BlogPostForm(instance=post)
else:
#Post data submitted, process data
form = BlogPostForm(instance=post, data=request.POST)
if form.is_valid():
form.save()
return redirect('blogs:posts', post_id=post.id)
context = {'post':post, 'form':form}
return render(request, 'blogs/edit_post.html', context)
forms.py
from django import forms
from .models import BlogPost
class BlogPostForm(forms.ModelForm):
class Meta:
model = BlogPost
fields = ['text', 'title']
labels = {'text':'This is the text box', 'title' :"Title here"}
edit_post.html
{% extends "blogs/base.html" %}
{% block content %}
<p>{{ post }}</p>
<p>Edit post:</p>
<form action="{% url 'blogs:edit_post' post.id %}" method='post'>
{% csrf_token %}
{{ form.as_p }}
<button name="submit">Save changes</button>
</form>
{% endblock content %}
posts.html
{% extends "blogs/base.html" %}
{% block content %}
<p>Posts</p>
<ul>
{% for post in posts %}
<li>
<p>{{ post }}</p>
<p>
Edit post
</p>
</li>
{% empty %}
<li>No posts have been added yet.</li>
{% endfor %}
</ul>
Add a new post
{% endblock content %}
new_post.html
{% extends "blogs/base.html" %}
{% block content %}
<p>Add a new post:</p>
<form action="{% url 'blogs:new_post' %}" method='post'>
{% csrf_token %}
{{ form.as_p }}
<button name="submit">Add post</button>
</form>
{% endblock content %}
The issue is with this line in edit_post.html:
<p>{{ post }}</p>
If you are editing the post with id 1, then this link is to the url /posts/1. But that has no match in your urls.py file.
Either you need to remove the post.id parameter from the link, or create a view and a corresponding path in urls.py for this link.
I'm trying to make a website that lets visitors search for books using another search engine. I have a script that takes a query, and returns some HTML with the results of the search, but I'm struggling to make a front end for this. I am using django because it seemed like the best option when I started, but now I am going in circles and I can't figure out how to make this thing - I'm just getting overwhelmed because the different tutorials and documentation that I'm reading all go into the advanced stuff before I can get the basic thing working.
Do I need separate search and results templates? Right now I'm getting the error The view book_search.views.search didn't return an HttpResponse object. It returned None instead.
How can I fix this error and/or design this whole thing better?
Here's what I have so far (the script that returns the results in html is pull.py):
The views and urls are from inside the book_search app.
views.py:
from django.shortcuts import render
from django.http import HttpResponse
from . import pull
from .forms import SearchForm
def index(request):
return HttpResponse("Welcome to the index page")
def test_search(request):
context = {'query': 'test query'}
return render(request, 'book_search/search.html', context)
def search(request):
if request.method == "GET":
form = SearchForm(request.GET)
if form.is_valid():
query = form.cleaned_data['query']
results = pull.main(query)
context = {'query': query, 'form': form, 'results': results}
return render(request, 'book_search/results.html', context)
apps.py:
from django.apps import AppConfig
class BookSearchConfig(AppConfig):
name = 'book_search'
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('index', views.index, name='index'),
path('test', views.test_search, name='test_search'),
path('', views.search, name='search'),
]
forms.py:
class SearchForm(forms.Form):
query = forms.CharField(label='Search', max_length=200)
template base.html:
<html>
<head>
</head>
<body>
<form method="GET" action="/search/">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
{% block content %}{% endblock %}
</body>
</html>
template results.html:
{% block content %}
{% results %}
{% endblock content %}
Since we guessed that form isn't valid (because no POST handler - you do not send anything to the form) and wrong indentation gives None response, now you can fix reference before assignment:
def search(request):
if request.method == "GET":
form = SearchForm()
context = {'form': form}
elif request.method == "POST":
form = SearchForm(request.POST)
if form.is_valid():
query = form.cleaned_data['query']
results = pull.main(query)
context = {'query': query, 'form': form, 'results': results}
return render(request, 'book_search/results.html', context)
and render errors in results.html template by putting this:
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
I am relatively new to django and i'm trying to implement some modelforms.
My page consists of two views, a Politics section and a Sports section, each one with the same form for making comments (my comment model is named Comentario). It has a field for the content and a field for the section the comment belongs to. Both views are basically the same so I'm going to showcase just the politics one:
from django.contrib import messages
from django.shortcuts import render
from django.views.generic import CreateView
from usuarios.models import Usuario
from .forms import CrearComentario
from .models import Comentario
usuarios = Usuario.objects.all()
comentarios = Comentario.objects.all()
pag = ''
def politics(request):
if request.user.is_authenticated:
if request.method == 'POST':
form = CrearComentario(request.POST, instance=request.user)
if form.is_valid():
messages.success(request, 'Publicado!')
pag = 'politics'
form.save()
form = CrearComentario()
else:
form = CrearComentario(request.POST,instance=request.user)
else:
messages.warning(request, 'Comentario no válido')
form = CrearComentario(request.POST)
return render(request, 'main/politics.html', {'usuarios': usuarios,
'comentarios': comentarios,
'form': form})
In case you're wondering, 'pag' is a control variable that is checked by my signals.py file to update the 'pagina' field
I had trouble with the submit buttons in my custom modelsforms, the form displays correctly, and when I write something in the form and submit it, it displays a success message but the comment doesn't appear in the comment section and it doesn't appear in the django shell either.
politics.html
{% extends 'main/base.html' %}
{% load static %}
{% load crispy_forms_tags %}
<!-- Here would be the content-->
{% block comentarios %}
<h3>Comentarios</h3>
<ul class="a">
{% for comment in comentarios %}
{% if comment.pagina == 'politics' %}
<li>
<span>{{ comment.contenido }}</span>
<br>
<small>{{ comment.usuario }} , {{ comment.fecha }}</small>
<hr>
<br>
</li>
{% endif %}
{% endfor %}
</ul>
{% if user.is_authenticated %}
<form method="POST" enctype="multipart/form-data" action="http://localhost:8000/main/politics/">
{% csrf_token %}
<fieldset class="form-group">
<legend>Dejanos tu opinion</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">OK</button>
</div>
</form>
{% else %}
<legend>Inicia sesión para poner comentarios</legend>
{% endif %}
{% endblock %}
My forms.py looks like this:
from django import forms
from .models import Comentario
class CrearComentario(forms.ModelForm):
contenido = forms.CharField(max_length = 250, required=False, widget=forms.Textarea)
pagina = forms.CharField(max_length = 250, required=False, widget=forms.HiddenInput())
class Meta:
model = Comentario
fields = ['contenido', 'pagina']
The field that determines to which section the comment belongs to ('pagina') is hidden because it's meant to be set by my signals.py file:
from django.db.models.signals import pre_save
from django.dispatch import receiver
from .models import Comentario
from .views import pag
from .forms import CrearComentario
#receiver(pre_save, sender=Comentario)
def fijar_pagina(sender, instance, **kwargs)
if pag:
instance.pagina = pag
pag = ''
instance.save(update_fields['pagina'])
I'm not getting any error message, and everything behaves like it should except for the fact that comments aren't being saved
I tried too a commit==False save instead of the signals but it was just as ineffective:
def politics(request):
if request.user.is_authenticated:
if request.method == 'POST':
form = CrearComentario(request.POST, instance=request.user)
if form.is_valid():
messages.success(request, 'Publicado!')
pag = 'politics'
comentario = form.save(commit=False)
comentario.pagina = 'sonsol'
comentario.save()
form = CrearComentario()
else:
form = CrearComentario(request.POST,instance=request.user)
else:
messages.warning(request, 'Comentario no válido)
form = CrearComentario(request.POST)
return render(request, 'main/politics.html', {'usuarios': usuarios,
'comentarios': comentarios,
'form': form})
usuarios and comentarios have both been defined at the module (file) level. As such they will not update for the lifetime of the process.
You should move both of these into the view body so that the query is run on every request
usuarios = Usuario.objects.all()
comentarios = Comentario.objects.all()
return render(request, 'main/politics.html', {'usuarios': usuarios,
'comentarios': comentarios,
'form': form})
I'm sure I'm doing something really obviously wrong, but I can't see it.
I've made a simple form for a Django app, but it's only returning the csrf token, not the field value. The form submits fine, but there's no 'event-title' key/value pair in the QueryDict.
To be precise, when I log the QueryDict, it looks like this:
<QueryDict: {u'csrfmiddlewaretoken': [u'dpXmMHTE3WmQvdvrAUD4oFer2WfKEjWd']}>
create_event.html:
{% extends "basic-layout.html" %}
{% block maincontent %}
<h1>Create Event</h1>
{% if error_message %}<p>{{ error_message }}</p>{% endif %}
<form action="/create-event" method="post">{% csrf_token %}
<label for="event-title">Event title</label>
<input type="text" title="event-title" id="event-title" required/>
<input type="submit" value="create event"/>
</form>
{% endblock %}
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.views.decorators.csrf import csrf_exempt
import views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.listEvents),
url(r'^create-event', csrf_exempt(views.createEvent))
]
views.py
def createEvent(request):
if request.method == 'GET':
template = loader.get_template('create_event.html')
context = RequestContext(request, {})
return HttpResponse(template.render(context))
if request.method == 'POST':
logger = logging.getLogger('degub')
logger.info(request.POST)
event_title = request.POST.get('event-title', '')
if event_title:
event = Event(event_title)
c = {}
c.update(csrf(request))
template = loader.get_template('list_events.html')
context = RequestContext(request, c)
return HttpResponse(template.render(context))
else:
template = loader.get_template('create_event.html')
template_values = {"error_message": "Nope, didn't work"}
context = RequestContext(request, template_values)
return HttpResponse(template.render(context))
Try adding the name attribute in your input tag.
<input type="text" name="event-title" title="event-title" id="event-title" required/>