我在Django应用程序中有forms.py
。
from django import forms
from django.core.urlresolvers import reverse_lazy
class ComposeMessageForm(forms.Form):
ccc = reverse_lazy('user_api')
st = 'customSelectize:u_r,modelUrl:"'+ reverse_lazy('user_api') +'", choiceField:"username"'
user_receivers = forms.ModelMultipleChoiceField(
queryset=User.objects.all(),
required=False,
widget=forms.SelectMultiple(
attrs={
'data-bind': st,
'placeholder': 'Select USERS'}))
当我运行它时,我得到了
TypeError at /message/compose/
cannot concatenate 'str' and '__proxy__' objects
如何做到这一点?我不知道__proxy__
对象是什么。
urls.py
是:
from django.conf.urls import patterns, include, url
from rest_framework.urlpatterns import format_suffix_patterns
from django.contrib import admin
from msgin import views
urlpatterns = patterns('',
url(r'^$', 'ms.views.home', name='home'),
url(r'^message/', include('msgin.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^msgs/$', views.MessageList.as_view()),
url(r'^msgs/(?P<pk>[0-9]+)/$',
views.MessageDetail.as_view()),
url(r'^users/$', views.UserList.as_view(),
name='user_api'),
url(r'^users/(?P<pk>[0-9]+)/$',
views.UserDetail.as_view()),
url(r'^groups/$', views.GroupList.as_view(),
name='groups_api'),
url(r'^groups/(?P<pk>[0-9]+)/$',
views.GroupDetail.as_view()),
)
答案 0 :(得分:2)
把它放在 str() 里面
from django.utils.translation import ugettext_lazy as _
str(self.price) + " " + str(_("USD"))
答案 1 :(得分:0)
代理 url是稍后解析的网址,而不是在调用reverse_lazy()
func时解析的网址。对于这个具体案例,您可以使用简单的reverse()
函数而不是惰性函数。
但是如果你想将代理网址强制转换为字符串时使用reverse_lazy()
:
st = 'customSelectize:u_r,modelUrl:"'+ str(reverse_lazy('user_api')) +'", choiceField:"username"'
或使用字符串格式:
st = 'customSelectize:u_r,modelUrl:"%s", choiceField:"username"' % reverse_lazy('user_api')
答案 2 :(得分:0)
在类定义中使用reverse_lazy
没有任何好处,因为不能&#34;懒惰&#34;
你有两个选择
1)使用reverse
2)将您的代码更改为
class ComposeMessageForm(forms.Form):
user_receivers = forms.ModelMultipleChoiceField(queryset=User.objects.all(),
required=False)
def __init__(self, *args, **kwargs):
super(ComposeMessageForm, self).__init__(*args, **kwargs)
st = 'customSelectize:u_r,modelUrl:"%s", choiceField:"username"' % reverse_lazy('user_api')
self.fields['user_receivers'].widget=forms.SelectMultiple(attrs={'data-bind': st,
'placeholder': 'Select USERS'})