简体   繁体   English

如何在Django中为CreateView和UpdateView创建通用模板

[英]How To Create Generic Templates for CreateView and UpdateView in Django

I have quite a few models in my django project, and I'm trying to avoid having to create an html template for all of them. 我的django项目中有很多模型,并且我试图避免为所有模型创建html模板。 I'm trying to create a number of views that use the same template. 我正在尝试创建许多使用相同模板的视图。

For example, I have an email model: 例如,我有一个电子邮件模型:

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})

Then I have the view: 然后我有看法:

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

Then the template: 然后是模板:

{% 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 %}

What I would like to do is repeatedly create simple views like this, pass in the form action url to tell which view will process the form data, and just use the same template over and over. 我想做的就是反复创建这样的简单视图,传递表单操作url来告诉哪个视图将处理表单数据,并反复使用相同的模板。

I tried to pass in a variable (action_url) into the context, but it will not render the template correctly. 我试图将变量(action_url)传递到上下文中,但是它将无法正确呈现模板。 I've also tried to pass the full html for the form in as a variable in the context, but that hasn't worked either. 我也尝试过将表单的完整html作为上下文中的变量传递,但这也不起作用。 I've turned autoescape off for those parts of the template. 我已经为模板的那些部分关闭了自动转义。

I'm sure it's something simple, but I can't quite figure it out. 我敢肯定这很简单,但是我不太清楚。

You don't need to use the {{}} inside the tag, since you're already in "code", as it were. 您不需要使用标签内的{{}} ,因为您已经在“代码”中了。 This works fine: 这工作正常:

<form action="{% url action_link %}" method="POST">

But also note that you are simply posting the form back to the URL that rendered it anyway, so you can just skip the whole creation of action_link and just use the "." 但也请注意,您只是将表单重新发布回呈现该表单的URL,因此您可以跳过整个action_link创建过程,而只需使用“”即可。 signifier: 指示符:

<form action="." method="POST">

reverse the url in your view, get the full url to the action and then pass that url to the template. reverse您视图中的网址,获取操作的完整网址,然后将该网址传递给模板。

{{}} won't work like that inside {% %} {{}}{% %}内部将无法正常工作

So do this in the view: 因此,在视图中执行以下操作:

context['action_link'] = reverse('people_and_property:email-create')

And in the template: 并在模板中:

<form action="{{ action_link }}" method="POST">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM