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/>
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.
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'),
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 %}
How do I provide a search bar in django? My code is as follows...
home.html
<form method='GET' action="">
<input type="text" name="search" placeholder="Search posts"/>
<input type="submit" value="Search"/>
</form>
views.py
def home(request):
posts = Post.objects.all()
search_term = ''
if 'search' in request.GET:
search_term = request.GET['search']
posts = posts.filter(text__icontains=search_term)
context = {
'posts': posts,
'search-term': search_term
}
return render(request, 'feed/home.html', context)
You likely need a function-based view. This is probably a duplicate or semi-related question.
from django.shortcuts import render
from django.db.models import Q
from .models import Posts #or whatever your model is
def search(request):
query = request.GET.get('q','')
#The empty string handles an empty "request"
if query:
queryset = (Q(text__icontains=query))
#I assume "text" is a field in your model
#i.e., text = model.TextField()
#Use | if searching multiple fields, i.e.,
#queryset = (Q(text__icontains=query))|(Q(other__icontains=query))
results = Posts.objects.filter(queryset).distinct()
else:
results = []
return render(request, 'home.html', {'results':results, 'query':query})
#You can also set context = {'results':results, 'query':query} after
#the else: (same indentation as return statement), and
#use render(request, 'home.html', context) if you prefer.
You should be able come up with your own error-handling or redirects as needed. Your urls.py will probably have to be something like:
from django.urls import path
from . import views
urlpatterns = [
path('feed/', views.search, name='home'),
#'feed/' being the name of desired url, 'views.search' the
#name of your func-based view, and "name='home'" the template
#you're using.
]
And your search bar would prob need to look like:
<form method='GET' action=".">
#I believe lowercase get also works
<input type="text" name="q" placeholder="Search posts"/>
<input type="submit" value="{{ query|escape }}"/>
</form>
EDIT: I forgot that you'll want to access the results and display them in your template (you can drop this in under the form for now). Something like:
{% if query %}
{% if results %}
<ul>
{% for item in results %}
<li>{{ item|escape }}</li>
{% endfor %}
</ul>
{% else %}
<p>Query returned no results.</p>
#SO is formatting "Query" in HTML for some reason. Nonetheless...
{% endif %}
{% endif %}
Reason given for failure:
CSRF token missing or incorrect.
I have provided the '{% csrf_token %}' as concerned in this html page but I can't sort the error myself, it's probably out of my understanding about django.
eventcreationform.html
<!DOCTYPE html>
<html lang="en">
<head>
{% csrf_token %}
</head>
<body>
<div class="alert-success">
{% if messages %} {{ message }} {% endif %}
</div>
<div class='container'>
<h1>
{% if user.is_authenticated %}
{{ user.username }} !
{% endif %} Please fill this form:
</h1>
<h3>
<form method='POST' enctype="text/plain"> {% csrf_token %} {{ form }}
<button type='submit' class='btn btn-default'>Submit</button>
</form>
</h3>
</div>
</body>
</html>
forms.py
...
class EventForm(forms.ModelForm):
event_name = forms.CharField(label='Name')
event_date_time = forms.DateTimeField(label='Date and Time',
widget=forms.DateTimeInput)
address = forms.CharField(label='Address')
class Meta:
model = CreatedEvent
fields = ('event_name', 'event_date_time', 'address')
...
urls.py
from django.conf.urls import url
from django.views.generic import TemplateView
from rest_framework.urlpatterns import format_suffix_patterns
from api import views
from django.conf import settings
from django.conf.urls.static import static
app_name = 'api'
urlpatterns = [
....
url(r'^register/', views.Register.as_view(), name='register'),
url(r'^eventform/', views.EventCreationForm.as_view(), name='eventform'),
....
]
urlpatterns = format_suffix_patterns(urlpatterns)
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_ROOT, document_root=settings.MEDIA_ROOT)
views.py
....
class EventCreationForm(View):
template_eventcreationform = 'eventcreationform.html'
form_class = EventForm
def get(self, request):
form = self.form_class(None)
return render(request, self.template_eventcreationform, {'form':
form})
def post(self, request):
# data is here
form = self.form_class(request.POST)
if form.is_valid():
event = form.save(commit=False)
user = request.user.objects
form.user = user.email
event_name = form.cleaned_data.get('event_name')
event_date_time = form.cleaned_data.get('event_date_time')
event_address = form.cleaned_data.get('address')
event.save()
message = 'Event added'
return render(request, 'base.html', {'message': message})
else:
message = 'Invalid form data, try again'
form = self.form_class(None)
return render(request, self.template_eventcreationform,
{'message': message, 'form': form})
....
The error is gone, i think the issue was with 'enctype=text/plain-text' and i just removed it.