I have a webpage form in django. I have some radio button on my webpage. After user selects the radio button and on submit I need to know which radio button was selected in my views.
I tried using following code:
Html Template:
<form action= "{% url 'rec:opt' %}" method="post">
{% csrf_token %}
{% for name in features %}
<tr>
<td>{{ name }}</td>
<td>
<input type="checkbox" name="is_obj" id={{ name }} + "_is_obj" > <br>
</td>
<td>
Lower Limit <input type="text" name="ll" id={{ name }} + "_ll">
Upper Limit <input type="text" name="ul" id={{ name }} + "_ul">
</td>
</tr>
{% endfor %}
<input type="submit" value="Submit" />
</form>
View.py
def opt(request):
print(request.POST['is_obj']) #'on'
The request.POST only returns 'on' and doesn't say which radio/check box was selected.
Also the getlist returns following
request.POST.getlist['is_obj'] # ['on']
You need to add value attribute to your checkboxes:
<input type="checkbox" name="is_obj" id={{ name }} + "_is_obj" value="{{ name|add:'_is_obj' }}">
If the value attribute was omitted, the default value for the checkbox is on.
Note you can use add filter for string concatination. But be careful strings that can be coerced to integers will be summed, not concatenated.
Related
.I am new to django. please help me with the solution.I want to get specific event name and number at a particular page. It has to same id and same name on next page. But, the input is showing me the last value of database.eventlist.html
<form method="post">
{% csrf_token %}
<label for="">Event Name</label>
<input type="text" name="eventname">
<input type="submit">
</form>
my view.py
def eventlist(request):
if request.method == 'POST':
eventname = request.POST.get('eventname')
eventid = str(random.randint(100000000, 999999999))
eventlistdata = EventList(eventname = eventname,eventid=eventid)
eventlistdata.save()
return render(request,"adminsys/eventlistlist.html",{'eventname': eventname,'eventid':eventid})
return render(request, 'adminsys/eventlist.html')
my eventlistlist.html file only for passing values
<form method="post">
{% csrf_token %}
<table>
<tr>
<th>Event Name</th>
<th>Event ID</th>
<th>Submit</th>
</tr>
{% for post in post %}
<tr>
<td><input type="text" name="eventname" id="eventname" value="{{post.eventname}}"></td>
<td><input type="text" name="eventid" id="eventid" value="{{post.eventid}}"></td>
<td><button type="submit">Submit</button></td>
</tr>
{%endfor%}
</table>
</form>
my views.py of eventlistlist file
<form method="post">
{% csrf_token %}
<label for="">Event Name</label>
<input type="text" value="{{eventname}}" id="eventn">
<label for="">Event Id</label>
<input type="text" value="{{eventid}}" id="eventi">
</form>
And the last page where I want to get my same value as given in eventlistlist.html
<form method="post">
{% csrf_token %}
<label for="">Event Name</label>
<input type="text" value="{{eventname}}" id="eventn">
<label for="">Event Id</label>
<input type="text" value="{{eventid}}" id="eventi">
</form>
I am always getting the data which is last in my mysql database.
I will attach the images below for reference
When I will select the first options:
I am receiving the last value in my datadabe
I have a table and I wish to add an edit button that updates the certain record both visually and in the database.
The HTML I have.
{% for work_entry in work_entries %}
{% if work_entry.date == date.date %}
<form action="{% url 'work_entries:object_edit' work_entry.id %}" method="post">
{% csrf_token %}
<tr>
<td>
<button onclick="return confirm('Are you sure you want this edit?')">Edit
</button>
</td>
<td> <form action="{% url 'work_entries:object_delete' work_entry.id %}" method="post">
{% csrf_token %}
<button onclick="return confirm('Are you sure you want to delete this record?')">Delete
</button>
</form>
</td>
<td>{{ work_entry.id }}</td>
<td><input type="text" value="{{ work_entry.description }}" name="description"></td>
<td><input type="number" value="{{ work_entry.num_hours }}" name="hours"></td>
</tr>
</form>
{% endif %}
{% endfor %}
The views.py
def object_edit(request, object_id):
record = get_object_or_404(WorkEntry, pk=object_id)
if request.method == "POST":
record.description = request.POST["description"]
record.num_hours = request.POST["hours"]
record.save()
return redirect("/employeePage")
return render(request, "employeePage.html")
And urls.py
app_name = "work_entries"
urlpatterns = [
path("", views.employee_view, name="employeePage"),
url(r"^delete/(?P<object_id>[0-9]+)/$", views.object_delete, name="object_delete"),
url(r"^edit/(?P<object_id>[0-9]+)/$", views.object_edit, name="object_edit"),
]
I used an input tag in the as I thought that would allow me to change data and save it. However this is giving me MultiValueDictKeyError at /employeePage/edit/14/
'description' error. I am not too experienced with jquery which from research I saw that could work but I don't seem to get it right. Can someone help or even suggestions on how I should approach this would be useful.
Note: there is already a button to delete the record which works, I tried a similar approach for editing, but it doesn't work.
I fully encourage you to use the forms provided by Django, it will make your life easier.
And I fully encourage you as well to not use a form for your delete stuff, it should be a simple link, it would avoid to have a form in a form. I think your problem is here. Having a form in a form with the button in the middle make impossible for your browser to know which parts of the form you want to submit.
As well you have two buttons but none of them is submit type.
If you don't want to use the Django forms a way to do it would be
{% for work_entry in work_entries %}
{% if work_entry.date == date.date %}
<form action="{% url 'work_entries:object_edit' work_entry.id %}" method="post">
{% csrf_token %}
<tr>
<td>
<button>
Delete
</button>
</td>
<td> <button type="submit" onclick="return confirm('Are you sure you want to update this record?')">
Update
</button>
</td>
<td>{{ work_entry.id }}</td>
<td><input type="text" value="{{ work_entry.description }}" name="description"></td>
<td><input type="number" value="{{ work_entry.num_hours }}" name="hours"></td>
</tr>
</form>
{% endif %}
{% endfor %}
It's not the most beautiful way to do it I tried to keep your achitecture
I am trying to create an app where a user can manage a database of "Lost property" items. To do so I have a main page where all the items are displayed and I have a button per row to be clicked when the item is returned to the owner.
That button is submitting a form that should contain the ID value of the element that has been clicked so I trying to get something like
<input id="id_id" name="id" type="hidden" value="{{lostitem.id}}">
But I don't know how to pass that value to my form ! Here is my template :
{% for lostitem in lostitems %}
<tr>
<td>{{lostitem.id}}</td>
<td>{{lostitem.description}}</td>
<td>
<form class="give-back-item-form" method="POST">
{% csrf_token %}
{{formGiveBackItem.as_p}}
<button type="submit" class="button btn btn-xs btn-success buttonItems">
<span class="glyphicon glyphicon-share-alt" aria-hidden="true"></span>
</button>
<!-- TRYING TO ADD A HIDDEN INPUT WITH THE ID AS VALUE -->
</form>
</td>
</tr>
{% endfor %}
Here is my form from forms.py
class GiveBackItemForm(forms.ModelForm):
id = forms.CharField(widget=forms.HiddenInput())
class Meta:
model = ItemLost
fields = ('id',)
And here is where I'm trying to get my $_POST['id'] and to update my object (I couldn't test this part as I'm not getting any POST information at the moment) :
from .forms import GiveBackItemForm
"""Defining our views"""
def item_list(request):
formGiveBackItem = GiveBackItemForm()
"""Ordering objects by date of creation"""
lostitems = ItemLost.objects.filter(added_date__lte=timezone.now()).order_by('added_date')
if request.method == "POST":
"""Giving back an item"""
itemToGive = ItemLost.objects.get(pk=request.POST.get('id'))
itemToGive.giveBackItem
"""Returning our ordered objects to the view"""
"""Request = everything we receive from the user (in a form for example)"""
return render(request, 'lostitem/item_list.html', {'lostitems': lostitems, 'formGiveBackItem' : formGiveBackItem})
Thanks for any help or remark about the code ! I'm just getting started and it was really hard to find anything helpful about my problem
EDIT : I managed to make it work by still using the Django ModelForm and the view to handle my form
Here is my code in my view :
def item_list(request):
"""Ordering objects by date of creation"""
lostitems = ItemLost.objects.filter(added_date__lte=timezone.now()).order_by('added_date')
"""To get data from the form"""
give_back_item_form = GiveBackItemForm(request.POST or None)
# check if form is valid
if give_back_item_form.is_valid():
itemToGive = ItemLost.objects.get(pk=give_back_item_form.cleaned_data['id'])
itemToGive.returned_date=timezone.now()
itemToGive.save()
# your rest of the code here
"""Returning our ordered objects to the view"""
"""Request = everything we receive from the user (in a form for example)"""
return render(request, 'lostitem/item_list.html', {'lostitems': lostitems, 'give_back_item_form' : give_back_item_form})
And here is the code for my template !
<form class="give-back-item-form" method="POST">
{% csrf_token %}
<input type="hidden" name="id" value="{{ lostitem.id }}">
<button type="submit" class="button btn btn-xs btn-success buttonItems">
<span class="glyphicon glyphicon-share-alt" aria-hidden="true"> </span>
</button>
</form>
Thank you all for your answers it lead me to the right solution !
If all you want to do is post back the id of an associated ItemLost object so that you can invoke a method on it (e.g., giveBackItem()), there's no need to use a ModelForm at all. Just use a normal HTML <form>, and manually put the hidden field in it:
<form class="give-back-item-form" method="POST">
{% csrf_token %}
<button type="submit" value="Give Back">
<input type="hidden" name="id" value="{{lostitem.id}}">
</form>
So your complete template would become:
{% for lostitem in lostitems %}
<tr>
<td>{{lostitem.id}}</td>
<td>{{lostitem.description}}</td>
<td>
<form class="give-back-item-form" method="POST">
{% csrf_token %}
<button type="submit" class="button btn btn-xs btn-success buttonItems">
<span class="glyphicon glyphicon-share-alt" aria-hidden="true"></span>
</button>
<input type="hidden" name="id" value="{{lostitem.id}}">
</form>
</td>
</tr>
{% endfor %}
I have a template index.html which contains a table of data. At the end of each row data, there is an edit button which allows you to edit the column entries in that row.
Here is how my table is constructed in index.html:
<table style="width:300px">
<tr>
<td> Mailing List Name</td>
<td> Mailing List Creation Date</td>
</tr>
{% for listEntry in lists %}
<tr>
<td>{{ listEntry.name }}</td>
<td>{{ listEntry.create_date }}</td>
<td>
<form action="/list_edit" method="post">
<input id="submit" type="submit" value="Edit" />
**Extra hidden input fields would be added here**
</form>
</td>
</tr>
{%endfor%}
</table>
How can I pass variables defined in the ListEntry model as hidden input fields to a form?
Try:
<input name="{{ listEntry.someId }}" type="hidden" value="{{ listEntry.value }}" />
However if you have one <form> element per row, you need to give submit action a value based on which row it is too.
import webapp2
from views import MainPageCourt, CreateCourt, DeleteCourt, EditCourt, Listbox, \
MainPage, CreateLocation, DeleteLocation, EditLocation, Unexpected, \
Schedule
app = webapp2.WSGIApplication([
('/', MainPage),
('/unexpected', Unexpected),
('/listbox', Listbox),
('/read/([\w]+)', MainPageCourt),
('/create/([\w]+)', CreateCourt),
('/createlocation/([\w]+)', CreateLocation),
('/schedule/([\w]+)/([\w]+)', Schedule),
('/editlocation/([\w]+)', EditLocation),
('/deletelocation/([\w]+)', DeleteLocation),
('/edit/([\w]+)/([\d]+)', EditCourt),
('/delete/([\w]+)/([\d]+)', DeleteCourt)
],
debug=True)
application: scheduler
version: 1
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /static
static_dir: static
- url: /create|schedule|createlocation|editlocation|deletelocation|edit|delete/.*
script: main.app
login: required
- url: /.*
script: main.app
libraries:
- name: jinja2
version: latest
- name: markupsafe
version: latest
builtins:
- remote_api: on
For my primary class class MainPageCourt(BaseHandler): the def post() code is never read and I cannot figure out why. When I press the submit button on the template, nothing happens and there is no reaction in the gae log. I wonder if the problem is that I want both the post() and the get() to "finish" the same way by going to the same page, read.html? Is that a problem or am I looking in the wrong way and wrong place for my problem? If it is the problem, what is an easy workaround?
The first line below is for the post() and the second is for the get() of MainPageCourt.
return webapp2.redirect("/read/%s" % location_id)
self.render_template('read.html', {'courts': courts,'location': location, ... etc ...}
This post relates to this question
template added below
{% extends "base.html" %}
{% block content %}
<p> You can start over at the beginning here. </p>
<p class="schedule" style="width: 850px;">
<big>{{ location.moreinfo}} </big> <br /
<form action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="ID" value="{{ location_id }}"></input>
<input type="hidden" name="weekday" value="{{ weekday }}"></input>
<input type="hidden" name="nowweekday" value="{{ nowweekday }}"></input>
<input type="hidden" name="month" value="{{ month }}"></input>
<input type="hidden" name="month" value="{{ nowmonth }}"></input>
<input type="hidden" name="day" value="{{ day }}"></input>
<input type="hidden" name="year" value="{{ year }}"></input>
<input type="hidden" name="startTime" value="{{ startTime }}"></input>
<input type="hidden" name="endTime" value="{{ endTime }}"></input>
{% for name in names %}
<input type="hidden" name="court" value="{{ name }}"></input>
{% endfor %}
<h1>{{ weekday }}, {{ month }} {{ day }}, {{ year }} at {{ location_id }} {{ location.venue }}</h1> <br />
Make a reservation by (1) filling out table fields and then (2) clicking "submit".
<div id="inputdata">
<input type="submit" value=submit />
</div>
<table border="1" cellpadding="2"
cellspacing="0" class="sortable" id="unique-id" align="center">
<thead>
<tr>
<td>Time</td>
{% for name in names %}
<td>{{ name }}</td>
{% endfor %}
</tr></thead>
<tbody>
{% for time in times %}
<tr>
<td >
{{ time[2] }}
</td>
{% for i in range(names|count) %}
<td>
{{ time[3+i] }}
</td>
{% endfor %}
{% endfor %}
</tr>
</tbody>
</form>
</table>
<br />
{% endblock content %}
There's no action specified in the form. In the form tag of your template you should add action=Url/Matching/BaseCourt.
In my template, immediately before the <form action... was an open tag: <br
With that fixed, the form is responding.