0
標題很不言自明,當我嘗試提交新條目時,django刪除了前一條。我認爲問題在於刪除功能,因爲當我禁用它時,我可以根據需要輸入儘可能多的條目。下面是我的文件:Django在提交新條目時刪除了以前的條目
Form.py
class FinancesForm(forms.Form):
description = forms.CharField(max_length = 50)
value = forms.DecimalField(max_digits = 10, decimal_places = 2)
Models.py
class Finances(models.Model):
date = models.DateField(auto_now = True)
description = models.CharField(max_length = 50)
value = models.DecimalField(max_digits = 10, decimal_places = 2)
total = models.DecimalField(max_digits = 10, decimal_places = 2, null = True)
Views.py
@login_required
def finances(request):
if request.method == 'POST':
form = FinancesForm(request.POST)
if form.is_valid():
newEntry = Finances()
newEntry.description = form.cleaned_data['description']
newEntry.value = form.cleaned_data['value']
if Finances.objects.all().aggregate(Sum('value')).values()[0] == None:
newEntry.total = newEntry.value;
else:
newEntry.total = Finances.objects.all().aggregate(Sum('value')).values()[0] + newEntry.value
newEntry.save()
return HttpResponseRedirect(reverse('finances'))
form = Finances()
entries = Finances.objects.all()
total = Finances.objects.all().aggregate(Sum('value')).values()[0]
return render(request, 'coop/finances.html', {'entries': entries, 'form':form, 'total': total})
@login_required
def fdelete(request):
if request.method != 'POST':
raise HTTP404
entryId = request.POST.get('entry', None)
entToDel = get_object_or_404(Finances, pk = entryId)
entToDel.delete()
return HttpResponseRedirect(reverse('finances'))
Finances.html
<tbody>
{% if entries %}
{% for entry in entries %}
{% if forloop.last %}
<tr>
<td>{{ entry.date }}</td>
<td>{{ entry.description }}</td>
{% if entry.value >= 0 %}
<td class="positive">{{ entry.value }}</td>
{% else %}
<td class="negative">{{ entry.value}}</td>
{% endif %}
<td>{{entry.total}}</td>
<td>
<form action="{% url "fdelete" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="hidden" name="entry" value="{{ entry.pk }}"/>
<input class="btn btn-primary" type="submit" value="Eliminar"/>
</td>
</tr>
{% else %}
<tr>
<td>{{ entry.date }}</td>
<td>{{ entry.description }}</td>
{% if entry.value >= 0 %}
<td class="positive">{{ entry.value }}</td>
{% else %}
<td class="negative">{{ entry.value}}</td>
{% endif %}
<td>{{entry.total}}</td>
<td></td>
</tr>
{% endif %}
{% endfor %}
{% endif %}
<tr>
<td></td>
<form class="input-group" action="{% url "finances" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<td><input class="form-control" type="text" placeholder="Concepte" name="description"/></td>
<td><input class="form-control" type="text" placeholder="Quantitat €" name="value" onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }"/></td>
</form>
<td></td>
<td></td>
</tbody>
感謝YOUT時間
是否也能提供這些意見的URL連接? – mateuszb