我正在使用计时器作为我的应用程序的一部分。用户可以按下按钮来启动或停止它,这将更新数据库中的DurationField。从用户那里我只能执行提交操作,这会触发我的视图以产生进入数据库的数据。
问题:考虑到进入数据库的数据不是用户输入的字符串或整数,而是从视图生成的,是否需要使用post方法?有更好的做法吗?
models.py
class Timer(models.Model):
timer_start = models.DateTimeField(auto_now_add=True)
final_duration = models.DurationField(null=True)
def __str__(self):
timer_start_f = self.timer_start.strftime("%Y-%m-%d %H:%M:%S")
return f"Created: {timer_start_f}"
def isActive(self):
if self.final_duration is None:
return True
else:
return False
def stop(self):
if self.isActive():
self.final_duration = timezone.now() - self.timer_start
self.save()
def time(self):
if self.isActive():
timedelta = timezone.now() - self.timer_start
return f"{timedelta}".split(".")[0]
else:
return f"{self.final_duration}".split(".")[0]
def timer_start_f(self):
return self.timer_start.strftime("%B %d, %Y, %H:%M %p")
urls.py
urlpatterns = [
path('', views.indexView, name='index'),
path('account/', views.timerView, name='timer')
]
views.py
def timerView(request):
try:
timer = Timer.objects.latest('timer_start')
except Timer.DoesNotExist:
if request.method == 'POST':
Timer.objects.create()
return HttpResponseRedirect("/account/")
else:
return render(request, 'pomodoro/timer.html', {'button_label': "Start Timer"})
else:
timer_list = Timer.objects.order_by('-timer_start')[1:]
if request.method == 'POST':
if timer.isActive():
timer.stop()
else:
Timer.objects.create()
return HttpResponseRedirect("/account/")
else:
# "state" is used by javascript to run or stop the timer
if timer.isActive():
button_label = "Stop Timer"
state = "active"
else:
button_label = "Start Timer"
state = "not active"
return render(request, 'pomodoro/timer.html', {'button_label': button_label, 'state': state, 'timer': timer, 'timer_list': timer_list})
答案 0 :(得分:0)
没有人要求您将视图包装在POST中。如果您希望某人使用GET参数触发您的视图(即与其他用户共享链接),请使用GET。
否则,我建议使用if POST
包装整个视图,因为它的意思是更接近于在db中操作数据,而不仅仅是选择并显示数据。