小编Osc*_*lal的帖子

如何在基于django类的视图上使用permission_required装饰器

我在理解新CBV如何工作方面遇到了一些麻烦.我的问题是,我需要登录所有视图,其中一些是特定权限.在基于函数的视图中,我使用@permission_required()和视图中的login_required属性执行此操作,但我不知道如何在新视图上执行此操作.django文档中是否有一些部分解释了这一点?我没找到任何东西.我的代码有什么问题?

我尝试使用@method_decorator,但它回复" / errors/prueba/_wrapped_view()中的TypeError至少需要1个参数(0给定) "

这是代码(GPL):

from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required, permission_required

class ViewSpaceIndex(DetailView):

    """
    Show the index page of a space. Get various extra contexts to get the
    information for that space.

    The get_object method searches in the user 'spaces' field if the current
    space is allowed, if not, he is redirected to a 'nor allowed' page. 
    """
    context_object_name = 'get_place'
    template_name = 'spaces/space_index.html'

    @method_decorator(login_required)
    def get_object(self):
        space_name = self.kwargs['space_name']

        for i in self.request.user.profile.spaces.all():
            if i.url …
Run Code Online (Sandbox Code Playgroud)

django django-views django-authentication django-class-based-views class-based-views

151
推荐指数
6
解决办法
8万
查看次数

为什么在python中用字符串声明unicode?

我还在学习python,我有一个疑问:

在python 2.6.x中,我通常在文件头中声明编码,如下所示(如PEP 0263)

# -*- coding: utf-8 -*-
Run Code Online (Sandbox Code Playgroud)

在那之后,我的字符串像往常一样写:

a = "A normal string without declared Unicode"
Run Code Online (Sandbox Code Playgroud)

但每次我看到python项目代码时,都不会在标题处声明编码.相反,它在每个字符串声明如下:

a = u"A string with declared Unicode"
Run Code Online (Sandbox Code Playgroud)

有什么不同?这是为了什么目的?我知道Python 2.6.x默认设置ASCII编码,但它可以被头声明覆盖,那么每个字符串声明的重点是什么?

附录:似乎我已将文件编码与字符串编码混合在一起.谢谢你解释:)

python encoding utf-8

120
推荐指数
4
解决办法
15万
查看次数

django 1.5 - 如何在静态标记内使用变量

我目前正在将项目中的所有静态文件引用迁移到django 1.5引入的新{%static%}标记,但是我遇到了问题,在某些地方我使用变量来获取内容.使用新标签我不能,有什么方法可以解决这个问题吗?

当前代码:

<img src="{{ STATIC_URL }}/assets/flags/{{ request.LANGUAGE_CODE }}.gif" alt="{% trans 'Language' %}" title="{% trans 'Language' %}" />
Run Code Online (Sandbox Code Playgroud)

它应该是什么(这不起作用):

<img src="{% static 'assets/flags/{{ request.LANGUAGE_CODE }}.gif' %}" alt="{% trans 'Language' %}" title="{% trans 'Language' %}" />
Run Code Online (Sandbox Code Playgroud)

django django-templates django-staticfiles

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

如何使用AJAX和jQuery发布django表单

我已经查看了大量关于django AJAX表单的教程,但是每一个都告诉你一种方法,没有一个是简单的,因为我从未使用过AJAX,所以我有点困惑.

我有一个名为"note"的模型,它的模型形式,在模板内部我需要每次注释元素发送stop()信号(来自jQuery Sortables)django更新对象.

我目前的代码:

views.py

def save_note(request, space_name):

    """
    Saves the note content and position within the table.
    """
    place = get_object_or_404(Space, url=space_name)
    note_form = NoteForm(request.POST or None)

    if request.method == "POST" and request.is_ajax:
        msg = "The operation has been received correctly."          
        print request.POST

    else:
        msg = "GET petitions are not allowed for this view."

    return HttpResponse(msg)
Run Code Online (Sandbox Code Playgroud)

JavaScript的:

function saveNote(noteObj) {
    /*
        saveNote(noteObj) - Saves the notes making an AJAX call to django. This
        function is meant to be …
Run Code Online (Sandbox Code Playgroud)

javascript django ajax jquery django-templates

71
推荐指数
3
解决办法
9万
查看次数

Django - 从多个到多个字段中获取对象

我在模型中有一个名为"admins"的m2m字段,我需要从视图中获取该字段中所有选定的条目,即用户ID.然后使用用户ID获取每个用户的电子邮件.可能吗?

我想要做的确切事情是向该平台内的所有空间管理员发送大量的内容.

空间模型:

class Space(models.Model):

    """     
    Spaces model. This model stores a "space" or "place" also known as a
    participative process in reality. Every place has a minimum set of
    settings for customization.

    There are three main permission roles in every space: administrator
    (admins), moderators (mods) and regular users (users).
    """
    name = models.CharField(_('Name'), max_length=250, unique=True,
        help_text=_('Max: 250 characters'))
    url = models.CharField(_('URL'), max_length=100, unique=True,
        validators=[RegexValidator(regex='^[a-z0-9_]+$',
        message='Invalid characters in the space URL.')],
        help_text=_('Valid characters are lowercase, digits and \
    admins = …
Run Code Online (Sandbox Code Playgroud)

django many-to-many django-models django-orm

27
推荐指数
3
解决办法
4万
查看次数

根据模型属性获取django对象id

我有一个名为"Places"的基本模型,它具有以下视图:

def view_index(request, place_name):
Run Code Online (Sandbox Code Playgroud)

用户将使用以下URL访问该视图:

http://server.com/kansas
Run Code Online (Sandbox Code Playgroud)

"堪萨斯"是存储在模型"位置"内名为"名称"的字段中的值.

问题是我无法弄清楚如何根据对象名称获取对象id.有没有办法做到这一点?

django django-models django-urls django-views

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

如何在django admin中创建一个自动填充和自动递增字段

[ 更新:更改问题标题更具体]

对不起,如果我没有很好地提出问题,我无法想象如何做到这一点:

class WhatEver():
    number = model.IntegerField('Just a Field', default=callablefunction)
...
Run Code Online (Sandbox Code Playgroud)

callablefunction这个查询在哪里:

from myproject.app.models import WhatEver

def callablefunction():
    no = WhatEver.objects.count()
    return no + 1
Run Code Online (Sandbox Code Playgroud)

我想自动写下一个号码,我不知道怎么做.

callablefunction说它无法导入模型时出错,我认为必须有一种更简单的方法来执行此操作.甚至没有必要使用它,但我无法用pk编号来计算如何使用它.

我已经google了这个,我发现的唯一的事情是使用save()方法自动递增数字...但我想<textfield>在保存之前显示它...

你会怎么做?

python django django-models default-value django-admin

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

jQuery删除最后一个表列

我目前有一个表可以是N列和N行.在界面中我有一个按钮来删除最后一列,但我无法弄清楚如何td从所有行中删除td最后一行td,到目前为止我所取得的是删除第一行和最后一行,但是离开那里的其他人.

这是我的代码(仅删除当前的最后一个标题):

function removeTableColumn() {
    /*
        removeTableColumn() - Deletes the last column (all the last TDs).
    */
    $('#tableID thead tr th:last').remove(); // Deletes the last title
    $('#tableID tbody tr').each(function() {
        $(this).remove('td:last'); // Should delete the last td for each row, but it doesn't work
    });
}
Run Code Online (Sandbox Code Playgroud)

我错过了什么吗?

jquery html-table

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

如何在Mac OS X中记录python程序活动

我是Python编程的新手,所以我有这个问题:

如何使用Mac OS X将Python应用程序活动记录到/ var/log中?

我尝试使用syslog模块,但它似乎没有写任何东西.我也尝试使用日志记录模块,但我总是遇到权限错误.

我该怎么做?

更新:

import logging
import time
LOG_FILENAME = "/var/log/writeup.log" + time.strftime("%Y-%m-%d")
LOG_FORMAT = "%(asctime)s - %(filename)s - %(levelname)s - %(message)s"
log = logging.getLogger("main.py")
log.setLevel(logging.DEBUG)
ch = logging.FileHandler(LOG_FILENAME)
ch.setLevel(logging.DEBUG)
format = logging.Formatter(LOG_FORMAT)
ch.setFormatter(format)
log.addHandler(ch)
Run Code Online (Sandbox Code Playgroud)

python macos logging

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

django'str'对象不可调用

我在django中创建URL视图时遇到问题.它给了我这个错误(ferrol是一个Space对象):

TypeError at /spaces/ferrol/
'str' object is not callable
Request Method: GET
Request URL:    http://localhost:8000/spaces/ferrol/
Django Version: 1.2.3
Exception Type: TypeError
Exception Value:    
'str' object is not callable
Exception Location: /usr/local/lib/python2.6/dist-packages/Django-1.2.3-py2.6.egg/django/core/handlers/base.py in get_response, line 100
Run Code Online (Sandbox Code Playgroud)

这是代码:

空间/ models.py

class Space(models.Model):

"""
Basic spaces model.
"""
name = models.CharField(_('Name'), max_length=100, unique=True)
description = models.TextField(_('Description'))
date = models.DateTimeField(auto_now_add=True)

logo = models.ImageField(upload_to='spaces/logos',
                         verbose_name=_('Logotype'))
banner = models.ImageField(upload_to='spaces/banners',
                           verbose_name=_('Banner'))
Run Code Online (Sandbox Code Playgroud)

主urls.py

urlpatterns = patterns('',

# Django administration
(r'^admin/', include(admin.site.urls)),

(r'^spaces/', include('apps.spaces.urls')),

(r'^static/(?P<path>.*)$', 'django.views.static.serve',
    {'document_root': 'static'}),

) …
Run Code Online (Sandbox Code Playgroud)

django django-views django-generic-views

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