我知道你可以使用字符串连接以彼此的方式创建全局常量:
define('FOO', 'foo');
define('BAR', FOO.'bar');
echo BAR;
Run Code Online (Sandbox Code Playgroud)
将打印'foobar'.
但是,我在使用类常量尝试执行相同操作时遇到错误.
class foobar {
const foo = 'foo';
const foo2 = self::foo;
const bar = self::foo.'bar';
}
Run Code Online (Sandbox Code Playgroud)
foo2的定义没有问题,但声明const bar会出错
解析错误:语法错误,意外'.',期待','或';'
我也尝试过使用像sprintf()这样的函数,但它不像左边的paren那样比字符串连接符'.'.
那么有没有什么方法可以创建类常量,而不是像foo2那样简单的设置案例?
与此问题相关,但扩展它 - 如何在formset中使用此技术?
我想在表单中使用当前登录的用户,但我正在使用formset中的表单.单个表单的引用解决方案是将request.user传递给init中的表单和进程.如何为formset中的每个表单添加kwargs?
我的代码中的示例:
在forms.py中
class NewStudentForm (forms.Form):
username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^\w+$',
help_text = _("Required. 30 characters or fewer. Alphanumeric characters only (letters, digits and underscores)."),
error_message = _("This value must contain only letters, numbers and underscores."))
first_name = forms.CharField(label=_('first name'), max_length=30 )
last_name = forms.CharField(label=_('last name'), max_length=30, )
email = forms.EmailField(label=_('e-mail address') )
password = forms.CharField(label=_('password'), max_length=64, )
class Meta:
model = User
fields = ("username","first_name", "last_name", "email", "password")
def __init__(self, *args, **kwargs):
self._user = …Run Code Online (Sandbox Code Playgroud) 编辑:虽然这篇文章是Django的ModelForm unique_together验证的副本,但是从ModelForm中删除'exclude'的接受答案是比其他问题中接受的答案更清晰的解决方案.
这是这个问题的后续行动.
如果我没有显式检查clean_title()函数中的unique_together约束,则django会抛出异常:
/ journal/journal/4中的IntegrityError
重复键值违反唯一约束"journal_journal_owner_id_key"
请求方法:POST
请求URL: http:// localhost:8000/journal/journal/4
异常类型:IntegrityError
异常值:重复键值违反唯一约束"journal_journal_owner_id_key"
例外位置:/Library/Python/2.6/site-packages/django/db/backends/util.py执行,第19行
但是我的印象是Django会通过引发ValidationError很好地强制执行这个约束,而不是我需要捕获的异常.
下面是我的代码,附带了一个额外的clean_title()方法,我将其用作解决方法.但我想知道我做错了什么,以致django没有以预期的方式强制执行约束.
谢谢.
型号代码:
class Journal (models.Model):
owner = models.ForeignKey(User, related_name='journals')
title = models.CharField(null=False, max_length=256)
published = models.BooleanField(default=False)
class Meta:
unique_together = ("owner", "title")
def __unicode__(self):
return self.title
Run Code Online (Sandbox Code Playgroud)
表格代码:
class JournalForm (ModelForm):
class Meta:
model = models.Journal
exclude = ('owner',)
html_input = forms.CharField(label=u'Journal Content:', widget=TinyMCE(attrs={'cols':'85', 'rows':'40'}, ), )
def clean_title(self):
title = self.cleaned_data['title']
if self.instance.id:
if models.Journal.objects.filter(owner=self.instance.owner, title=title).exclude(id=self.instance.id).count() > 0:
raise forms.ValidationError(u'You …Run Code Online (Sandbox Code Playgroud) 我有一个Spark TextArea:
<s:TextArea id="editor">
<s:textFlow>
<s:TextFlow id="_tf" >
<s:p>Lorem ipsum etc.</s:p>
<s:p>
<s:img source="http://example.com/example.jpg" />
</s:p>
<s:p>Aliquam tincidunt tempor etc.</s:p>
</s:TextFlow>
</s:textFlow>
</s:TextArea>
Run Code Online (Sandbox Code Playgroud)
还有一个添加图片的按钮:
<s:Button id="imageBtn"
label="insert image"
width="89"
click="imageBtn_clickHandler(event);" />
Run Code Online (Sandbox Code Playgroud)
以下脚本有效:
import flashx.textLayout.elements.*;
import mx.events.FlexEvent;
protected function imageBtn_clickHandler(evt:MouseEvent):void {
var img:InlineGraphicElement = new InlineGraphicElement();
img.source = "http://example.com/example.jpg";
var p:ParagraphElement = new ParagraphElement();
p.addChild(img);
_tf.addChild(p);
_tf.flowComposer.updateAllControllers();
editor.setFocus();
}
Run Code Online (Sandbox Code Playgroud)
但只附加到TextFlow的末尾.如何在TextArea中的活动插入符处插入InlineGraphicElement?我的第一个想法是这样的:
import flashx.textLayout.elements.*;
import mx.events.FlexEvent;
protected function imageBtn_clickHandler(evt:MouseEvent):void {
var img:InlineGraphicElement = new InlineGraphicElement();
img.source = "http://example.com/example.jpg";
var p:ParagraphElement;
//pseudocode
p = …Run Code Online (Sandbox Code Playgroud) 我正在尝试基于依赖项文件在virtual_env位置安装AMFAST.我在我当地的.profile,并通过运行并看到它列出来确认它的存在.但是,每当我运行针对虚拟环境的PIP时,gcc都会设置为目标i386和ppc.我也尝试过前置和PIP命令,但是gcc总是有标志.如何让gcc读取我的拱形文字?export ARCHFLAGS="-arch x86_64"envenv ARCHFLAGS="-arch i386 -arch x86_64"env ARCHFLAGS="-arch x86_64"-arch i386 -arch ppc -arch x86_64
例:
sudo pip install -E ~/Documents/project/project_env -r ~/Documents/project/trunk/django/dependencies.txt`
Run Code Online (Sandbox Code Playgroud)
输出
......
Running setup.py install for amfast
building 'amfast.encode' extension
gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arch ppc -arch x86_64 -pipe -I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c amfast/ext_src/encoder.c -o build/temp.macosx-10.6-universal-2.6/amfast/ext_src/encoder.o
/usr/libexec/gcc/powerpc-apple-darwin10/4.2.1/as: assembler (/usr/bin/../libexec/gcc/darwin/ppc/as or /usr/bin/../local/libexec/gcc/darwin/ppc/as) for architecture ppc not installed
Installed assemblers are:
/usr/bin/../libexec/gcc/darwin/x86_64/as for architecture …Run Code Online (Sandbox Code Playgroud) 我正在构建动态过滤器,我通过GET传递给查询集过滤器:
for k, v in request.GET.iteritems():
kwargs[str(k)] = str(v)
students = models.Student.objects.filter( **kwargs )
Run Code Online (Sandbox Code Playgroud)
它正在为我投掷的几乎所有查询工作.但是,我有一个相关的模型,有很多关系,Group.因此,学生可以成为许多团体的成员.我可以使用以下内容过滤属于特定组的学生:'groups__in='+str(group.id)
例如--//example.com/students/?groups__in=1
但我无法弄清楚如何过滤不属于任何群体的学生.我试过以下但没有成功:
groups__in=None # students == []
groups__exact=None # students == []
groups__iexact=None # FAIL not that I really expected this to work
groups__isnull=True # students == []
Run Code Online (Sandbox Code Playgroud)
最后一个版本是我希望实际工作的.我确信我可以通过修改顶部代码来实现这一点
if request.GET['something']:
students = models.Student.objects.exclude(groups__isnull=False)
else:
students = models.Student.objects.filter( **kwargs )
Run Code Online (Sandbox Code Playgroud)
所以我想问题就变成了,我怎么能创造出来
students = models.Student.objects.exclude(groups__isnull=False)
Run Code Online (Sandbox Code Playgroud)
使用.filter()?
作为这个问题的后续内容,我想确定正在发生的实际错误.我做错了什么,或者这是一个错误?
f = {'groups__isnull': 'True'}
students1 = models.Student.objects.filter( **f )
students2 = models.Student.objects.filter(groups__isnull=True)
Run Code Online (Sandbox Code Playgroud)
这两个查询应该相同,但不是.
作为参考,我的模型:
class Student (models.Model):
user = models.ForeignKey(User, unique=True, null=False, related_name='student')
teacher = models.ForeignKey(User, null=False, related_name='students')
assignment = models.ForeignKey(LabJournal, blank=True, null=True, related_name='students')
class JournalGroup (models.Model):
title = models.CharField(null=False, max_length=256)
owner = models.ForeignKey(User, null=True, related_name='journal_groups')
members = models.ManyToManyField(Student, blank=True, related_name='groups')
Run Code Online (Sandbox Code Playgroud) django ×4
django-forms ×2
apache-flex ×1
class ×1
const ×1
constants ×1
django-views ×1
filter ×1
flex-spark ×1
gcc ×1
image ×1
insertion ×1
macos ×1
many-to-many ×1
modelform ×1
php ×1
pip ×1
python ×1
textarea ×1
validation ×1
virtualenv ×1