我需要做的是运行一个函数并在该函数返回的结果的开头附加一个前缀.每次为我的模型创建新实例时都需要执行此操作.
我试过的......
以下操作无效,因为您无法将字符串添加到函数中,并将ID设置为s_<function name etc>而不是函数的结果.
APP_PREFIX = "_s"
id = models.CharField(primary_key=True, max_length=50, unique=True,
default="{}{}".format(APP_PREFIX, make_id))
Run Code Online (Sandbox Code Playgroud)
也不会将前缀传递给函数,因为Django每次以这种方式调用函数时都会生成相同的键,不知道为什么:
id = models.CharField(primary_key=True, max_length=50, unique=True,
default=make_id(APP_PREFIX))
Run Code Online (Sandbox Code Playgroud)
这也不起作用:
id = models.CharField(primary_key=True, max_length=50, unique=True,
default=make_id + APP_PREFIX)
Run Code Online (Sandbox Code Playgroud)
或这个:
id = models.CharField(primary_key=True, max_length=50, unique=True,
default=make_id() + APP_PREFIX)
Run Code Online (Sandbox Code Playgroud)
怎么能实现这一目标?
我可以覆盖该save()方法并实现此目的,但必须有一种方法可以使用字段上的默认参数执行此操作!
我有一个完美的文件上传,但我想为它写一个测试,所以我做了以下....
def test_post_ok(self):
image = Image.new('RGB', (100, 100)
tmp_file = tempfile.NamedTemporaryFile(suffix='.jpg')
image.save(tmp_file)
payload = {
"name": "Test",
"thumbnail_image": tmp_file
}
api = APIClient()
api.credentials(Authorization='Bearer ' + self.token)
response = api.post(url, payload, format='multipart')
Run Code Online (Sandbox Code Playgroud)
但是,测试给出错误...
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=1024x768 at 0x108A5DCF8>
{'thumbnail_image': [u'The submitted file is empty.']}
Run Code Online (Sandbox Code Playgroud)
我假设我没有正确地做到这一点,如果不是为什么?
我有一个过滤器,我需要在其中访问request.user. 但是, django-filter 没有通过它。在不使用混乱的inspect.stack()情况下,有没有办法在member_filter下面的方法中获取当前用户?
class ClubFilter(django_filters.FilterSet):
member = django_filters.MethodFilter(action='member_filter')
class Meta:
model = Club
fields = ['member']
def member_filter(self, queryset, value):
# get current user here so I can filter on it.
return queryset.filter(user=???)
Run Code Online (Sandbox Code Playgroud)
例如,这有效但感觉不对......
def member_filter(self, queryset, value):
import inspect
request_user = None
for frame_record in inspect.stack():
if frame_record[3] == 'get_response':
request_user = frame_record[0].f_locals['request'].user
print(request_user)
Run Code Online (Sandbox Code Playgroud)
有没有办法将它添加到一些将用户注入所有方法的中间件中?或者,还有更好的方法?
我用来boot2docker安装但最近为Mac安装了Docker ToolBox应用程序(运行10.11).当我打开iTerm并输入时,docker ps我收到以下消息.
Get http:///var/run/docker.sock/v1.20/containers/json: dial unix /var/run/docker.sock: no such file or directory.
* Are you trying to connect to a TLS-enabled daemon without TLS?
* Is your docker daemon up and running?
Run Code Online (Sandbox Code Playgroud)
我用来使用boot2docker所以我假设现在需要ToolBox.我启动了Docker quick start terminal只在终端内部工作的应用程序.但是,我想在我自己的终端等中使用docker.
为什么我会收到此错误?怎么修?
如何将self.key下面传递给装饰者?
class CacheMix(object):
def __init__(self, *args, **kwargs):
super(CacheMix, self).__init__(*args, **kwargs)
key_func = Constructor(
memoize_for_request=True,
params={'updated_at': self.key}
)
@cache_response(key_func=key_func)
def list(self, *args, **kwargs):
pass
class ListView(CacheMix, generics.ListCreateAPIView):
key = 'test_key'
Run Code Online (Sandbox Code Playgroud)
我收到错误:
'self' is not defined
Run Code Online (Sandbox Code Playgroud) 我想在模型上设置非持久属性。我尝试了以下方法:
class class User(models.Model):
email = models.EmailField(max_length=254, unique=True, db_index=True)
@property
def client_id(self):
return self.client_id
Run Code Online (Sandbox Code Playgroud)
然后:
user = User.objects.create(email='123', client_id=123)
print(user.client_id)
Run Code Online (Sandbox Code Playgroud)
我收到错误:无法设置attribute。为什么?
你怎么能让你的本地Django开发服务器认为它使用SSH隧道在你的AWS网络中运行?
我的场景,我正在运行本地Django服务器,即python manage.py runserverRedis作为缓存后端(Elasticache).当我的应用程序在AWS环境中运行时,它可以访问Elasticache,但是,本地它不会(这是一件好事).如果由于某种原因我想用Elasticache测试我的本地环境,我需要以某种方式使用SSH隧道使AWS认为它在VPC网络内运行.
我试过通过使用下面的方法来实现这一点.我已经确认我可以使用SSH隧道连接本地连接Redis桌面管理器,因此100%我知道AWS支持这一点,我的问题现在与Django做同样的事情.
这就是我尝试过的:
> python manage.py runserver 8000
> ssh -i mykey.pem ec2-user@myRandomEC2.com -L 6379:localhost:6379
Run Code Online (Sandbox Code Playgroud)
我访问时收到消息"错误60连接到"消息http://127.0.0.1:8000/.
我在这里做错了什么?
笔记:
ec2-user@myRandomEC2.com 不是Redis服务器,只是AWS上的另一个EC2实例,它可以访问我想用作隧道的Elasticache. mykey.pem访问和正确的权限.尽管存在数据,但以下模板未输出任何内容.
我的问题是......我是否可以将"点"对象的内容转储到模板中,这样我才能看到它里面有什么?
template.py
<h3>{% trans "Points" %}</h3>
{% if points %}
<p>{% trans "Total Points" %}: {{ points.Points }}</p>
<table>
<thead>
<tr>
<th>{% trans "Transaction" %}</th>
<th>{% trans "Status" %}</th>
<th>{% trans "Points" %}</th>
</tr>
</thead>
<tbody>
{% for item in points.Points_items.all %}
<tr>
<td>{{ item.transaction_description }}</td>
<td>{{ item.get_status_display }}</td>
<td>{{ item.points }}</td>
</tr>
{% endfor %}
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud) 我需要上传并读取CSV然后保存到数据库.我是初学者,下面是我迄今为止使用'django-adapters'(http://django-adaptors.readthedocs.org/en/latest/index.html)所取得的成就.我知道它不是很多,但我'我只是这样做了解更多:)
我在代码的视图中苦苦挣扎(下图).我不知道如何上传然后将文件读入CodeCSvModel()函数?谁能帮忙解释一下?非常感谢.:)
views.py
from django.template import RequestContext
from django.shortcuts import render_to_response
from web.forms import codeUploadForm
from web.csvTools import CodeCSvModel
def codeImport(request):
# If we had a POST then get the request post values.
if request.method == 'POST':
form = codeUploadForm(request.POST, request.FILES)
# handle_uploaded_file(request.FILES['file'])
====[HELP HERE]=====
#form = codeUploadForm(request.POST)
CodeCSvModel.import_from_file(form['file'])
else:
form = codeUploadForm()
context = {'form':form}
return render_to_response('import.html', context, context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)
forms.py
class codeUploadForm(forms.Form):
file = forms.FileField()
place = forms.ModelChoiceField(queryset=Incentive.objects.all())
Run Code Online (Sandbox Code Playgroud)
csvTool.py
from datetime import datetime
from adaptor.fields import *
from adaptor.model …Run Code Online (Sandbox Code Playgroud) 今天我收到一封来自 Celery 的错误电子邮件,有人可以解释一下它以及如何解决超时问题吗?这将非常有帮助,谢谢。
PS 尽管出现此错误,但我的消息似乎已发送,这也是对的吗?
错误:
Task Request to Process with id 65123935-b190-4718-9ed0-fb863359f27f
raised exception:
'TimeLimitExceeded(300.0,)'
Task was called with args: (<Batch: Batch object>,) kwargs: {}.
The contents of the full traceback was:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/billiard/pool.py", line 496, in on_hard_timeout
raise TimeLimitExceeded(job._timeout)
TimeLimitExceeded: TimeLimitExceeded(300.0,)
--
Just to let you know,
py-celery at w1.ip-10-32-53-113.
Run Code Online (Sandbox Code Playgroud)
任务:
class ProcessRequests(Task):
name = "Request to Process"
max_retries = 1
default_retry_delay = 3
def run(self, batch):
# Only run this task on …Run Code Online (Sandbox Code Playgroud) python ×9
django ×7
boot2docker ×1
docker ×1
macos ×1
python-2.7 ×1
python-3.x ×1
redis ×1
ssh ×1
ubuntu ×1