Referencing variable form ID in django
I am having trouble figuring out how to reference the (variable) name of a form in django. This is the code I currently have:
in email_edit.html
:
{% for email in email_list %}
<table>
<tr>
<td><form action="/emails/edit/" method="post">
{% csrf_token %}
<input type="text" name="{{ email.id }}" value=" {{email}}"></td>
<td><input type="submit" value="Edit" name="action"></td>
<td><input type="submit" value="Delete" name="action"></td>
</tr>
</form>
</table>
{% endfor %}
<p>Add new</p>
<form action="/emails/edit/" method="post">
{% csrf_token %}
<input type="text" value="" name="add_email">
<input type="submit" value="Add" name="action">
def email_edit(request):
email_list = Email.objects.order_by('email')
if request.POST:
action = request.POST.get('action')
if action == "Add":
Email.objects.create(email=request.POST['add_email'])
return HttpResponseRedirect('/emails/edit/')
if action == 'Delete':
Email.objects.filter(id={{ emails.id }}).delete()
return HttpResponseRedirect('/emails/edit/')
if action == "开发者_Python百科Update":
Email.objects.filter(id= {{ emails.id }}).update(name=request.POST[{{ emails.id }}])
return HttpResponseRedirect('/emails/edit/'))
What goes in {{ email.id }}
in the views.py
file to correctly reference the form?
Not to be rude, I think you might want to take a step back at what you're trying to accomplish. You have a list of emails that you want to then edit or delete. You don't really need to submit a form to get to another view in which you are going to edit or delete one of these records.
You'll most definitely need a form on an edit or delete view to post your values, but in the case of this list, I'm 99.9% sure you just need an anchor tag to edit or delete:
{% for email in email_list %}
<table>
<tr>
<td>{{email}}></td>
<td><a href="{% url edit_email email.id %}">Edit</a></td>
<td><a href="{% url delete_email email.id %}">Delete</a></td>
</tr>
</table>
{% endfor %}
Hope that makes sense.
[Followup Answer] Given the code you set up, I would make each row would be it's own form, and the email field would need to have a non-dynamic name. Otherwise, it's going to be tougher to access that value in the request.POST collection. Here's how I would set that up:
#views.py
from django.shortcuts import render
def my_view(request):
email_list = MyModel.objects.all()
if request.method == 'POST':
email = request.POST.get('email')
action = request.POST.get('action')
if action == 'Edit':
#do edit
else:
#do delete
return render(request, 'template.html', {'email_list' : email_list})
#template.html
{% for email in email_list %}
<table>
<tr>
<form action="." method="post">
<td>{{ email }}<input type="hidden" name="email" value="{{ email }}" /></td>
<td><input type="submit" name="action" value="Edit" /></td>
<td><input type="submit" name="action" value="Delete" /></td>
</form>
</tr>
</table>
{% endfor %}
精彩评论