小编sch*_*eck的帖子

抑制 django 天真的日期时间警告

我关心涉及日期时间模块的脚本。我必须抑制“时区处于活动状态时对象收到一个简单的日期时间”,因为脚本中还有其他打印语句。我的代码如下

脚本:

from datetime import datetime
date = datetime.now()

objName = className.objects.create(param=value, param=value, param=value, time=date, attachment=attachment)
Run Code Online (Sandbox Code Playgroud)

模型.py

class className(models.MOdel):
    t = models.DateTimeField(null=True, blank=True)
Run Code Online (Sandbox Code Playgroud)

如何抑制天真的日期时间警告?

python django datetime

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

使用分段上传将文件放到Amazon S3

我正在尝试通过分段上传来上传带有Amazon Java SDK的文件.我们的想法是将upload-id传递给applet,applet将文件部分放入readonly-bucket中.通过这种方式,我避免将AWS凭证存储在applet中.

在我的测试中,我使用boto(python)生成upload-id并将文件存储到存储桶中.这很好用.

我的Applet从S3获得"403 Access denied",我不知道为什么.

这是我的代码(部分来自http://docs.amazonwebservices.com/AmazonS3/latest/dev/llJavaUploadFile.html):

AmazonS3 s3Client = new AmazonS3Client();
List<PartETag> partETags = new ArrayList<PartETag>();

long contentLength = file.length();
long partSize = Config.getInstance().getInt("part_size");
String bucketName = Config.getInstance().getString("bucket");
String keyName = "mykey";
String uploadId = getParameter("upload_id");

try {
    long filePosition = 0;
    for (int i = 1; filePosition < contentLength; i++) {

        partSize = Math.min(partSize, (contentLength - filePosition));

        // Create request to upload a part.
        UploadPartRequest uploadRequest = new UploadPartRequest()
            .withBucketName(bucket).withKey(keyName)
            .withUploadId(uploadId).withPartNumber(i)
            .withFileOffset(filePosition)
            .withFile(file)
            .withPartSize(partSize);

        // …
Run Code Online (Sandbox Code Playgroud)

java applet amazon-s3

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

在get_resource_uri中构建反向URL

如果有人阅读Tastypie-Mailinglist:我没有在那里得到答案,很抱歉在这里交叉.

在Tastypie中,我更改了Resource的URL模式,因为我使用的是另一个键而不是PK.当我访问资源时,这工作正常.现在我想将此资源嵌套到父资源中,但嵌套的资源包含带有PK的URI,而不是我的自定义密钥.我学到的是,在我的情况下,我必须改变孩子的get_resource_uri.

我孩子的资源(NamespacedResource)中的方法如下所示:

def get_resource_uri(self, bundle_or_obj):

    obj = bundle_or_obj.obj if isinstance(bundle_or_obj, Bundle) else bundle_or_obj

    kwargs={
        'resource_name': self._meta.resource_name,
        'custom_id': obj.custom_id
        }

    return self._build_reverse_url('api_dispatch_detail', kwargs=kwargs)
Run Code Online (Sandbox Code Playgroud)

孩子的网址覆盖方法是这样的:

def override_urls(self):
    return [
        url(r"^(?P<resource_name>%s)/(?P<custom_id>[-_\w\d]+)%s$" % (
                self._meta.resource_name,
                trailing_slash()
            ),
            self.wrap_view('dispatch_detail'),
            name="api_dispatch_detail"
        ),
    ]
Run Code Online (Sandbox Code Playgroud)

但是应用程序无法反转URL.我收到此错误:

Reverse for 'api_dispatch_detail' with arguments '()' and keyword arguments '{'custom_id': u'3_ee5-4423', 'resource_name': 'myresource'} not found.
Run Code Online (Sandbox Code Playgroud)

如何正确反转URL?

提前致谢.

django tastypie

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

搜索多个字段

我想我不会正确地解读django-haystack:

我有一个包含几个字段的数据模型,我想搜索其中两个:

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True, default=None)
    twitter_account = models.CharField(max_length=50, blank=False)
Run Code Online (Sandbox Code Playgroud)

我的搜索索引设置:

class UserProfileIndex(SearchIndex):
    text = CharField(document=True, model_attr='user')
    twitter_account = CharField(model_attr='twitter_account')

    def get_queryset(self):
        """Used when the entire index for model is updated."""
        return UserProfile.objects.all()
Run Code Online (Sandbox Code Playgroud)

但是当我执行搜索时,只搜索字段"username"; "twitter_account"被忽略.当我通过dbshel​​l选择Searchresults时,对象包含"user"和"twitter_account"的正确值,但结果页面显示"无结果":

    {% if query %}
        <h3>Results</h3>

        {% for result in page.object_list %}
            <p>
               <a href="{{ result.object.get_absolute_url }}">{{ result.object.id }}</a>
            </p>
        {% empty %}
            <p>No results</p>
        {% endfor %}
    {% endif %}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

python django django-haystack

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

自定义信号不起作用

我创建了一个信号:

sig_published = Signal()
Run Code Online (Sandbox Code Playgroud)

此信号放在signals.py中,我在models.py中导入:

from signals import sig_published
Run Code Online (Sandbox Code Playgroud)

在模型文件的页脚中,我将它连接到一个函数,为了测试目的,只打印出一个调试字符串:

def update_mode(sender, **kwargs):
    print "UPDATING"
sig_published.connect(update_mode, sender=MyModel)
Run Code Online (Sandbox Code Playgroud)

现在,在我的save() - Method中,我尝试发送一个信号:

sig_published.send(sender=self)
Run Code Online (Sandbox Code Playgroud)

但它没有打印出任何东西.如果我尝试像pre_save这样的内置信号:

pre_save.connect(update_mode, sender=MyModel)
Run Code Online (Sandbox Code Playgroud)

有用.有任何想法吗?

django django-signals

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

Drupal Ajax缓存

我正在更新我从D6写到D7的模块,因此必须通过新的#ajax表格交换旧的AHAH.

我正在执行一个ajax请求,它创建一个结果并用它替换一个表单元素.这基本上可以正常工作,但在第一次请求之后,结果会被缓存,并且不会考虑表单中的更改.我认为这可能是一个浏览器问题,但可能是Drupal发送了一个过期标头,导致浏览器采用缓存版本?还有其他想法吗?

hook_cache()中的片段:

  $form['fieldset']['mybutton'] = array(
    '#type' => 'button',   
    '#value' => t('Send request'),
    '#ajax' => array(
          'callback' => 'mycallback',
          'wrapper' => 'mywrapper',
          'method' => 'replace',
          'effect' => 'fade',  
    )
Run Code Online (Sandbox Code Playgroud)

一个回调片段:

function mycallback($form, $form_state) {

        [..]

        $form['fieldset']['mywrapper']['#markup'] = 'test';
        return $form['fieldset']['mywrapper']['#markup'];
    }
Run Code Online (Sandbox Code Playgroud)

php drupal drupal-7 drupal-modules

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

使用通用存储库更新实体失败

我有一个通用存储库:

    public class GenericRepository<TEntity> : AbstractRepository<TEntity>, IRepository<TEntity> where TEntity : class
    {
        private DbContext _context;
        [...]
        public GenericRepository(DbContext context)
        {
            _context = context;
            context.Configuration.AutoDetectChangesEnabled = true;
            _dbSet = _context.Set<TEntity>();
        }
        [...]
        public void SaveChanges()
        {
            _context.SaveChanges();
        }
        [...]
    public void Add(TEntity entity)
    {
        if (entity == null)
        {
            throw new ArgumentNullException("entity");
        }

        _dbSet.Add(entity);
    }
        [...]
    public virtual void Update(TEntity entity)
    {
        _context.Entry(entity).State = EntityState.Modified;
    }
Run Code Online (Sandbox Code Playgroud)

在我的控制器中,有以下代码:

    [HttpPost]
    public ActionResult Edit(Project project)
    {
          if (ModelState.IsValid)
        {
            if (project.Id == 0)
            { …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc entity-framework repository asp.net-mvc-4

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