只是一个小背景:我对Python/Django还不熟悉,但有一个我在其中制作的工作应用程序,我正在尝试重组,以便能够充分利用Django模型的强大功能。我目前有一个选择模型,用户从下拉列表中选择,然后他们被重定向到一个成功页面。最终,脚本将根据它们的选择执行。在success页面上,我想显示他们当前的选择,作为他们执行脚本的“确认”。你知道吗
在研究了一段时间之后,我收集了一些我需要去的方向,但是在实现时遇到了一些问题,这使我相信我可能对模型设置缺乏一些基本的了解,所以澄清一下就好了。你知道吗
无论如何,我想使用模板中的get\u device\u display字段来实现这一点。然而,每当我试图实现它时,它就不起作用。我看到有些人为此使用自定义模型管理器,我需要以某种方式实现它吗?或者在显示成功页面时创建另一个窗体/模板视图?这是我的密码:
你知道吗模型.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()
你知道吗视图.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'
你知道吗成功.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>
谢谢你找我。就像我说的,我明白我在这里遗漏了一些关于模型的基本信息,但我似乎无法找出这可能是什么。你知道吗
编辑:添加了更多的代码。 索引.html(用于提交设备选择)
<!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>
你知道吗表单.py你知道吗
from django import forms
from port_reset.models import DeviceChoice
class DeviceChoiceForm(forms.ModelForm):
class Meta:
model = DeviceChoice
fields = ['device']
编辑2:
我试着为我的孩子做些什么视图.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})
你知道吗网址.py你知道吗
urlpatterns = [
path('', DeviceChoiceView.as_view(), name='index'),
path('success/<int:deviceSelection>', SuccessView.as_view, name="success")
这根本不是选项字段或显示方法的问题。问题是,在SuccessView中没有为模板提供任何上下文;根本没有要显示的设备,
deviceSelection
未定义。你知道吗您需要使用DetailView,其URL包含标识要显示的设备id的参数。然后,在create视图中,需要通过重写
get_succress_url
方法重定向到该URL。你知道吗相关问题 更多 >
编程相关推荐