Post data from button value to views in Django - python

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']}

Related

Why doesn't request.GET.get("edit") work in my code?

I'm trying to make a view in Django, in where if the edit button is pressed on that page it is passed on to another view as a session.
def page(request,user_input):
entry = util.get_entry(user_input)
name = user_input.capitalize()
request.session['name'] = name
request.session['entry'] = entry
if request.GET.get("edit"): # **<- This is not working for some reason.**
request.session['edit'] = True
else:
request.session['edit'] = False
return render(request, "homepage/page.html", {
"entry":entry,
"title":name,
})
Here is my page.html file
{% block body %}
{% if entry %}
<h1>{{title}}</h1>
{{ entry }}
{% endif %}
<form action="{% url 'create' %}" name='edit'>
<input type="submit" value='edit' class="button">
</form>
{% endblock %}
This is the view where I want to use the session
def create(request):
change =request.session['edit']
if request.GET.get('submit'):
title = str(title).lower()
if change:
util.save_entry(title,content)
return HttpResponseRedirect('/index')
You can specify a key-value pair by making use of the <button> tag, so then the form should look like:
<form action="{% url 'create' %}">
<button name="submit" value="edit" type="submit" class="button">edit</button>
</form>

Django form only sending GET requests

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 %}

Getting a "NoReverseMatch" error in python code

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 %}

Reverse for 'favorite' with arguments '('',)' not found, following Bucky's Django tutorial on YouTube

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" >

Django url not found upon submitting form

My apologies if the question is stupid, I am a newbie to this. I am creating a django web application. I have created a form inside it. When I submit the form, it says 'url' not found even though the same URL loads fine for the first time when opening the form. This is whats confusing me. Here is my code:
#forms.py
class Recipe_ruleForm(forms.ModelForm):
class Meta:
model = Recipe_rule
fields = ('content',)
#urls.py
url(r"^create_recipe_rule/(?P<recipe_pk>[0-9]+)/$",views.create_recipe_rule, name="create_recipe_rule"),
#views.py
def create_recipe_rule(request, recipe_pk):
form = Knowledgebase_ruleForm
selected_recipe = Recipe.objects.get(pk = recipe_pk)
if request.method == 'POST':
form = Recipe_ruleForm(request.POST)
if form.is_valid():
#current_user = request.user
data = form.cleaned_data
recipe_rule_data=Recipe_rule.objects.create(recipe=selected_recipe, content=data['content'])
recipe_rule_data.save()
recipe_rule = Recipe_rule.objects.get(pk = recipe_rule_data.pk)
recipe=selected_recipe
recipe = Recipe.objects.get(pk = recipe.pk)
return redirect('recipe_detail', pk=recipe.pk)
else:
messages.error(request, "Error")
return render(request, 'create_recipe_rule.html' , {'form': form})
Here is the error when I submit the form:
Page not found (404) Request Method: POST Request
URL: http://[ip_adress]:[port]/create_recipe_rule/
UPDATE:
Here is my template:
{% extends "account/base.html" %}
{% load i18n %}
{% load bootstrap %}
{% block body_class %}applications{% endblock %}
{% block head_title %}{% trans "Create recipe" %}{% endblock %}
{% block body %}
<form action="/create_recipe_rule/" method="post">
{% csrf_token %}
<div class="form-group">
<label for="{{ form.content.label }}">{{ form.content.label }}:</label>
<textarea type="{{ form.content.type }}" name="{{ form.content.name }}" max_length="500" class="form-control" id="{{ form.content.id }}"></textarea>
</div>
<input class="btn btn-default" type="submit" value="submit">
</form>
{% endblock %}
You have action="/create_recipe_rule/", which is missing the recipe id.
One option is to simply remove the action from the form, then your browser will submit the request to the current url.
<form method="post">
If you do want to include the form action, then first you need to update your view so that it includes the recipe id in the template context.
return render(request, 'create_recipe_rule.html' , {'form': form, recipe_id: recipe_id })
Then you can update the form action to include the recipe id.
action="/create_recipe_rule/{{ recipe_id }}"
It's good practice to use the {% url %} tag, so that you are not hardcoding urls in the template:
action="{% url 'create_recipe_rule' recipe_id %}"

Categories

Resources