私信  •  关注

Sam

Sam 最近回复了
4 年前
回复了 Sam 创建的主题 » 如何在基于类视图的django模板中使用模型方法

你可以做的一件事是使用自定义 templatetags :

遵循以下步骤:

  1. 模板标记 在你的应用程序目录中
  2. book_filter.py __init__.py
  3. 里面 书本过滤器.py

书本过滤器.py

from django import template
egister = template.Library()

@register.filter
def total_price(amounts):
    total = 0
    for amount in amounts:
        total += amount.price
    return total

现在在html文件中,执行以下操作:

{% load book_filter %}

Total price of all books: {{object_list|total_price}}

使用此链接作为参考: custom-template-tags

5 年前
回复了 Sam 创建的主题 » 我怎样才能用python编写一个键顺序精确的字典呢?

上面的解决方案可能是您所需要的,但是如果您使用panda,您将得到一个中间数据帧,这使得操作、分析和可视化数据更容易(如果这是您想要的途径)。解决方案如下:

import datetime
import pandas as pd

k = ['date', 'deviceCategory', 'transactionId', 'productSku', 'productName', 'productCategoryHierarchy', 'channelGrouping', 'itemRevenue', 'itemQuantity']

v = [datetime.date(2019, 3, 5), 'desktop', 1551740677701, 60104621, '(not set)', 'sale/apartment/alicante/bajo-vinalopo/elx', 'Tráfico de Búsqueda de Pago - Venta', 0.0, 1]

df = pd.concat([pd.DataFrame(v, k)], axis=1)

# the dataframe
date                                                     2019-03-05
deviceCategory                                              desktop
transactionId                                         1551740677701
productSku                                                 60104621
productName                                               (not set)
productCategoryHierarchy  sale/apartment/alicante/bajo-vinalopo/elx
channelGrouping                 Tráfico de Búsqueda de Pago - Venta
itemRevenue                                                       0
itemQuantity                                                      1

dict = df.to_dict()
results = dict[0]
results

# the dictionary
{'date': datetime.date(2019, 3, 5),
 'deviceCategory': 'desktop',
 'transactionId': 1551740677701,
 'productSku': 60104621,
 'productName': '(not set)',
 'productCategoryHierarchy': 'sale/apartment/alicante/bajo-vinalopo/elx',
 'channelGrouping': 'Tráfico de Búsqueda de Pago - Venta',
 'itemRevenue': 0.0,
 'itemQuantity': 1}

如果不需要这个方法,就不要在视图上实现它,视图是ApiView的子类。它将自动发送方法不允许的响应。

您可以将该文件用作 脚本 以及 可导入模块 .

fibo.py(名为 fibo )

# Other modules can IMPORT this MODULE to use the function fib
def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while b < n:
        print(b, end=' ')
        a, b = b, a+b
    print()

# This allows the file to be used as a SCRIPT
if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))

参考: https://docs.python.org/3.5/tutorial/modules.html

4 年前
回复了 Sam 创建的主题 » python-从文件夹目录创建字典

试试附加的代码。它不包括您指定的id属性,但是可以很容易地将其添加到 tree = {} 部分代码。

def pathto_dict(path):
    for root, dirs, files in os.walk(path_):
        tree = {"name": root, "type":"folder", "children":[]}
        tree["children"].extend([pathto_dict(os.path.join(root, d)) for d in dirs])
        tree["children"].extend([{"name":os.path.join(root, f), "type":"file"} for f in files])
        return tree
5 年前
回复了 Sam 创建的主题 » 如何用pycharm安装Tkinter?

python已经安装了tkinter。它是一个基本模块,比如random或time,因此不需要安装它。

def save(self, *args, **kwargs):
        user = super(UserAdminChangeForm, self).save(*args, **kwargs)
        user.email = self.cleaned_data['email']
        user.username = self.cleaned_data['username']
        return user

必须重写save方法才能修复它。似乎Django因为一些未知的原因而不匹配这两个字段。

5 年前
回复了 Sam 创建的主题 » python无法连接到mysql数据库

不,mysql不能创建sqlite3数据库,因为这是两个不同的数据库管理系统,具有不同的数据类型、工具等。现在,忘掉mysql,只需使用sqlite3了解更多。看起来您正在尝试构建flask sqlalchemy应用程序(考虑到上面代码中的导入和注释)。如果你对python有一定的了解,这些东西很容易安装和运行,但是如果你不了解数据库,那么对于第一个、第二个甚至第三个项目来说,构建web应用并不是最好的选择。在启动应用程序之前,在数据库中获得更好的基础,否则这将是一个非常令人沮丧的过程。

使用python db api连接到sqlite3数据库如下所示:

# create connection
import sqlite3
connection = sqlite3.connect("databasename.db")

# create a cursor object
c = connection.cursor()

# execute a query
c.execute("sql query")

# commit the changes
connection.commit()

# close the connection
connection.close()

请阅读python db api文档以获取更多答案。我建议首先使用db api,这样在进入sqlalchemy之前,您可以更了解sql(orms很好,但是在使用它们之前,您确实应该对sql有一些了解)。

https://docs.python.org/3/library/sqlite3.html