我的django项目中有很多模型,我试图避免为所有这些模型创建html模板。我正在尝试创建一些使用相同模板的视图。
例如,我有一个电子邮件模型:
class Email(models.Model):
EMAIL_TYPE = (
('work', 'work'),
('home', 'home'),
('other', 'other')
)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
owner = models.ForeignKey(Person, related_name='email_set')
address = models.EmailField()
primary = models.NullBooleanField(help_text='Is this the primary email address you use?')
type = models.CharField(max_length=25, choices=EMAIL_TYPE, null=True, blank=True)
def __str__(self):
return self.address
def get_absolute_url(self):
return reverse('people_and_property:email-detail', kwargs={'pk': self.pk})然后我就有了这样的看法:
class EmailCreate(PermissionRequiredMixin, CreateView):
"""
This view allows staff to create email objects
"""
model = Email
fields = ['owner', 'address', 'primary']
template_name = 'people_and_property/generic_create.html'
permission_required = 'people_and_property.can_add_email'
def get_context_data(self, **kwargs):
"""
This should add in the url for the template to send the data to.
"""
context = super(EmailCreate, self).get_context_data(**kwargs)
context['name_of_object'] = 'Email' # This tells the template what it is that we're editing
context['action_link'] = 'people_and_property:email-create'
return context然后模板:
{% extends "case_manager/employee-portal-base.html" %}
{% block content %}
<h2>Edit {{ name_of_object }}</h2>
<div class="form">
{% autoescape off %}
<form action="{% url {{ action_link }} %}" method="POST">
{% endautoescape %}
{% csrf_token %}
{{ form.as_ul }}
<BR>
<input type="submit" value="Submit Changes"/>
</form>
</div>
{% endblock %}我想要做的是反复创建像这样的简单视图,传入表单操作url来判断哪个视图将处理表单数据,并且只需要一遍又一遍地使用相同的模板。
我试图将一个变量(action_url)传递到上下文中,但是它不能正确地呈现模板。我还尝试将表单的完整html作为上下文中的变量传递,但这也不起作用。我已经关闭了模板的那些部分的自动转义。
我相信这是很简单的事情,但我不太明白。
发布于 2016-01-03 22:35:18
您不需要在标记中使用{{}},因为您已经在“代码”中了。这样做很好:
<form action="{% url action_link %}" method="POST">但是还要注意的是,您只是简单地将表单发回给呈现它的URL,所以您可以跳过整个action_link的创建过程,只需使用“。意符:
<form action="." method="POST">发布于 2016-01-03 22:20:15
reverse视图中的url,获取操作的完整url,然后将该url传递给模板。
{{}}不会在{% %}里面那样工作
因此,在视图中这样做:
context['action_link'] = reverse('people_and_property:email-create')在模板中:
<form action="{{ action_link }}" method="POST">https://stackoverflow.com/questions/34582227
复制相似问题