我的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作为变量传递,但这也没有用。我已经为模板的那些部分关闭了autoescape。
我确信这很简单,但我无法弄明白。
答案 0 :(得分:2)
您不需要在代码中使用{{}}
,因为您已经在&#34;代码&#34;中。这很好用:
<form action="{% url action_link %}" method="POST">
但是请注意,您只是将表单发布回到呈现它的URL,因此您可以跳过action_link的整个创建,只需使用&#34;。&#34;能指:
<form action="." method="POST">
答案 1 :(得分:0)
IsVisible
您视图中的网址,获取操作的完整网址,然后将该网址传递给模板。
{{}}
在{% %}
在视图中这样做:
context['action_link'] = reverse('people_and_property:email-create')
在模板中:
<form action="{{ action_link }}" method="POST">