为什么我不能在Django中打印选择模型实例?

时间:2019-03-04 20:59:05

标签: python django

有点背景故事:我是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>

感谢您的光临。就像我说的那样,我知道我在这里缺少有关Models的基本知识,但是我似乎无法找出可能是什么。

编辑:添加了更多代码。 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:

这是我为自己的观点所做的尝试。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")

1 个答案:

答案 0 :(得分:1)

这与选择字段或显示方法完全无关。问题是您没有在SuccessView中为模板提供任何上下文。根本没有设备可显示,并且deviceSelection是未定义的。

您需要使用一个DetailView,其URL包含一个标识您要显示的设备ID的参数。然后,在您的创建视图中,您需要通过覆盖get_succress_url方法来重定向到该URL。

相关问题