我在Django中还很缺乏经验,我想知道是否可以直接从模板更新/保存数据库中的今日日期?更新/直接从模板保存模型日期值?
我有一个Django筛选filterView(列表视图),它显示我的部门中我目前在我的数据库中的人员列表。我想通过点击列表中显示的< \ a>链接将日期时间值(上次访问人员时)更新为今天的日期。这样我就不需要设置更新视图来更新我上次访问同事时的更新视图。这是甚么可能吗?
我的确尝试在我的models.py中使用@property标记实现一个函数,但是当我刷新网页或访问页面时,它会自动更新它,而无需点击链接。
编辑:这里是代码:
# models.py
@property
def update_visit_date(self):
self.last_visit = timezone.make_aware(datetime.datetime.today())
super(Directory, self).save()
return reverse('directory_list')
# snippet from my template directory_list.html
{% for contact in items %}
<tr>
<td>{{ contact.first_name }}</td>
<td>{{ contact.last_name }}</td>
<th><a href="{{ contact.get_absolute_url }}">{{ contact.email_address }}</a></th>
<td>{{ contact.phone_number_1 }}</td>
<td>{{ contact.get_department_display }}</td>
<td>{{ contact.room_number }}</td>
{% if contact.is_past_due == 'no_visit_performed' %}
<td class="info">{{ contact.last_visit }}<a href="{{
contact.update_visit_date }}"> {% bootstrap_icon "plus-sign" %}</a></td>
{% elif contact.is_past_due == 'visit_good' %}
<td class="success">{{ contact.last_visit }}<a href="{{
contact.update_visit_date }}"> {% bootstrap_icon "plus-sign" %}</a></td>
{% elif contact.is_past_due == 'visit_old' %}
<td class="warning">{{ contact.last_visit }}<a href="{{
contact.update_visit_date }}"> {% bootstrap_icon "plus-sign" %}</a></td>
{% elif contact.is_past_due == 'need_visit' %}
<td class="danger">{{ contact.last_visit }}<a href="{{
contact.update_visit_date }}"> {% bootstrap_icon "plus-sign" %}</a></td>
{% endif %}
</tr>
{% empty %}
这是不是这是可能的,从模板链接进行CRUD?还是我以错误的方式去做这件事?任何帮助是极大的赞赏。非常感谢你!
编辑:找到了一个决心。我最终做的是创建了一个执行CRUD的基于功能的视图。这里是代码:
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
def last_visit_view(request, pk):
last_visit_obj = Directory.objects.filter(pk=pk)
if last_visit_obj:
last_visit_obj = last_visit_obj[0]
last_visit_obj.last_visit = datetime.now()
last_visit_obj.save()
return HttpResponseRedirect(reverse('directory_list'))
我的模板url调用这个函数,它的工作很好。现在我需要看看如何在HttpResponseRedirect上保留过滤结果。
谢谢你的评论,因为它我能找到一个决心。我所能做的是创建一个执行CRUD的基于功能的视图。我会用代码编辑我的问题。 – TVH