这只是一个小小的背景故事:我对Python/Django是个新手,但我在其中制作了一个可以工作的应用程序,我正在尝试重组它,这样我就可以充分利用Django模型的强大功能。我目前有一个选择模型,用户可以从下拉列表中选择,然后被重定向到一个成功页面。最终,脚本将根据他们的选择执行。在成功页面上,我希望将他们当前的选择显示为他们已执行脚本的“确认”。
在研究了很长一段时间后,我收集了一些我需要去做的方向,但我在实现时遇到了一些问题,这让我相信我可能对模型设置缺乏一些基本的理解,所以一些澄清会很好。
无论如何,我想使用模板中的get_device_display字段来完成此操作。然而,每当我尝试实现它时,它都不起作用。我发现有些人使用自定义模型管理器来实现这一点,我需要以某种方式实现它吗?或者在显示成功页面时创建另一个form/TemplateView?下面是我的代码:
modles.py
from django.db import models
class DeviceChoice(models.Model):
DEVICE_NAMES = (
('1', 'Haha123-9400-5'),
('2', 'Cisco-4506-1'),
('3', 'Test-3850-3'),
('4', 'Hello-2960C-1'),
('5', 'Router-9850-1'),
('6', 'Switch-2900-4'),
)
device = models.CharField(max_length=20, choices=DEVICE_NAMES)
objects = models.Manager()views.py
def success(request):
return render(request, 'success.html')
class SuccessView(TemplateView):
template_name = "success.html"
class DeviceChoiceView(CreateView):
model = DeviceChoice
form_class = DeviceChoiceForm
success_url = reverse_lazy('success')
template_name = 'index.html'success.html
<!DOCTYPE html>
<html>
<head>
<title>Port Reset</title>
</head>
<body>
<h1>Success!!</h1>
<!--Not sure how to implement below this line-->
{{ deviceSelection.get_device_display }}
</body>谢谢你的关注。正如我所说的,我知道我在这里遗漏了一些关于模型的基本信息,但我似乎找不到可能的原因。
编辑:添加了更多代码。index.html (用于提交deviceSelection)
<!DOCTYPE html>
<html>
<head>
<title>Port Reset</title>
</head>
<body>
<h1>Device Database</h1>
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" id="deviceSelection" value="Submit">
</form>
</body>forms.py
from django import forms
from port_reset.models import DeviceChoice
class DeviceChoiceForm(forms.ModelForm):
class Meta:
model = DeviceChoice
fields = ['device']编辑2:
以下是我尝试为我的views.py做的事情:
class SuccessView(DetailView):
model = DeviceChoice
template_name = "success.html"
queryset = DeviceChoice.objects.all()
class DeviceChoiceView(CreateView):
model = DeviceChoice
form_class = DeviceChoiceForm
#success_url = reverse_lazy('success')
template_name = 'index.html'
def get_success_url(self):
return reverse_lazy('success', kwargs={'deviceSelection': self.deviceSelction})urls.py
urlpatterns = [
path('', DeviceChoiceView.as_view(), name='index'),
path('success/<int:deviceSelection>', SuccessView.as_view, name="success")发布于 2019-03-05 07:39:02
这根本不是选择字段或显示方法的问题。问题是您没有为SuccessView中的模板提供任何上下文;根本没有要显示的设备,并且deviceSelection是未定义的。
您需要使用一个DetailView,该URL包含一个参数来标识您想要显示的设备的id。然后,在create视图中,您需要通过覆盖get_succress_url方法来重定向到该URL。
https://stackoverflow.com/questions/54991450
复制相似问题