使用通用的UpdateView始终编辑单个配置对象

时间:2018-09-30 22:29:51

标签: django python-3.x django-views

我需要什么

我想为我的应用程序进行全局配置,并且想重用通用的UpdateView

我尝试过的事情

为此,我创建了一个模型(示例字段):

class Configuration(models.Model):
    admin = models.ForeignKey('User', on_delete=models.CASCADE)
    hostname = models.CharField(max_length=23)

通用Updateview:

class ConfigurationView(UpdateView):
    model = Configuration
    fields = ['admin','hostname']

urls.py 条目

path(
    'configuration/', 
    views.ConfigurationView.as_view(
        queryset=Configuration.objects.all().first()
    ),
    name='configuration'
),

如您所见,我希望 configuration / 路径链接到此配置,并且始终只编辑该一个对象。

问题

我得到了错误

  

AttributeError:“配置”对象没有属性“全部”

问题

  1. 如何将对象硬编码到 urls.py 中的路径中,以便始终将第一个Configuration对象用于UpdateView

  2. 是否有更好的方法来做到这一点?我只想拥有一个全局配置对象,并希望使用我选择的模板对其进行编辑和显示。

1 个答案:

答案 0 :(得分:0)

您正在尝试向期望查询集的类提供单个对象。视图调用 <!DOCTYPE html> <html> <head> <title>Question-2</title> <meta charset="UTF-8"> <script src="q2.js"></script> </head> <body> <div id="myDIV" style="width:500px; ">Lorem ipsum dolor sit amet, porttitor ut donec ut egestas, purus urna consectetuer, arcu et vitae elementum nulla etiam in, sit leo lacus. Ligula cras tortor dignissim laoreet ut, nonummy hendrerit mauris, vitae augue congue congue, vel et augue, eros at. Fringilla id donec libero mauris eleifend. Nulla nunc sit. Consequat sodales placerat faucibus mauris, urna lectus vitae, sit nisl laoreet libero at suscipit ut, neque laoreet dapibus sapien. Sodales sit ut metus commodo tellus, ultricies cursus, et faucibus vitae quam, sit ultrices rhoncus. Massa duis mauris arcu vulputate, iste orci porttitor a ac, quisque venenatis pellentesque in in velit sed, repellat lorem consectetur vero, urna tellus donec. Suscipit in, donec beatae, lectus bibendum morbi justo consectetuer ac, facilisis metus vel non sapien vel. Magna congue vitae quia nulla nulla, lorem enim urna augue et et, sem morbi lorem ornare velit neque morbi, erat id et blandit iaculis.</div> </body> </ul> </html> 来执行此操作;

    class ModifyParagraph {
  constructor(div) {
    this.myDIV = div;
  }
  toggleBoldStyle() {
    // create the button.
    var btn = document.createElement('button');
    // give it some text/value.
    btn.textContent = 'toggle Bold styling';
    // add click event listener to the button.
    btn.addEventListener('click', function() {
      // if the font-weight is 800 make it 'normal' else if it's other than 800 make it 800'
      // add the 'this' keyword in the addEventListener method references the button, to get the member myDIV we'll just call it without preceding it by 'this'(myDIV in place of this.myDIV).
      myDIV.style.fontWeight = (myDIV.style.fontWeight === '800') ? 'normal':'800';
    });
    // append the button to the DOM
    this.myDIV.appendChild(btn);
  }
}
// testing...
var p = new ModifyParagraph(document.getElementById('myDIV'));
p.toggleBoldStyle();

您提供了一个查询集,以使其到达get_queryset,在您的示例中,该查询集正在您的类的实例上调用def get_queryset(self): """ Return the `QuerySet` that will be used to look up the object. This method is called by the default implementation of get_object() and may not be called if get_object() is overridden. """ if self.queryset is None: if self.model: return self.model._default_manager.all() else: raise ImproperlyConfigured( "%(cls)s is missing a QuerySet. Define " "%(cls)s.model, %(cls)s.queryset, or override " "%(cls)s.get_queryset()." % { 'cls': self.__class__.__name__ } ) return self.queryset.all()

要使用self.queryset.all()的{​​{1}} kwarg,您需要执行类似all()的操作

因此,您需要更改视图查找对象的方式;

queryset

默认情况下,as_view()这样做是为了获取对象; https://ccbv.co.uk/projects/Django/2.0/django.views.generic.edit/UpdateView/

如果将配置限制为1个对象,则还需要实现Singleton设计。本质上,这是确保只能存在1个对象的方法。在这里阅读更多; https://steelkiwi.com/blog/practical-application-singleton-design-pattern/

对于单身人士,有一个非常有用的软件包,名为django-solo