小编Sco*_*ott的帖子

django包含来自另一个应用程序的模板

在设置我的项目并努力使应用程序不依赖时,我遇到了麻烦.我希望来自不同应用程序的所有模板都具有一致的页眉和页脚.这是我正在尝试的:

myproject/
         base/
             templates/
                      header.html
                      footer.html
         app1/
             templates/
                      my_app1_page.html -> want to include 'header.html'
                                           and 'footer.html' from base app
Run Code Online (Sandbox Code Playgroud)

假装有更多的应用程序也想要这样做.这是可能的和/或正确的方法吗?

django templates

56
推荐指数
2
解决办法
3万
查看次数

按字段获取Queryset的不同值

我有这个型号:

class Visit(models.Model):
    timestamp  = models.DateTimeField(editable=False)
    ip_address = models.IPAddressField(editable=False)
Run Code Online (Sandbox Code Playgroud)

如果用户在一天内多次访问,如何根据ip字段筛选唯一行?(我想今天的独特访问)

today = datetime.datetime.today()
yesterday = datetime.datetime.today() - datetime.timedelta(days=1)

visits = Visit.objects.filter(timestamp__range=(yesterday, today)) #.something?
Run Code Online (Sandbox Code Playgroud)

编辑:

我看到我可以使用:

Visit.objects.filter(timestamp__range=(yesterday, today)).values('ip_address')
Run Code Online (Sandbox Code Playgroud)

获取只有ip字段的ValuesQuerySet.现在我的QuerySet看起来像这样:

[{'ip_address': u'127.0.0.1'}, {'ip_address': u'127.0.0.1'}, {'ip_address':
 u'127.0.0.1'}, {'ip_address': u'127.0.0.1'}, {'ip_address': u'127.0.0.1'}]
Run Code Online (Sandbox Code Playgroud)

如何在不评估QuerySet和获取数据库命中的情况下过滤此唯一性?

# Hope it's something like this...
values.distinct().count()
Run Code Online (Sandbox Code Playgroud)

django field distinct django-queryset

48
推荐指数
3
解决办法
6万
查看次数

Apollo 客户端片段未嵌入数据

这是我第一次冒险进入碎片,我看不出我哪里搞砸了,但它绝对行不通!在 GraphiQL 中它工作正常:

query Tasks($taskIds: [String]!) {
    tasks(taskIds: $taskIds) {
        ...taskDisplay
    }
}
fragment taskDisplay on Task {
    _id
    name
    description
    status
    children {
        _id
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的客户端应用程序中的内容:

import { gql } from "@apollo/client";

export const TASK_FRAGMENT = gql`
    fragment taskDisplay on Task {
        _id
        name
        description
        status
        children {
            _id
        }
    }
`;

export const TASKS = gql`
    query Tasks($taskIds: [String]!) {
        tasks(taskIds: $taskIds) {
            ...taskDisplay
        }
    }
    ${TASK_FRAGMENT}
`;
Run Code Online (Sandbox Code Playgroud)

因此,服务器返回的数据是正确的,正如我在Chrome 的“网络”选项卡中看到的那样,但结果接收到的数据useQuery是一个空对象。是什么赋予了?

使用@apollo/client@3.2.0-beta.2(我已经降级到3.1.0,结果相同) …

graphql apollo-client

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

流星文件上传

我看到之前已经问过这个问题,但是从那以后Meteor.http就没有了.我仍然在掌握Meteor的概念,文件上传完全是我的意思.

这是我的问题:
那么,在我认为正确的方法中,
Meteor.http.call("POST", url, [options], [asyncCallback])
你为网址添加了什么?通过meteor中的客户端/服务器javascript关系,它似乎并没有真正使用url.

如果有人在流星上有一个基本的文件上传示例,那就太棒了.

file-upload meteor

13
推荐指数
2
解决办法
7440
查看次数

Meteor/React - 如何等待Meteor.user()

我正在努力弄清楚如何Meteor.user()在react组件中等待订阅.我知道用户已登录因为Meteor.userId()返回_id,但尝试访问电子邮件地址show Meteor.user()返回undefined.我假设因为它尚未可用.

唉,既然Meteor.user()不是我手工订阅的出版物,我不知道如何在React组件中等待它.有人能指出我的榜样吗?

import { Meteor } from 'meteor/meteor';
import React from 'react';
import { Link } from 'react-router';
import { createContainer } from 'meteor/react-meteor-data';

import './BaseLayout.scss';


class BaseLayout extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            isAuthenticated: (Meteor.userId() !== null) ? true : false,
        }
    }

    componentWillMount() {
        if (!this.state.isAuthenticated) {
            this.context.router.push('/login');
        }
    }

    componentDidUpdate(prevProps, prevState) {
        if (!this.state.isAuthenticated) {
            this.context.router.push('/login');
        }
    }

    toggleUserMenu() {
        this.refs.userMenu.style.display = (this.refs.userMenu.style.display === 'block') ? …
Run Code Online (Sandbox Code Playgroud)

meteor meteor-react

8
推荐指数
2
解决办法
2015
查看次数

Django ForeignKey创建空?

这看起来非常基本,我一定会遗漏一些东西,但无论如何......

有两个这样的模型:

class School(models.Model):
    name    = models.CharField("Official School Name", max_length=128)
    address = models.TextField("Address of the School", max_length=256)
    mascot  = models.CharField("Name of the School Mascot", max_length=128)

class StudentProfile(models.Model):
    name   = models.CharField(max_length=128)
    school = models.ForeignKey(School)
Run Code Online (Sandbox Code Playgroud)

如果学生在学校之前创建,我如何给"学校"一个默认的空值?是空白还是什么

谢谢!

django foreign-keys

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

Django文件上传和模型FileField

我太近了......但是我没有看到从上传视图到模型的连接.当我在模型中使用回调时,FileField上传工作正常,但我不确定实际文件副本的发生位置.目标是确保chunking发生这种情况,但文件复制操作似乎隐藏在某处?

这就是我所拥有的:

模型:

def get_media_upload_dir(instance, filename):
    user_id  = instance.user.id
    upload_dir = "%s/%d/%s" % (settings.MEDIA_ROOT, user_id, filename)
    print "Upload dir set to: %s" % upload_dir
    return upload_dir

class MediaFile(models.Model):
    media_file     = models.FileField(upload_to=get_media_upload_dir)
    download_count = models.PositiveIntegerField(default=0)
Run Code Online (Sandbox Code Playgroud)

视图:

def file_upload(request, course_id):    
    if request.method == 'POST':
        form = FileUploadForm(request.POST, request.FILES)
        if form.is_valid():
            uploaded = form.cleaned_data['file_upload']
            mediaFile = MediaFile(media_file=uploaded,
                                owner=request.user.profile,
                                creator=request.user.profile)
            mediaFile.save()

            return HttpResponseRedirect('/course/%s/' % course_id)
    else:
        form = FileUploadForm()
    return render_to_response('course/file_upload.html', {'form':form,'course':course}, context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)

python django upload file

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

定向非循环图遍历...帮助?

我的深度有点偏离,需要给朋友打电话.我有一个我需要遍历的定向非循环图,我第一次绊到了图论.我最近一直在阅读很多关于它的内容,但不幸的是我没有时间在学术上解决这个问题.有人可以帮我解决一下如何处理这棵树吗?

以下是规则:

  • n个根节点(我称之为"源")
  • n个终端节点
  • 源节点带有数值
  • 下游节点(我称之为"工作"节点)对传入值(如Add,Mult等)执行各种操作.

正如你可以看到下面的图,节点a,bc需要被处理之前d,ef.

走这棵树的顺序是什么?

在此输入图像描述

traversal graph directed-acyclic-graphs

6
推荐指数
2
解决办法
5861
查看次数

django创建用户并将其登录

在一个视图中,我正在尝试创建一个新用户,然后将其登录,但会在成功时生成一个新URL.

def create(request):

    if request.method == "POST":

        # do user creation #
        user.save()

        auth_user = authenticate(username=user.username,password=user.password)

        if auth_user is not None:
            login(request, auth_user)

            return HttpResponseRedirect('/user/account/')

    return render_to_response('create_form.html')
Run Code Online (Sandbox Code Playgroud)

那么,如何在非关联视图中user使用HttpResponseRedirect或验证登录用户来维护对象?

django

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

将Postgres11部署到Elastic Beanstalk-需要/ etc / redhat-release

我在将我的第一个应用程序部署到Elastic Beanstalk时遇到了麻烦,真的可以使用一些帮助。尽管RDS正式支持Postgres11,但我无法安装它。

问题
如果我运行,eb deploy我会收到消息说pg_config找不到可执行文件。需要psycopg2从源代码构建。

/usr/lib64/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'project_urls'
  warnings.warn(msg)
running egg_info
creating pip-egg-info/psycopg2.egg-info
writing pip-egg-info/psycopg2.egg-info/PKG-INFO
writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt
writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt
writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt'

Error: pg_config executable not found.

pg_config is required to build psycopg2 from source.  Please add the directory
containing pg_config to the $PATH or specify the full executable path with the
option: ...
Run Code Online (Sandbox Code Playgroud)

我想我需要添加回购吗?很公平。接下来,我尝试添加回购协议,就像我在互联网上的其他帖子中所发现的那样:

[ec2-user@ip-... etc]$ sudo yum -y install https://download.postgresql.org/pub/repos/yum/11/redhat/rhel-7-x86_64/pgdg-centos11-11-2.noarch.rpm
Loaded plugins: priorities, …
Run Code Online (Sandbox Code Playgroud)

django postgresql amazon-web-services amazon-elastic-beanstalk

5
推荐指数
4
解决办法
2287
查看次数