小编Joh*_*fis的帖子

自定义Django Admin更改密码页面

我想拥有自己的自定义change_password页面,我已经在使用Django的管理员登录(使用from django.contrib.auth.decorators import login_required).
管理员登录工作但想要更改change_password页面.

我怎么做?
我不确定如何链接到管理员登录,或者因为我想自定义我的change_password,我还必须自定义我的管理员登录?

需要一些指导.谢谢...

django django-admin

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

Django orm group by multiple columns

如何在Django中执行多列组?
我只看过一个列组的例子.
下面是我想要转换为Django ORM的查询.

SELECT order_id,city,locality,login_time,sum(morning_hours),sum(afternoon_hours),sum(evening_hours),sum(total_hours) 
FROM orders 
GROUPBY order_id,city,locality,login_time`
Run Code Online (Sandbox Code Playgroud)

django django-models django-orm

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

use_required_attribute()缺少1个必需的位置参数:“ initial” django形式

我写了一个动态表格:

class VoteForm(forms.Form):
    def __init__(self, *args, **kwargs):
        question = kwargs.pop('instance', None)
        super().__init__(*args, **kwargs)

        if question:
            if question.allow_multiple_votes:
                choice_field = forms.ModelMultipleChoiceField(queryset=question.choice_set)
            else:
                choice_field = forms.ModelChoiceField(queryset=question.choice_set)
            choice_field.widget = forms.RadioSelect
            choice_field.label=False
            choice_field.empty_label=None
            choice_field.error_messages={'required': _('No choice selected.'),
                                         'invalid': _('Invalid choice selected.')}
            self.fields['choice'] = choice_field
Run Code Online (Sandbox Code Playgroud)

没有RadioSelect窗口小部件,一切似乎都可以正常工作,但是使用它,会发生以下错误:

TypeError:use_required_attribute()缺少1个必需的位置参数:“ initial”

python forms django

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

分页在 DRF APIView 中不起作用

我用于APIView获取和发布项目。
我想使用 Django Rest Framework 为我的 API 实现分页,但它不起作用。

我想每页显示 10 个项目,但是当我这样做时api/v1/items?page=1,我会得到所有项目,如果我这样做,api/v1/items我会得到一个空列表。

这是我所做的:

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

class ItemsAPIView(APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request, format=None):
        """
        Return a list of all items of this user.
        """
        reply = {}
        page = request.GET.get('page')
        print ('page is', page)
        try:
            products = BaseItem.objects.owned_items().filter(owner=request.user)
            reply['data'] = OwnedItemSerializer(products, many=True).data

            items = BaseItem.objects.filter(owner=request.user)
            paginator = Paginator(items, 1)
            items_with_pagination = paginator.page(page)
            if page is not None:
                reply['data'].extend(ItemSerializer(items_with_pagination, many=True).data)
            reply['data'].extend(ItemSerializer(items, …
Run Code Online (Sandbox Code Playgroud)

python django pagination django-rest-framework

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

从Sanic应用程序的蓝图中检索配置

我有一个Sanic应用程序,并且想要app.config从其持有的蓝图中进行检索MONGO_URL,然后将其从蓝图传递到存储库类。

但是,我找不到如何获得app.config蓝图。我也检查了Flask解决方案,但它们不适用于Sanic。

我的app.py

from sanic import Sanic
from routes.authentication import auth_route
from routes.user import user_route

app = Sanic(__name__)
app.blueprint(auth_route, url_prefix="/auth")
app.blueprint(user_route, url_prefix="/user")

app.config.from_envvar('TWEETBOX_CONFIG')
app.run(host='127.0.0.1', port=8000, debug=True)
Run Code Online (Sandbox Code Playgroud)

我的auth blueprint

import jwt
from sanic import Blueprint
from sanic.response import json, redirect
from domain.user import User
from repository.user_repository import UserRepository
...

auth_route = Blueprint('authentication')
mongo_url = ?????
user_repository = UserRepository(mongo_url)
...

@auth_route.route('/signin')
async def redirect_user(request):
    ...
Run Code Online (Sandbox Code Playgroud)

python flask python-3.x sanic

4
推荐指数
2
解决办法
1509
查看次数

卸载应用程序 A,因为应用程序 B 在一次旧迁移中具有依赖项

我正在尝试卸载名为 的应用程序django-cities,但在我的应用程序“位置”中,我有一个名为 的模型Venue,在迁移中该0001_initial.py模型的ForeingKeytocities.Subregion模型为django-cities

我继续删除django-citiesINSTALLED_APPS但出现以下错误:

Traceback (most recent call last):
  File "/home/d/.virtualenvs/beplay/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper
    fn(*args, **kwargs)
  File "/home/d/.virtualenvs/beplay/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 128, in inner_run
    self.check_migrations()
  File "/home/d/.virtualenvs/beplay/local/lib/python2.7/site-packages/django/core/management/base.py", line 422, in check_migrations
    executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
  File "/home/d/.virtualenvs/beplay/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 20, in __init__
    self.loader = MigrationLoader(self.connection)
  File "/home/d/.virtualenvs/beplay/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 52, in __init__
    self.build_graph()
  File "/home/d/.virtualenvs/beplay/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 274, in build_graph
    raise exc
django.db.migrations.exceptions.NodeNotFoundError: Migration places.0001_initial dependencies reference nonexistent parent …
Run Code Online (Sandbox Code Playgroud)

python django django-models django-migrations

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

在 geodjango 中按距离(整个表)排序的效率如何

假设我有以下数据模型

Person(models.Model):
    id       = models.BigAutoField(primary_key=True)
    name     = models.CharField(max_length=50)
    location = models.PointField(srid=4326)
Run Code Online (Sandbox Code Playgroud)

还假设我有一个应用程序可以查询这个 django 后端,这个应用程序的唯一目的是从最近到最远返回注册用户的(分页)列表。

目前我有这个查询:

# here we are obtaining all users in ordered form
current_location = me.location
people = Person.objects.distance(current_location).order_by('distance')

# here we are obtaining the first X through pagination
start_index = a
end_index = b

people = people[a:b]
Run Code Online (Sandbox Code Playgroud)

虽然这有效,但它没有我想要的那么快。

我对这个查询的速度有些担心。如果表很大(100 万+),那么数据库(带有 PostGIS 的 Postgres SQL)在对随后的 100 万行执行之前是否必须测量数据库中current_location每个之间的距离?locationorder_by

有人可以建议如何以有效的方式正确返回按距离排序的附近用户吗?

python django postgresql geodjango

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

如何在django中的Model字段之间执行算术运算

序幕:

这是SO中经常出现的问题:

也可以在这里应用:

我已经在SO文档中编写了一个示例,但由于文档将于2017年8月8日关闭,我将遵循这个广泛上升和讨论的元答案的建议,并将我的示例转换为自我回答的帖子.

当然,我也很乐意看到任何不同的方法!


题:

假设以下型号:

class MyModel(models.Model):
    number_1 = models.IntegerField()
    number_2 = models.IntegerField()
    date_1 = models.DateTimeField()
    date_2 = models.DateTimeField()
Run Code Online (Sandbox Code Playgroud)

如何在此模型的字段之间执行算术运算?

例如,我如何找到:

  • MyModel对象的产品number_1number_2
  • 如何过滤date_210天或以上的物品date_1

python django

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

通过 Geodjango 中的几何交集关联两个模型

在 GeoDjango 中,两个有两个包含几何字段的模型:

from django.contrib.gis.db import models 

class Country(models.Model):
    territory = models.MultiPolygonField()
    language = models.CharField(max_length=2)

class House(models.Model):
    location = models.PointField()
Run Code Online (Sandbox Code Playgroud)

我想进行一个查询,返回位于说英语的国家/地区的所有房屋。
Country 和 House 之间的关系应该通过House.location与相交来完成Country.territory

我如何使用 GeoDjango 的 ORM 来实现这一点?

python django postgis geodjango

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

用Django识别哪个多边形包含一个点?

我需要快速识别 Django 1.9 中一组点属于哪些多边形。

第一个选项是循环遍历所有多边形并检查它们包含哪些点:

for countrypolygon in countrypolygons:
    placesinthecountry = Place.objects.filter(lnglat__intersects=countrypolygon.geom)
Run Code Online (Sandbox Code Playgroud)

这需要很多时间,因为我需要循环遍历很多多边形。

是否可以做相反的事情,即循环遍历每个点并立即获取包含该点的多边形?

python django polygon geodjango intersect

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