我正在创建一个联系人列表,允许用户使用 Django 添加、删除和编辑。除了在用户点击“提交”后更新数据库中的信息外,我已经能够慢慢地完成大部分工作。
我尝试了一些我认为可能有效的不同方法,但不幸的是我最终遇到了错误。所以我想知道,在我呈现 html 编辑表单并且用户编辑他们选择的任何字段并点击提交之后,我如何接收该信息并用它更新数据库?我读到我需要使用“POST”,但我不确定如何设置。
视图.py 文件
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpRequest
from django.template import loader
from .models import Contact
def index(request):
return HttpResponse("Hello, world. You're at the contacts app.")
def list(request):
contacts_list = Contact.objects.all()
return render(request, 'index.html', {'contact_list':contacts_list})
def add(request):
if request.method == 'POST':
new_contact = Contact(
firstname = request.POST['firstname'],
lastname = request.POST['lastname'],
age = request.POST['age'],
phone = request.POST['phone'],
email = request.POST['email'],
gender = request.POST['gender'],
)
new_contact.save()
return redirect('/contacts/list/')
return render(request, 'addform.html')
def edit(request, cur_id):
if request.method == 'GET':
contact_to_edit = Contact.objects.get(id=cur_id)
contacts_list = Contact.objects.all()
return render(request, 'editform.html', {'cur_contact':contact_to_edit, 'contact_list':contacts_list})
elif request.method == 'POST':
pass
def delete(request, cur_id):
contact = Contact.objects.get(id=cur_id)
if request.method == 'POST':
contact.delete()
return redirect('/contacts/list/')
return render(request, 'index.html', {'contact': contact})
编辑表单.html
<html>
<head>
<title>
Contacts App
</title>
{% load static %}
<script src="{% static '/contacts.js'%}"></script>
{% load static %}
<link rel='stylesheet' type='text/css' href="{% static '/contacts.css' %}">
</head>
<body>
<p>
Welcome to your contacts management application. You can add contacts, edit them,
delete contacts, and see all your contacts.
</p>
<div>
<select id='contact_select'>
{% for contact in contact_list %}
<option value="{{ contact.id }}">
{{ contact.id }} {{ contact.firstname }} {{ contact.lastname }}
</option>
{% endfor %}
</select>
<br><br>
<button type='button' onclick='editContact()'>Edit Contact</button>
<button type='button' onclick='deleteContact()'>Delete Contact</button>
<button type='button' onclick='addContact()'>Add Contact</button>
<br><br>
<div>
<form id='edit_form' action="{% url 'contacts:edit' cur_contact.id %}" method="POST">
{% csrf_token %}
<label for='id'>Contact Id</label>
<input type='number' name='id' id='id' value="{{cur_contact.id}}" disabled><br>
<label for='firstname'>First Name</label>
<input type='text' name='first_name' id='first_name' value="{{cur_contact.firstname}}"><br>
<label for='lastname'>Last Name</label>
<input type='text' name='last_name' id='last_name' value="{{cur_contact.lastname}}"><br>
<label for='age'>Age</label>
<input type="number" name='age' id='age' value="{{cur_contact.age}}"><br>
<label for='phone'>Phone Number</label>
<input type='text' name='phone' id='phone' value="{{cur_contact.phone}}"><br>
<label for='email'>Email</label>
<input type='text' name='email' id='email' value="{{cur_contact.email}}"><br>
<label for='gender'>Gender</label>
<input type='text' name='gender' id='gender' value="{{cur_contact.gender}}"><br>
<input type='submit' id='submit_button' onclick='formValidate()' value="Submit">
<button type='button' name='cancel' onclick='homePage()' id='cancel_button'>Cancel</button><br>
</form>
<br>
</div>
<table>
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>Phone</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{% for contact in contact_list %}
<tr>
<td> {{ contact.id }} </td>
<td> {{ contact.firstname }} </td>
<td> {{ contact.lastname }} </td>
<td> {{ contact.age }} </td>
<td> {{ contact.phone }} </td>
<td> {{ contact.email }} </td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>
我对此很陌生,所以如果我遗漏了什么或者这是一个愚蠢的问题,我深表歉意。任何帮助将不胜感激。
我尝试过的一些事情是;
def edit(request, cur_id):
if request.method == 'GET':
contact_to_edit = Contact.objects.get(id=cur_id)
contacts_list = Contact.objects.all()
return render(request, 'editform.html', {'cur_contact':contact_to_edit, 'contact_list':contacts_list})
elif request.method == 'POST':
contact = Contact(
firstname = request.POST['firstname'],
lastname = request.POST['lastname'],
age = request.POST['age'],
phone = request.POST['phone'],
email = request.POST['email'],
gender = request.POST['gender'],
)
contact.save()
return redirect('/contacts/list/')
但是有了这个,我得到了这个回溯;
Environment:
Request Method: POST
Request URL: http://localhost:8000/contacts/edit/6/
Django Version: 3.1.7
Python Version: 3.9.2
Installed Applications:
['contacts.apps.ContactsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "C:\Users\Spenc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\utils\datastructures.py", line 76, in __getitem__
list_ = super().__getitem__(key)
During handling of the above exception ('firstname'), another exception occurred:
File "C:\Users\Spenc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Spenc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Spenc\Desktop\School\Python CS223\mysite\contacts\views.py", line 34, in edit
firstname = request.POST['firstname'],
File "C:\Users\Spenc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\utils\datastructures.py", line 78, in __getitem__
raise MultiValueDictKeyError(key)
Exception Type: MultiValueDictKeyError at /contacts/edit/6/
Exception Value: 'firstname'
我还尝试删除他们试图编辑的联系人,以便他们可以重新输入信息。然而,这对 ID 号码造成了问题,我无法删除联系人。
为该模型创建一个更新视图并指定您要更新的字段。您可以使用自定义表单,但相信我,这些通用视图将为您节省大量时间。
视图.py:
from django.views.generic.edit import UpdateView
class updimagesUpdateView(UpdateView):
model = updimages
fields = ['approval']
template_name_suffix = '_update_form'
在所有属性中,您可以提及需要更新的属性。如上面最后一行所示 (template_name_suffix) ,对模板使用相同的命名后缀模式... [modelname_update_form.html] 并显示表单...
模型名_update_form.html :
{% extends "base.html" %}
{% load static %}
{% load bootstrap_tags %}
{% block title %} Update {% endblock %}
{% block body%}
<div class="jumbotron">
Are you sure you want to approve the Image ?
</div>
<br>
<form method="POST">
{% csrf_token %}
{{ form|as_bootstrap }}
<input type="submit" value="Submit" />
</form>
{% endblock %}
确保从模板中获取要更新的相应元素:
<h3><a href="{% url 'images:update' pk=val.pk %}">update</a></h3>
单击上面的会触发 url。添加网址,
网址.py:
path('update/<int:pk>', views.updimagesUpdateView.as_view() , name = "update"),
PS:您还可以使用查询更新视图中的值以选择所需的对象,然后像这样编辑它们,
在 views.py 中:
example = model.objects.filter(id=images.id).update(content=txt)
查看文档了解更多信息:https : //docs.djangoproject.com/en/3.1/ref/class-based-views/generic-editing/
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句