我有一个if/else语句,它决定了哪个按钮将显示在我的base.py模板中。通过研究,我认为我走在正确的道路上,但无论结束日期字段是空的还是填充的,endcast按钮都会显示。
产品型号:
class Cast(models.Model):
id = models.AutoField(db_column='Id')
startdate = models.DateTimeField(db_column='StartDate')
enddate = models.DateTimeField(db_column='EndDate')
class Meta:
managed = True
db_table = 'Cast'
verbose_name_plural = "Cast"
get_latest_by = "pk"
模板块:
<div class="top-button-container stickey-top">
{% with last=Cast.objects.latest %}
{% if last.enddate %}
<button type="button" class="btn btn-danger btn-lg btn-block">
<a class="nav-link" href="{% url 'caststart' %}">Start Cast</a>
</button>
{% else %}
<button type="button" class="btn btn-danger btn-lg btn-block">
<a class="nav-link" href="{% url 'cast_end' %}">End Cast</a>
</button>
{% endif %}
{% endwith %}
</div>
意见:
def caststart(request):
context ={}
form = StartCastForm(request.POST or None)
if request.method == "POST":
form = StartCastForm(request.POST, request.FILES)
if form.is_valid():
form.save()
castid=Cast.objects.last()
return HttpResponseRedirect("%i/castend" % castid.pk)
else:
form = StartCastForm
if 'submitted' in request.GET:
submitted = True
return render(request, 'wwdb/casts/caststart.html', {'form':form, 'submitted':submitted, 'id':id})
context['form']= form
return render(request, "wwdb/casts/caststart.html", context)
def cast_end(request):
last = Cast.objects.latest('pk')
return redirect('castend', id=last.pk)
def castend(request, id):
context ={}
obj = get_object_or_404(Cast, id = id)
form = EndCastForm(request.POST or None, instance = obj)
if request.method == 'POST':
cast=Cast.objects.last()
if form.is_valid():
form.save()
cast.refresh_from_db()
cast.endcastcal()
cast.save()
return HttpResponseRedirect("/wwdb/casts/%i/castenddetail" % cast.pk)
context["form"] = form
return render(request, "wwdb/casts/castend.html", context)
我期待着“开始铸造”按钮呈现时,最后一个对象结束日期字段填充。当结束日期字段为无时,应呈现“结束转换”按钮。它当前呈现“结束投射”按钮,而不管最后一个对象的结束日期字段值。
1条答案
按热度按时间hyrbngr71#
最后,我需要添加一个上下文处理器来解决这个问题。
我创建了文件myapp/context_processors.py
在我的base.py模板中:
settings.py