如何使用变量代替字符串进行表单操作?我尝试过以下操作并遇到错误。
URLS
url(r'^newrole', ModelCreateView.as_view(model = Role, model_url = 'role-new', page_name = 'Role'), name='role-new'),
url(r'^newmember', ModelCreateView.as_view(model = Member, model_url = 'member-new', page_name = 'Member'), name='member-new'),
查看
class ModelCreateView(CreateView):
model_url = None
page_name = None
template_name = 'create_model.html'
def get_success_url(self):
return reverse(model_url)
def get_context_data(self,**kwargs):
context = super(ModelCreateView, self).get_context_data(**kwargs)
context['page_name'] = self.page_name
return context
这两个都分别报告了以下错误
<form action="{% url {{model_url}} %}" method="POST">
<form action="{% url model_url %}" method="POST">
错误
Could not parse the remainder: '{{model_url}}' from '{{model_url}}'. The syntax of 'url'changed in Django 1.5, see the docs.
'url' requires a non-empty first argument. The syntax changed in Django 1.5, see the docs
有没有办法在不使用html文件中的一系列if语句的情况下执行此操作?
答案 0 :(得分:0)
是的,您可以使用reverse
。您可以在文档here中详细了解它。
from django.core.urlresolvers import reverse
def get_context_data(self,**kwargs):
context = super(ModelCreateView, self).get_context_data(**kwargs)
context['page_name'] = self.page_name
context['model_url'] = reverse("name of the url goes here")
return context
然后在您的模板中,您不使用网址模板标记。你只需使用变量。
<form action="{{ model_url }}" method="POST">
答案 1 :(得分:0)
这是对的:
<form action="{% url model_url %}" method="POST">
您只是不将model_url变量传递到模板上下文中,您需要添加一行:
def get_context_data(self,**kwargs):
context = super(ModelCreateView, self).get_context_data(**kwargs)
context['page_name'] = self.page_name
context['model_url'] = self.model_url # this line added
return context