小编AKS*_*AKS的帖子

Django中STATIC_URL和STATIC_ROOT之间有什么区别?

我对Django 'staticfiles'应用程序中STATIC_URL和STATIC_ROOT之间的区别感到困惑.

我相信我理解STATIC_ROOT它是什么:它本质上是服务器上的位置,staticfiles' collectstatic命令将放置从django项目收集的静态文件.该collectstatic命令将搜索您在STATIC_FINDERS设置中指定的位置.

但是,究竟做了STATIC_URL什么呢?这应该是什么?显然,它旨在设置一些用户可以访问静态文件的东西.但这与它的关系是什么STATIC_ROOT

为什么STATIC_URL简单的默认值/static/?是否STATIC_URL必须能够参考STATIC_ROOT

python django django-staticfiles

14
推荐指数
2
解决办法
5272
查看次数

以多种方式合并2个列表 - Python

我一直在尝试一些技术,但我确信这是完成这项工作的顺利方法.

假设我有两个列表,其中包含相同数量的项目(每个4个):

a = ['a', 'b', 'c', 'd']    
b = [1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

我想在保留订单的同时以所有可能的方式合并这些列表.示例输出:

a, b, c, d, 1, 2, 3, 4    
1, 2, 3, 4, a, b, c, d    
a, b, 1, 2, c, 3, 4, d
Run Code Online (Sandbox Code Playgroud)

关键是每个列表必须保留其顺序,因此考虑到它在列表中的位置,项目不能在输出中的另一个项目之前.所以例如输出不能是:

a, b, **d**, c, 1...   > d precedes c whereas c is before d in the original list
1, **4**, a, b, 3....  > 4 precedes 3 whereas 3 is before 4 in the original list
Run Code Online (Sandbox Code Playgroud)

我想这个想法是以所有可能的方式将第二个列表合并到第一个列表中.一个完全有效的例子是这样的:

a = [a, …
Run Code Online (Sandbox Code Playgroud)

python combinations list permutation

10
推荐指数
1
解决办法
198
查看次数

Django 序列化程序:未调用验证函数

我正在尝试validate()调用覆盖函数serializers.is_valid(),但它没有被调用。

序列化程序.py

class LoginSerializer(serializers.Serializer):
    email = serializers.EmailField(max_length=255,required=True)
    password = serializers.CharField(max_length=128,required=True)


    def validate(self,data):
       '''
       Check for invalid email.
       & blank email and password. 
       '''

       print 'hey i am in login'

       if data['email'] is '':
           raise serializers.ValidationError("Email cannot be empty.")
       if data['password'] is '':
          raise serializers.ValidationError("Password cannot be empty.")
       try:
          validate_email(data['email'])
       except ValidationError:
          raise serializers.ValidationError("The email is not a valid email address.")
       return data
Run Code Online (Sandbox Code Playgroud)

视图.py

class LoginAPI(APIView):
    permission_classes = (permissions.AllowAny,)
    serializer = LoginSerializer

    def post(self, request):
       data = …
Run Code Online (Sandbox Code Playgroud)

python django django-forms django-views django-rest-framework

6
推荐指数
1
解决办法
6581
查看次数

在 DetailView 中显示多个对象

我最近一直在涉足 Django CBV 并有一个问题。也许你有比我更好的想法。

假设我有一个航空公司预订 CRM 应用程序,我打算为各种事情执行客户的显示。假设我有一个列表Models,对于一个CustomerBookingRatingCustomer_Service_CallsFavourited_Route

现在,鉴于DetailView由 Django 的 CBV 实现,我有这样的东西

class CustomerThreeSixtyView(DetailView):
  model = 'Customer'

  def get_context_data(self, **kwargs):
      context = super(CustomerThreeSixtyView, self).get_context_data(**kwargs)
      context['bookings'] = Booking.objects.all.filter(customer_id=request.kwargs['pk']
      context['ratings'] = Ratings.objects.all.filter(customer_id=request.kwargs['pk']
      context['calls'] = Customer_Service_Calls.objects.all.filter(customer_id=request.kwargs['pk'], status'Open')
      context['fav_routes'] = Favourited_Route.objects.all.filter(customer_id=request.kwargs['pk'], status'Open')
      return context
Run Code Online (Sandbox Code Playgroud)

像这样的东西。我的问题是,有没有更好的方法来做到这一点?这是最直接的方法,但我正在寻求建议,因为似乎有些事情是必然的。

python django django-views

4
推荐指数
1
解决办法
257
查看次数

Django如何在Forms.py中进行链式选择?

class Library(forms.ModelForm):

    author = forms.ChoiceField(
        widget = forms.Select(),
        choices = ([
            ('Jk Rowling','Jk Rowling'), 
            ('agatha christie','agatha christie'),
            ('mark twain','mark twain'), 
        ]),
        initial = '1', 
        required = True,
    )
    books = forms.ChoiceField(
        widget = forms.Select(), 
        choices = ([
            ('Harry Potter 1','Harry Potter 1'),  # 1
            ('Harry Potter 2','Harry Potter 2'),  # 2
            ('Harry Potter 3','Harry Potter 3'),  # 3
            ('Harry Potter 4','Harry Potter 4'),  # 4
            ('The A.B.C. Murders','The A.B.C. Murders'),  # 5
            ('Dumb Witness','Dumb Witness'),  # 6
            ('Death on the …
Run Code Online (Sandbox Code Playgroud)

django django-forms django-views chained-select

4
推荐指数
1
解决办法
3537
查看次数

Pandas read_html 导致 TypeError

我正在使用 bs4 来解析一个 html 页面并提取一个表格,下面给出的示例表格,我试图将它加载到 Pandas 中,但是当我打电话时,pddataframe = pd.read_html(LOTable,skiprows=2, flavor=['bs4'])我得到下面列出的错误,但我可以打印由 bs4 美化的表格

有什么建议可以解决这个问题,而无需获取每个 td 并逐一读取?

样品表

<table cellpadding="5" cellspacing="0" class="borders" width="100%">
    <tr>
     <th colspan="2">
      Learning Outcomes
     </th>
    </tr>
    <tr>
     <td class="info" colspan="2">
      On successful completion of this module the learner will be able to:
     </td>
    </tr>
    <tr>
     <td style="width:10%;">
      LO1
     </td>
     <td>
      Demonstrate an awareness of the important role of Financial Accounting information as an input into the decision making process.
     </td>
    </tr>
    <tr>
     <td style="width:10%;">
      LO2
     </td> …
Run Code Online (Sandbox Code Playgroud)

python pandas

3
推荐指数
1
解决办法
3301
查看次数

在JavaFX中获取Shape对象的宽度和高度

我有需要的任何子类的方法Shape(可以是Circle,Rectangle,Polygon,Line,等...),并返回一个Shape对象.

public Shape returnShapeObject() {
   return circle1;
}
Run Code Online (Sandbox Code Playgroud)

问题是,一旦我得到了我的圆的形状对象表示,它就不再有.getRadius()方法了.它没有.getWidth().getHeight()任何一个.

如何在2d JavaFX中获取Shape对象的半径/宽度/高度呢?

java geometry 2d javafx

2
推荐指数
1
解决办法
2345
查看次数

Django中由多个IntegerRangeField组成的选择字段

我正在尝试创建一个模型,其中一个字段应该是 Age 字段,但它不是一个简单的数字 ( IntegerField),而是需要是几个可用年龄范围的 Choice (5-8, 8-12, 12-18, 18-99, 5-99)。我正在查看 Choices 的文档,但我什至不确定我可以直接IntegerRangeField在其中使用 an ,所以我最终得到了这样的结果:

class Person(models.Model):
    FIRST_RANGE = IntegerRangeField(blank=True, validators=[MinValueValidator(5), MaxValueValidator(8)])
    SECOND_RANGE = IntegerRangeField(blank=True, validators=[MinValueValidator(8), MaxValueValidator(12)])
    THIRD_RANGE = IntegerRangeField(blank=True, validators=[MinValueValidator(12), MaxValueValidator(18)])
    FOURTH_RANGE = IntegerRangeField(blank=True, validators=[MinValueValidator(18), MaxValueValidator(99)])
    FIFTH_RANGE = IntegerRangeField(blank=True, validators=[MinValueValidator(18), MaxValueValidator(99)])

    AGE_CHOICES = (
        (FIRST_RANGE, '5-8'),
        (SECOND_RANGE, '8-12'),
        (THIRD_RANGE, '12-18'),
        (FOURTH_RANGE, '18-99'),
        (FIFTH_RANGE, '5-99'),
    )

    age = models.IntegerRangeField(blank=True, choices=AGE_CHOICES)
Run Code Online (Sandbox Code Playgroud)

这是正确的方法吗?这对我来说看起来有点尴尬,我正在考虑只使用 Char 来代替,尽管我想坚持在最后在这个字段上有一个范围......

谢谢!

django postgresql

2
推荐指数
1
解决办法
364
查看次数

限制从SQL查询返回无值

我正在使用Odoo ERP,我想限制从生成SQL查询中的字典列表返回无值.

form_data = self.read(cr, uid, ids, ['start_date','end_date'], context=context)[0]
sql = "select i.date_invoice, i.number, (select name from res_partner where id=i.partner_id) as partner,i.currency_id, (select name from res_currency where id=i.currency_id) as currency, (select description from account_tax where name=t.name), t.amount, t.base, (t.amount+t.base) as total from account_invoice i, account_invoice_tax t where t.invoice_id = i.id and i.state = 'open' and i.type = 'out_invoice' and i.date_invoice >= '%s' and i.date_invoice <= '%s' order by t.name"%(form_data['start_date'],form_data['end_date']) 

cr.execute(sql)
data = cr.dictfetchall()
Run Code Online (Sandbox Code Playgroud)

生成结果:

data=[
    {'currency_id': 38, 
    'description': u'GST 7%', …
Run Code Online (Sandbox Code Playgroud)

python sql postgresql openerp odoo-8

2
推荐指数
1
解决办法
471
查看次数

Python3:TypeError:'int'对象不可调用

Python3:TypeError: 'int' object is not callable是因为我调用方法的.area()方式错了吗?或者是因为我说的方式.area()是错的?谢谢

class Rectangle: 
    def __init__ (self):
        self.height = 0
        self.width = 0
        self.area = 0

    def setData(self, height, width):
        self.height = height
        self.width = width

    def area(self, height, width):
        self.area = height * width

    def __str__(self):
        return "height = %i, width = %i" % (self.height, self.width)
        return "area = %i" % self.area

if __name__ == "__main__":
    r1 = Rectangle()
    print (r1)
    r1.setData(3,4)
    print (r1)
Run Code Online (Sandbox Code Playgroud)

在这里我打电话.area(),我想问题来自哪里:

    r1.area(3,4)
    print …
Run Code Online (Sandbox Code Playgroud)

python oop python-3.x

2
推荐指数
1
解决办法
3091
查看次数

Python拆分列表元素

我有一个清单:

lines = [['1 1 4.59114 0.366832 -9.56424 '], ['2 1 5.24742 -0.870574 -8.40649 '], ['3 2 5.21995 -0.38856 -7.39145 ']]
Run Code Online (Sandbox Code Playgroud)

我想按如下方式拆分列表中的每个元素:

[['1', '1 4.59114', '0.366832', '-9.56424'], ['2', '1', '5.24742', '-0.870574', '-8.40649 '], ['3', '2', '5.21995', '-0.38856', '-7.39145']]
Run Code Online (Sandbox Code Playgroud)

我尝试了以下代码:

m = []
for i in range(len(lines)):
    a = re.split(r'\t+', lines[i].rstrip('\t').split(",")
    m.append(a)
Run Code Online (Sandbox Code Playgroud)

但是,split不适用于单个列表元素。有任何想法吗?

python list

1
推荐指数
1
解决办法
1586
查看次数

查询集何时使用_result_cache,而不是访问数据库?

我对查询集使用它_result_cache或它直接命中数据库的时间感到困惑.

例如(在python shell中):

user = User.objects.all()  # User is one of my models   
print(user)  # show data in database (hitting the database)   
print(user._result_cache)  # output is None   
len(user)  # output is a nonzero number  
print(user._result_cache)  # this time, output is not None   
Run Code Online (Sandbox Code Playgroud)

所以,我的问题是:

  1. 为什么_result_cache就是None命中数据库后?
  2. 查询集是否被评估意味着_result_cache不是None
  3. 查询集何时使用它_result_cache,而不是命中数据库?

django orm django-queryset

1
推荐指数
1
解决办法
675
查看次数