简体   繁体   English

如何将额外的 object 传递给 Django 表单,以便在模板中呈现一些字段?

[英]How do I pass an additional object to a Django form so I can render some fields in the template?

I have a form in Django where site visitors can submit "gear" to be included in a person's set of gear.我在 Django 中有一个表格,网站访问者可以在其中提交“装备”以包含在一个人的装备中。 Here's the URL to the change form:这是更改表格的 URL:

# urls.py

path('person/<slug:slug>/gear/submit/', GearSubmitView.as_view(), name='forms/submit_gear'),

You can see that the person for whom the gear is being submitted is represented by a slug in the URL.您可以看到正在为其提交装备的人由 URL 中的 slug 表示。

Here's the first part of the CreateView :这是CreateView的第一部分:

# views.py

class GearSubmitView(LoginRequiredMixin, CreateView):
    """Allows for third-party submissions for a pro's gear collection."""
    template_name = 'forms/submit_gear.html'
    form_class = GearSubmitForm
    success_message = 'Success: Submission added.'

And the form:和形式:

# forms.py

class GearSubmitForm(forms.ModelForm):
    class Meta:
        model = PersonProduct
        fields = ['product', 'version', 'setup_note', 'usage_start_date', 'evidence_link', 'evidence_text']

where PersonProduct is a junction table between my Person and Product models.其中PersonProduct是我的PersonProduct模型之间的连接表。

And the template:和模板:

# submit_gear.html

{% extends '_base.html' %}
{% load crispy_forms_tags %}

{% block content %}
    <div class="container">
        <h2 id="content-header">Submit Gear For {{ person.full_name }}</h2>
        {% crispy form %}
    </div>
{% endblock content %}

where you can see what I'm trying to do.在那里你可以看到我正在尝试做的事情。 I want to insert the name of the person represented by the slug in the URL in the form template .我想在表单模板的 URL 中插入由蛞蝓代表的人的姓名

How can I do it?我该怎么做?

You can override get_context_data method in your views.py as mentioned in FormMixin .FormMixin中所述,您可以在您的views.py中覆盖get_context_data方法。

class GearSubmitView(LoginRequiredMixin, CreateView):
    """Allows for third-party submissions for a pro's gear collection."""
    template_name = 'forms/submit_gear.html'
    form_class = GearSubmitForm
    success_message = 'Success: Submission added.'

    def get_context_data(self, **kwargs):
        data = super().get_context_data(**kwargs)
        person = Person.objects.filter(slug=self.kwargs.get("slug")).first()
        data['full_name'] = person.full_name if person else ""
        return data

You can change the variable name with full_name in the html file.您可以在 html 文件中使用full_name更改变量名称。 You can also pass whole instance if you need, I just minimize the data sending from view to html.如果需要,您也可以传递整个实例,我只是最小化从视图发送到 html 的数据。 I didn't run the code block above but it should something like this.我没有运行上面的代码块,但它应该是这样的。

Here you can use the get_context_data method inside of your createview it will look like:在这里,您可以在 createview 中使用 get_context_data 方法,它看起来像:

def get_context_data(self, **kwargs):
   context = super().get_context_data(**kwargs)
   context['user'] = self.request.user
   return context

and on your template you will add:在您的模板上,您将添加:

{{user}}

Hope it help you out !希望对您有所帮助!

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

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