我用py+Django寫編輯修改的功能,遇到QuerySet filter的save錯誤。
查過官方文檔的內容是說’QuerySet’ object has no attribute ‘save’,
也就是說這是一個集合QuerySet,而對於集合的話,是沒有“save”這個屬性。
所以我在save()的位置添加**[0]**,使其值不為空
按下編輯修改按鈕後,可以抓到當前資料的id編號,如下圖
但問題來了,當我按下submit(確認修改),撈進來的id卻從id編號:1開始抓資料?! 如下圖
反而不是抓當前資料的id編號(舉例:id 120),這也是因為 filter 所影響的問題嗎?
請問該如何修正才能正確抓到當前資料的id編號? 謝謝
以下是提供我的程式代碼
Models:
Software Table
class Software(models.Model):
STATUS_CHOICES = [
(0, '規劃中'),
(1, '開發中'),
(2, '使用中'),
(3, '已廢棄')
]
name = models.CharField(max_length=100, verbose_name="系統名稱")
url = models.CharField(max_length=100, verbose_name="系統網址")
status = models.PositiveIntegerField(default=0, choices=STATUS_CHOICES, verbose_name="目前狀態")
company = models.ForeignKey(Company, on_delete=models.CASCADE, verbose_name="開發公司或單位")
team = models.ForeignKey(Team, on_delete=models.DO_NOTHING, verbose_name="所屬組別")
def __str__(self):
return self.name
Memo Table
class Memo(models.Model):
notes = models.TextField()
software = models.ForeignKey(Software, on_delete=models.CASCADE)
#software = models.ForeignKey(Software, on_delete=models.SET_NULL, null=True, blank=True)
timestamp = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.notes
Templates:
{% extends 'base.html' %}
{% block title %}
查核系統
{% endblock %}
{% block main %}
<h2 >編輯備註</h2>
<hr>
<form action="/editmemo/" method="POST">
{% csrf_token %}
<input name="pk" type="hidden" value={{ target_memo.id }}>
<table class="table table-striped">
<tr>
<td align=right>備註:
</td>
<td>
{% for memo in memos %}
<input type=text name="memos" size=50 value='{{memo.notes}}'>
{% endfor %}
</td>
</tr>
<tr><td> </td><td>
<input type=submit value="確定修改" class="btn btn-warning">
</td></tr>
</table>
</form>
{% endblock %}
Views:
@login_required(login_url='/admin/login/')
def edit_memo(request,pk=1):
teamid = Team.objects.get(name = logged_user.team).id
target_soft = Software.objects.get(id=pk)
item = Software.objects.get(id=pk)
if request.method=="POST":
softwareid = request.POST.get('softwareid')
item = Software.objects.get(id=pk)
memos = Memo.objects.filter(software=item)
memos[0].save() #使值不為空
return render(request,"showdetail.html",locals())
try:
memos = Memo.objects.filter(software=item)
except:
return redirect("/showall/")
return render(request, "edit_memo.html", locals())
Url:
urlpatterns = [
path('editmemo/',views.edit_memo),
path('editmemo/<int:pk>/',views.edit_memo),
path('', views.index),
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
<form action="/editmemo/" method="POST">
你每次submit的時候,打的網址是 /editmemo/,而不是 /editmemo/[pk]/。
加上
def edit_memo(request,pk=1):
你pk預設為1,加上沒有pk,當然pk會是1