简体   繁体   English

模板中的Django外键表单字段渲染

[英]Django foreign key form field rendering in template

I would like to create a view for multiple object deletion.我想为多个对象删除创建一个视图。 For this, I thought I could use a modelformset_factory .为此,我想我可以使用modelformset_factory

This are my models:这是我的模型:

class Item(models.Model):
    rfid_tag    = models.CharField()
    asset       = models.OneToOneField('Assets', default=None, null=True,
                                       on_delete=models.SET_DEFAULT,)
    date        = models.DateTimeField(name='timestamp',                     
                                       auto_now_add=True,)
...

class Assets(models.Model):
    id = models.AutoField(db_column='Id', primary_key=True)
    assettag = models.CharField(db_column='AssetTag', unique=True, max_length=10)
    assettype = models.CharField(db_column='AssetType', max_length=150)
...

    class Meta:
        managed = False
        db_table = 'Assets'
        ordering = ['assettag']

    def __str__(self):
        return f"{self.assettag}"

    def __unicode__(self):
        return f"{self.assettag}"

Below is the form and formset factory:下面是表单和表单集工厂:

class ItemDelete(forms.ModelForm):

    asset = forms.CharField(required=True,
                            help_text= "Item asset tag",
                            max_length=16,
                            )

    delete = forms.BooleanField(required=False,
                                label="Delete",
                                help_text='Check this box to delete the corresponding item',
                                )

    class Meta:
        model = Item
        fields = ['asset']

ItemDeleteMultiple= forms.modelformset_factory(model=Item,
                                         form=ItemDelete,
                                         extra=0,
                                         )

The view:风景:

class DeleteMultipleView(generic.FormView):
    template_name = *some html file*
    form_class = ItemDeleteMultiple
    success_url = *some url*

    def form_valid(self, form):
        return super().form_valid(form)

And the template:和模板:

{% extends "pages/base.html" %}

{% block title %}
    <title>Delete Multiple</title>
{% endblock %}

{% block static %}
    {% load static %}
{% endblock %}

{% block content %}
    <h1>Delete Multiple Items</h1>

    <form class="item_delete_multiple_form" action ="." method="POST"> {% csrf_token %}
        <table border="2">
            <tr><th colspan="3" scope="row">Select Items to Delete</th></tr>
            {% for item_form in form %}
            <tr>
                {% if item_form.non_field_errors %}
                    <td>{{ item_form.non_field_errors }}</td>
                {% endif %}
                {% if item_form.asset.errors %}
                    <td>{{item_form.asset.errors}}</td>
                {% endif %}
                <td><label for="{{ item_form.asset.id_for_label }}">AssetTag {{forloop.counter}}:</label></td>
                <td>{{item_form.asset}}</td>
                {% if item_form.delete.errors %}
                    <td>{{item_form.delete.errors}}</td>
                {% endif %}
                <td>{{item_form.delete}}</td>
            </tr>
            {% endfor %}
        </table>
    </form>
{% endblock %}
{% block script %}
{% endblock %}

The template is not very easy to the eye, so here is the important part: <td>{{item_form.asset}}</td> .模板不是很容易看,所以这里是重要的部分: <td>{{item_form.asset}}</td>

The issue is the following:问题如下:

If I don't add the asset = CharField() part in the ItemDelete form, the template will render what the __str__ / __unicode__ method of the Assets model will return (the assettag field) in a choice field.如果我不在ItemDelete表单中添加asset = CharField()部分,模板将在选择字段中呈现Assets模型的__str__ / __unicode__方法将返回的内容( Assets标签字段)。

If the asset field is a CharField in the form, the template will render the id of the Assets .如果资产字段是表单中的CharField ,模板将呈现Assets的 id。 The database entry in the Item table. Item表中的数据库条目。

I would like to render asset.assettag in a CharField (read only text input).我想在 CharField(只读文本输入)中呈现asset.assettag Is it possible to do this?是否有可能做到这一点?

Or is there a better way to achieve the multiple delete operation, using a list of objects and a checkbox?或者有没有更好的方法来实现多次删除操作,使用对象列表和复选框?

I have came to the following solution:我得出了以下解决方案:

class ItemDelete(forms.ModelForm):

    asset = forms.CharField(required=True,
                            help_text= "Item asset tag",
                            max_length=16,
                            disabled=True,
                            )

    delete = forms.BooleanField(required=False,
                                label="Delete",
                                help_text='Check this box to delete the corresponding item',
                                )

    def __init__(self, *args, **kwargs):
        super(ItemDelete,self).__init__(*args, **kwargs)
        self.initial['asset'] = Assets.objects.get(id=self.initial['asset']).assettag

    class Meta:
        model = Item
        fields = ['asset']

Given that the input field is used just for presentation purposes (is disabled and cannot be edited), I think it will do.鉴于输入字段仅用于演示目的(已禁用且无法编辑),我认为它可以。 The downside is that it will hit the database for every object (being a formset, every object will have it's own form).缺点是它会为每个对象访问数据库(作为一个表单集,每个对象都有自己的表单)。

I am still open to better suggestions.我仍然愿意接受更好的建议。

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

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