I have this add page which uses a django form to get information which i am trying to store within "tasks" list and display in the todo html page.
i believe all my syntax is correct but it is not displaying the list of tasks when I submit the form.
on cmd it detects a GET request every time i submit the form, shouldnt it be saying post?
views:
from django.shortcuts import render
from django import forms
tasks = []
class newTaskForm(forms.Form):
task = forms.CharField(label="new task")
# Create your views here.
def index(request):
return render(request, "tasks/todo.html", {
"tasks": tasks
})
def add(request):
if request.method == "POST":
form = newTaskForm(request.POST)
if form.is_valid():
task = form.cleaned_data["task"]
tasks.append(task)
else:
return render(request, "tasks/add.html", {
"form": form
})
return render(request, "tasks/add.html", {
"form": newTaskForm
})
add:
{% extends "tasks/layout.html" %}
{% block body %}
<form action="{% url 'tasks:add' %}">
{% csrf_token %}
{{ form }}
<input type="submit">
</form>
Veiw list
{% endblock %}
todo:
{% extends "tasks/layout.html" %}
{% block body %}
<h1> To Do List</h1>
<ul>
{% for task in tasks %}
<li> {{ task }}</li>
{% endfor %}
</ul>
Add items
{% endblock %}
as #Iain Shelvington suggested, you need to put method="post" as
{% block body %}
<form method="post" action="{% url 'tasks:add' %}">
{% csrf_token %}
{{ form }}
<input type="submit">
</form>
Veiw list
{% endblock %}
Related
I aim to redirect the view after the form has been saved. However django keeps throwing a NoReverseMatch error. Is there a step that I've missed or a misconfiguration?
views.py
def add_carpet(request):
context_dict = {}
carpet_form = forms.CarpetForm()
if request.method == "POST":
carpet_form = forms.CarpetForm(request.POST)
if carpet_form.is_valid():
carpet = carpet_form.save()
return redirect(reverse(
"dashboard_add_images",
kwargs={
"model_type": "carpet",
"id": carpet.id
}
))
context_dict["carpet_form"] = carpet_form
return render(
request,
'dashboard/add_carpet.html',
context_dict
)
def add_images(request, model_type, id):
...
add_images.hml
{% extends 'layouts/dashboard_base.html' %}
{% load django_bootstrap5 %}
{% load static %}
{% block title %}Add Images{% endblock title %}
{% block content %}
<div class="row">
<div class="col justify-content-end">
<h1 class="heading half_space text-muted">
Add Images for the {model}
<span class="divider-left"></span>
</h1>
</div>
</div>
{# Load CSS and JavaScript #}
{% bootstrap_css %}
{% bootstrap_javascript %}
{# Display django.contrib.messages as Bootstrap alerts #}
{% bootstrap_messages %}
{# Display a form #}
<form enctype="multipart/form-data" action="{% url 'dashboard_add_images' %}" method="post" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% bootstrap_button button_type="submit" content="OK" %}
</form>
{% endblock content %}
From above you can see I added the enctype on the form but still no change.
urls.py
urlpatterns = [
path('add_carpet', views.add_carpet, name="dashboard_add_carpet"),
path('add_images/<str:model_type>/<uuid:id>', views.add_images, name="dashboard_add_images"),]
An example redirect url after a form has been submitted is this:
http://127.0.0.1:8000/dashboard/add_images/carpet/97afd259-6ec4-48fc-869f-2a00bbe29c70
Error:
Reverse for 'dashboard_add_images' with no arguments not found. 1 pattern(s) tried: ['dashboard/add_images/(?P<model_type>[^/]+)/(?P<id>[^/]+)$']
Getting this error in my python code when attempting to delete a created topic.
Here are the url, views, and template snippets.
path('delete_topic/<int:topic_id>/', views.delete_topic, name='delete_topic')
def delete_topic(request, topic_id):
topic = Topic.objects.get(id=topic_id)
if request.method == 'POST':
topic.delete()`enter code here`
return redirect('online_diaries:topics', topic_id=topic.id)
context = {'topic': topic}
return render(request, 'online_diaries/delete_topic.html', context)
{% extends "online_diaries/base.html" %}
{% block content %}
<p>Are you sure to delete the topic <b><u>{{ topic }}?</b></u></p>
<form method="POST" action = "{% url 'online_diaries:delete_topic' topic.id %}">
{% csrf_token %}
cancel
<input type = "submit" name = "Confirm" class="btn btn-secondary btn-sm">
</form>
{% endblock content %}
I have a button in my template and I need to post the value of the button to my views. Unfortunately, my request.POST returns 'None'. How can I retrieve the information from my HTML template?
Thank you.
My template:
{% extends 'vocab/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<form action="{% url 'card' %}" method="POST">
{% for document in documents %}
<button type ='submit' value="{{ document.file }}" class='btn btn-outline-info' >
{{document.file}} </button>
{% endfor %}
</form>
{% endblock content %}
My view:
def card_view(request):
if request.method == 'POST':
context = {'request.POST':request.POST}
return render(request, 'vocab/card.html', context)
add name as attribute in button. name is like Key in python dictionary while value is the value of the Key.
Therefore, by using name you can obtain the ```value``
context = {'request.POST' : request.POST['name']}
I keep getting NoReverseMatch at /music/2/ error, and it's pointing me to the parent template that i'm inheriting from, base.html, but i can't find anything wrong with it. I know it's probably annoying when someone asks you to search for errors, but maybe someone can easily see what i'm unable to see
{% extends "music/base.html" %}
{% block content %}
<p> Album : {{one_album}} </p>
<p> Song list : </p>
{% if somethings_wrong %}
<p> {{ somethings_wrong }} </p>
{% endif %}
<form action = "{% url 'music:favorite' album.id %}" method="post" >
{% csrf_token %}
{% for song in album_entries %}
<input type="radio" id="song{{forloop.counter}}" name="song" value="{{ song.id }}">
<label for="song{{ forloop.counter }}">
{{ song.song_title }}
{% if song.is_favorite %} #afterwards, set this explicitly to true, for learning purposes
<img src="https://i.imgur.com/olM72b8.png"/> #check if this slash is necessary later
{% endif %}
</label><br>
{% endfor %}
<input type="submit" value="Favorite">
</form>
{% endblock content %}
Here's the base.html
<p>
Link to the homepage
</p>
{% block content %}
{% endblock content %}
Here's the Views.py :
from django.shortcuts import render
from django.http import HttpResponse
from .models import Album, Song
def index(request):
albums = Album.objects.all()
context = {'albums': albums}
return render(request, 'music/index.html', context)
def detail(request, album_id):
# show album and every entry in that album.
one_album = Album.objects.get(id=album_id)
album_entries = one_album.song_set.all()
context = {'one_album' : one_album, 'album_entries' : album_entries}
return render(request, "music/album.html", context)
# Create your views here.
def favorite(request, album_id):
one_album = Album.objects.get(id=album_id)
try:
context = {'one_album' : one_album}
selected_song = one_album.song_set.get(id=request.POST["song"])
except(KeyError, Song.DoesNotExist):
somethings_wrong = "Something's not right with your choice"
context = {'one_album' : one_album, 'somethings_wrong' : somethings_wrong}
return render(request, "music/album.html", context)
else:
selected_song.is_favorite = True
selected_song.save()
return render(request, "music/album.html", context)
i think error is somewhere here, urls.py and models.py are pretty simple. I've added is_favorite booleanfield to Song class, which is False by default, and urls.py is pretty straightforward
path('<int:album_id>/favorite', views.favorite, name='favorite')
variable that you want to refer to is one_album
but you are calling it album.
change
<form action = "{% url 'music:favorite' album.id %}" method="post" >
to
<form action = "{% url 'music:favorite' one_album.id %}" method="post" >
My form inputs are not showing. It's just a button. i think homepage.html doesn't getting this form
Forms.py
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
Views.py
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'mainApp/homepage.html', {'form': form})
homepage.html
{% extends "mainApp/wrapper.html" %}
{% block title %}Главная{% endblock %}
{% block content %}
<h1>Main page</h1>
{% include "mainApp/includes/somehtml.html" %}
<br>
<form action="/account/username/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
<br>
{% endblock %}
It shoes only "Submit" button. How can I fix it?
Please change
{{form}}
to {{form.as_p}}
Views.py
from app_name.forms import * # Change app_name with your app name
def get_name(request):
temp_context = {} # Check here
if request.method == 'POST':
acc_form = NameForm(request.POST) # Check here
temp_context["acc_form"] = acc_form # Check here
if acc_form.is_valid(): # Check here
return HttpResponseRedirect('/')
else:
temp_context[“acc_form”] = NameForm() # Check here
return render(request, 'mainApp/homepage.html', temp_context) # Check here
homepage.html
{% extends "mainApp/wrapper.html" %}
{% block title %}Главная{% endblock %}
{% block content %}
<h1>Main page</h1>
{% include "mainApp/includes/somehtml.html" %}
<br>
<form action="/account/username/" method="post">
{% csrf_token %}
{{ acc_form }} # Check here;
# you can also try {{ acc_form.as_table }} or {{ acc_form.as_p }} if there any issue
<input type="submit" value="Submit" />
</form>
<br>
{% endblock %}