标签: django-1.7

PyDev + Django - 来自导入的未定义变量

具体来说,任何查询集都会导致:

users = User.objects.all().order_by('user_group__user_group_description', 'user_name')
Run Code Online (Sandbox Code Playgroud)

all() 在说 Undefined variable from import

这是在我的视图中的任何查询集上 - 然而服务器运行正常.我已经将django添加到强制内置,我重新安装了django,我甚至重新安装了pydev,它坚持这个变量不存在,但服务器无论如何都会正常运行.

为了让事情变得更烦人,它最近工作正常并且停止工作 - 没有对代码进行任何更改.

我不知道该尝试什么.

编辑:所以我有一个修复,但我不知道为什么这样做.
降级到Django 1.6.5然后重新升级到1.7,重建python解释器,解决了这个问题.不太理想,因为我的计算机上有1.6.5的文件,建议删除它们...

python aptana django pydev django-1.7

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

将Django的StaticLiveServerCase与登台服务器一起使用

我已经使用了一些功能测试StaticLiveServerCase.这适用于本地测试,但现在我也想测试我的登台服务器.我正在阅读这本书的作者提出了以下黑客攻击:

import sys
[...]

class NewVisitorTest(StaticLiveServerCase):

    @classmethod
    def setUpClass(cls):
        for arg in sys.argv:
            if 'liveserver' in arg:
                cls.server_url = 'http://' + arg.split('=')[1]
                return
        super().setUpClass()
        cls.server_url = cls.live_server_url

    @classmethod
    def tearDownClass(cls):
        if cls.server_url == cls.live_server_url:
            super().tearDownClass()

    # Now use self.server_url instead of self.live_server_url
Run Code Online (Sandbox Code Playgroud)

我调整它以调用super(LiveServerTestCase, cls).setUpClass()(以及tearDownClass),而不是使用"临时服务器",因为直截了当地忽略(大)父母的实现感觉不对.

仍然是一个黑客,我想知道是否存在更清洁的解决方案.Django确实有--liveserver自己的参数,但它只能用于更改临时服务器的绑定.

到目前为止,我已经提出了以下想法:

  • 子类化StaticLiveServerCase以解析参数,相应地更改live_server_url属性,并让临时服务器刚刚启动/停止使用.从理论上讲,某些性能会降低成本,使得测试的可靠性降低.
  • 利用Python的动态类型来确定运行时的基类(StaticLiveServerCase或某些StagingServerTestCase子类TransactionTestCase).这并不是一个黑客,我的IDE可能也不会喜欢它.
  • 编写委托给其中的第三个类StaticLiveServerTestCaseTransactionTestCase(组合而不是继承).看起来很多工作要实现这一点.

python django unit-testing django-1.7

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

如何在Django 1.7+中创建每个项目的initial_data fixture

在Django 1.7之前,我曾经fixtures在设置中定义了每个项目目录:

FIXTURE_DIRS = ('myproject/fixtures',)
Run Code Online (Sandbox Code Playgroud)

并使用它来放置我的initial_data.json夹具存储整个项目必不可少的默认.这对我来说效果很好,因为我可以通过将每个项目数据与特定于应用程序的数据分开来保持设计的清洁.

现在使用Django 1.7,initial_data不推荐使用夹具,建议数据迁移与应用程序的架构迁移结合在一起; 没有明显的选择全球每个项目的初始数据.

此外,新的迁移框架执行兼容应用程序(包括django.contrib.auth应用程序)的迁移之前安装所有旧的初始数据夹具.此行为导致我的包含默认组的fixture 无法安装,因为该auth_group表尚未存在于DB中.

有关如何(优雅地)所有迁移之后(或至少在auth应用程序迁移之后)运行灯具的建议?还是其他任何想法来解决这个问题?我发现夹具是提供初始数据的好方法,并希望有一种简单而干净的方式来声明它们的自动安装.新的RunPython太麻烦了,我认为它对大多数用途来说都是一种过度杀伤力; 它似乎只适用于每个应用程序的迁移.

django django-fixtures django-1.7 django-migrations

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

将transaction.commit_manually()升级到Django> 1.6

我继承了为Django 1.4编写的应用程序的一些代码.我们需要更新代码库以使用Django 1.7,并最终将1.8作为下一个长期支持版本.

在一些地方,它使用旧的风格@transaction.commit_manuallywith transaction.commit_manually:

我对一般的交易了解不多,但我想了解它们的用途,所以我可以删除它们(如果没有必要)或将它们升级到更新set_autocommit(False)或等效的.

我已经理解Django <1.5中的事务管理并不理想,并且对于大多数用例来说太复杂了.

数据库连接如下所示,没有特殊的事务管理.(使用Postgres 9.3)

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'dbname',
        'USER': 'user',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '',
    }
}
Run Code Online (Sandbox Code Playgroud)

没有特殊的交易中间件.

我发现以下观点特别令人费解.(编辑)的

@UserRequiredDecorator
class XMLModelView(View):

    @transaction.commit_manually
    def get(self, request, *args, **kwargs):
        user = request.user

        xml_models = models.XMLModel.objects.filter(user=user).order_by('-created').all()
        if xml_models:
            xml_model = xml_models[0]
            model = xml_model.xml_field
        else:
            obj = initialize_xml_model(user)
            model = obj.xml_field

        transaction.commit()
        if isinstance(model, unicode):
            model = model.encode('utf-8')

        with transaction.commit_manually():
            xml = XMLManipulator(model, remove_blank_text=True)
            xml.insert_user_info(user) …
Run Code Online (Sandbox Code Playgroud)

python xml django transactions django-1.7

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

在Django 1.7中删除app(和相关的数据库表)

是否可以使用Django 1.7迁移来完全删除/卸载应用程序及其所有跟踪(主要是其所有数据库表)?

如果没有,在Django 1.7中这样做的适当方法是什么?

python django django-1.7

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

将帮助文本添加到 django 管理视图中的只读字段

以下是我的管理视图:

@admin.register(AuditStashAwsMasterPolicies)
class AuditPoliciesAdmin(reversion.VersionAdmin):
exclude = ['source_policy_path', 'source_state', 'target_state']
readonly_fields = ['comparison_date', 'source', 'source_policy_name', 'target', 'target_policy_name',
                   'target_policy_path', 'policy_difference']

def policy_difference(self, instance):
    return drift.compare_two_policies(instance.source, instance.source_policy_name, instance.source_policy_path,
                                instance.target, instance.target_policy_name, instance.target_policy_path)
Run Code Online (Sandbox Code Playgroud)

我想要做的是在我的“policy_difference”只读字段中添加一些帮助文本。从帮助文档中,我只能通过修改模型并在那里创建一个带有帮助文本的只读字段来做到这一点。

问题是我没有在“policy_difference”字段中存储任何值,我只是即时生成它,并希望避免将其存储在模型中。

有什么方法可以在不更改模型 AuditStashAwsMasterPolicies 的情况下将文本添加到“policy_difference”只读字段?

django python-2.7 django-modeladmin django-1.7

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

Google&Oauthlib-范围已更改

我正在使用OAuthlib进行Google的OAuth流程。运行4到5个月效果良好。突然我开始出现以下错误:

File "/home/whitesnow-2/Gaurav/Axonator/AxVirtualEnv/local/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/parameters.py", 
line 409, in validate_token_parameters raise w Warning: Scope has changed from 
"https://www.googleapis.com/auth/calendar 
https://www.googleapis.com/auth/docs 
https://www.googleapis.com/auth/spreadsheets 
https://www.googleapis.com/auth/drive.file
https://www.googleapis.com/auth/userinfo.email 
https://www.googleapis.com/auth/userinfo.profile" to 
"https://www.googleapis.com/auth/calendar 
https://www.googleapis.com/auth/docs 
https://www.googleapis.com/auth/spreadsheets 
https://www.googleapis.com/auth/drive.file 
https://www.googleapis.com/auth/userinfo.email 
https://www.googleapis.com/auth/userinfo.profile".
Run Code Online (Sandbox Code Playgroud)

以下是用于生成OAuth授权URL的代码:

flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
            settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON,
            scopes=['https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/docs https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile'],
            redirect_uri=REDIRECT_URI
        )
    authorization_url, state = flow.authorization_url(
            access_type='offline',
            include_granted_scopes='true',
            prompt='consent'
        )
Run Code Online (Sandbox Code Playgroud)

以下是Google OAuth回调的代码:

auth_code = request.GET.get("code")
    objectid = request.GET.get("state")
    error = request.GET.get("error")
    if error == "access_denied":
        return "Access Denied"
    else:
        flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
            settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON,
            scopes=['https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/docs https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile'],
            redirect_uri=REDIRECT_URI
        )
        flow.fetch_token(code=auth_code)
Run Code Online (Sandbox Code Playgroud)

python python-2.7 google-oauth google-api-python-client django-1.7

8
推荐指数
4
解决办法
2928
查看次数

为“templatetags”使用自定义目录

有人知道它是否可能对“templatetags”使用自定义目录eje:“my-project/templatetags”

Normal
My-Project-Name
  My-App
    __init__.py
      templatetags
        __init__.py
Run Code Online (Sandbox Code Playgroud)

需要一些这样的

My-Project-Name
  templatetags
    __init__.py
Run Code Online (Sandbox Code Playgroud)

django django-1.7

7
推荐指数
2
解决办法
3387
查看次数

Django 1.7空白CharField/TextField约定

使用Django的新迁移框架,假设我有以下模型已存在于数据库中:

class TestModel(models.Model):
    field_1 = models.CharField(max_length=20)
Run Code Online (Sandbox Code Playgroud)

我现在想要为模型添加一个新的TextField,所以它看起来像这样:

class TestModel(models.Model):
    field_1 = models.CharField(max_length=20)
    field_2 = models.TextField(blank=True)
Run Code Online (Sandbox Code Playgroud)

当我尝试使用迁移此模型时python manage.py makemigrations,我收到以下提示:

You are trying to add a non-nullable field 'field_2' to testmodel without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows)
 2) Quit, and let me add a default in models.py
Run Code Online (Sandbox Code Playgroud)

我可以通过添加null=True来轻松解决这个问题field_2,但Django的惯例是避免在CharField和TextField等基于字符串的字段上使用null(来自 …

python django django-1.7 django-migrations

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

如何使用django formsets创建一个包含问题和答案的调查应用程序?

我需要创建一份调查表.不同类型的用户将在调查中回答不同的问题集.

models.py

from django.contrib.auth.models import Group, User

from django.db import models

ANSWER_CHOICES = (
    ('0', 'No'),
    ('1', 'Yes')
)


class Survey(models.Model):
    name = models.CharField(max_length=100)
    group = models.ForeignKey(Group)

    def __str__(self):
        return self.name


class Feature(models.Model):
    name = models.CharField(max_length=150)
    survey = models.ForeignKey(Survey)

    def __str__(self):
        return self.name


class Rating(models.Model):
    rating = models.IntegerField(choices=ANSWER_CHOICES)
    feature = models.ForeignKey(Feature)
    rating_for = models.ForeignKey(User, related_name='rated_user')
    rating_by = models.ForeignKey(User, related_name='rated_by')

    def __str__(self):
        return str.format("%s - %s", self.feature, self.rating)
Run Code Online (Sandbox Code Playgroud)

每个问题(特征)的答案(评级)是单选按钮的是或否.用户提交表单后,会将答案保存在评级表中.

django实现这个目标的方法是什么?

谢谢


forms.py

from django import forms
from django.forms import modelformset_factory, TextInput …
Run Code Online (Sandbox Code Playgroud)

django django-models django-forms django-1.7

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