隐藏 django modelform 中的字段

发布于 2024-11-15 02:06:47 字数 4387 浏览 4 评论 0原文

django 文档建议我可以从模板中识别隐藏/可见字段。我有两个模型:AddressInfo 和 PharmacyInfo。我需要从单个页面输入两个表的数据。我想隐藏 address_id 字段(来自 PharmacyInfo 模型)。我目前有:

    {% for form in formset %}
    {% if form.non_field_errors %}
        <div class="form_errors">
            {{ form.non_field_errors }}
        </div>
    {% endif %}

    {% for field in form.visible_fields%}
        <div class="field_content">                  
                <label>{{field.label_tag }}</label>
        <div class="field">

            {% if field.help_text %}
            <div class = "help_text">
                {{ field.help_text }}
            </div>
            {% endif %}               
                {{ field }}
                {{ field.errors }}
        </div> 
        </div>
    {% endfor %}
{% endfor %}



class PharmForm(ModelForm):
    class Meta:
        model = PharmInfo
        widgets = {
            'address_id': forms.HiddenInput()
        }



class AddressForm(ModelForm):
    class Meta:
        model = AddressInfo



class AddressInfo(models.Model):
    address_id = models.AutoField(primary_key=True)

    address_1 = models.CharField("Address Line 1", max_length = 64)
    address_2 = models.CharField("Address Line 2", max_length = 64, blank=True, null=True)
    address_3 = models.CharField("Address Line 3", max_length = 64, blank=True, null=True)
    address_4 = models.CharField("Address Line 4", max_length = 64, blank=True, null=True)
    town_city = models.CharField("Town or City", max_length = 32)
    post_code = models.CharField("Post Code", max_length = 8)
    phone = models.CharField("Phone Number - numbers 0-9 only", 
                        max_length = 16) #this must be numeric 0-9 only for auto-dial functionality.
    email = models.CharField("email address", max_length = 64) #must be valid email



class PharmInfo(models.Model):
    pharm_id = models.AutoField(primary_key=True)
    pharm_name = models.CharField("Pharamcy Name", max_length = 64)
    address_id = models.ForeignKey(AddressInfo, db_column="address_id")



def pharmView (request, id=None):
    pharmForm = PharmForm()
    addForm = AddressForm()
    if request.method == 'POST': #this is a form submission
        if id == None: #it's a new record
            pharmForm = PharmForm(request.POST)
            addForm = AddressForm(request.POST)
            if addForm.is_valid(): #add the address_id into the pharmForm.
                request.POST = request.POST.copy()
                request.POST['address_id'] = addForm.save().pk
                pharmForm = PharmForm(request.POST)
                if pharmForm.is_valid(): 
                    pharm = pharmForm.save()
                    return render_to_response('thanks.html', 
                        {'form1': pharmForm,
                         'form2': addForm},
                        context_instance=RequestContext(request),
                    )

        else: #it's an existing record
            pharm = PharmInfo.objects.get(pk=id)
            address = pharm.address_id
            pharmForm = PharmForm(request.POST, instance = pharm)
            addForm = AddressForm(request.POST, instance = address)
            if pharmForm.is_valid() and addForm.is_valid():
                pharmForm.save()
                addForm.save()
                return render_to_response('updateThanks.html',
                    {'form1': pharmForm,
                     'form2': addForm},
                    context_instance=RequestContext(request),
                )
    else: 
        if id != None: #form bound to a pharmacy record
            pharm = PharmInfo.objects.get(pk=id)
            address = pharm.address_id
            pharmForm = PharmForm(instance = pharm)
            addForm = AddressForm(instance = address)
            return render_to_response('institutions/pharm.html', 
                {'form1': pharmForm,
                 'form2': addForm},
                context_instance=RequestContext(request),
                )            

    return render_to_response('institutions/pharm.html', 
            {'form1': pharmForm,
             'form2': addForm},
            context_instance = RequestContext(request),
        )

此代码隐藏了address_id字段的输入框,但标签仍然显示。我想隐藏整个 div,但 'form.visible_fields' 并未将其从输出中排除。这让我抓狂。谁能告诉我如何以模板可见的方式标记 address_id 字段。

The django documentation suggests I can identify hidden / visible fields from within my template. I have two models, AddressInfo and PharmacyInfo. I need to enter data for both tables from a single page. I want to hide the address_id field (from the PharmacyInfo model). I currently have:

    {% for form in formset %}
    {% if form.non_field_errors %}
        <div class="form_errors">
            {{ form.non_field_errors }}
        </div>
    {% endif %}

    {% for field in form.visible_fields%}
        <div class="field_content">                  
                <label>{{field.label_tag }}</label>
        <div class="field">

            {% if field.help_text %}
            <div class = "help_text">
                {{ field.help_text }}
            </div>
            {% endif %}               
                {{ field }}
                {{ field.errors }}
        </div> 
        </div>
    {% endfor %}
{% endfor %}



class PharmForm(ModelForm):
    class Meta:
        model = PharmInfo
        widgets = {
            'address_id': forms.HiddenInput()
        }



class AddressForm(ModelForm):
    class Meta:
        model = AddressInfo



class AddressInfo(models.Model):
    address_id = models.AutoField(primary_key=True)

    address_1 = models.CharField("Address Line 1", max_length = 64)
    address_2 = models.CharField("Address Line 2", max_length = 64, blank=True, null=True)
    address_3 = models.CharField("Address Line 3", max_length = 64, blank=True, null=True)
    address_4 = models.CharField("Address Line 4", max_length = 64, blank=True, null=True)
    town_city = models.CharField("Town or City", max_length = 32)
    post_code = models.CharField("Post Code", max_length = 8)
    phone = models.CharField("Phone Number - numbers 0-9 only", 
                        max_length = 16) #this must be numeric 0-9 only for auto-dial functionality.
    email = models.CharField("email address", max_length = 64) #must be valid email



class PharmInfo(models.Model):
    pharm_id = models.AutoField(primary_key=True)
    pharm_name = models.CharField("Pharamcy Name", max_length = 64)
    address_id = models.ForeignKey(AddressInfo, db_column="address_id")



def pharmView (request, id=None):
    pharmForm = PharmForm()
    addForm = AddressForm()
    if request.method == 'POST': #this is a form submission
        if id == None: #it's a new record
            pharmForm = PharmForm(request.POST)
            addForm = AddressForm(request.POST)
            if addForm.is_valid(): #add the address_id into the pharmForm.
                request.POST = request.POST.copy()
                request.POST['address_id'] = addForm.save().pk
                pharmForm = PharmForm(request.POST)
                if pharmForm.is_valid(): 
                    pharm = pharmForm.save()
                    return render_to_response('thanks.html', 
                        {'form1': pharmForm,
                         'form2': addForm},
                        context_instance=RequestContext(request),
                    )

        else: #it's an existing record
            pharm = PharmInfo.objects.get(pk=id)
            address = pharm.address_id
            pharmForm = PharmForm(request.POST, instance = pharm)
            addForm = AddressForm(request.POST, instance = address)
            if pharmForm.is_valid() and addForm.is_valid():
                pharmForm.save()
                addForm.save()
                return render_to_response('updateThanks.html',
                    {'form1': pharmForm,
                     'form2': addForm},
                    context_instance=RequestContext(request),
                )
    else: 
        if id != None: #form bound to a pharmacy record
            pharm = PharmInfo.objects.get(pk=id)
            address = pharm.address_id
            pharmForm = PharmForm(instance = pharm)
            addForm = AddressForm(instance = address)
            return render_to_response('institutions/pharm.html', 
                {'form1': pharmForm,
                 'form2': addForm},
                context_instance=RequestContext(request),
                )            

    return render_to_response('institutions/pharm.html', 
            {'form1': pharmForm,
             'form2': addForm},
            context_instance = RequestContext(request),
        )

This code hides the input box for the address_id field but the label is still shown. I want to hide the whole div but 'form.visible_fields' isn't excluding it from the output. This is driving me nuts. Can anyone tell me how to mark the address_id field in a way visible to the template.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

白馒头 2024-11-22 02:06:47

如果您根本不打算在表单中编辑 address_id 字段,则应使用 exclude 元字段,如中所述使用形式

结果应如下所示:

class PharmForm(ModelForm):
    class Meta:
        model = PharmInfo
        exclude = ('address_id',)

请注意,这将阻止通过表单设置 address_id 字段(请检查文档中示例下的注释)。

If you don't intend on the address_id field to be edited at all in the form, you should use the exclude meta field as documented in Using a subset of fields in the form.

The result should look like:

class PharmForm(ModelForm):
    class Meta:
        model = PharmInfo
        exclude = ('address_id',)

Note that this will prevent the address_id field from being set through the form (check the note under the example in the docs).

遮云壑 2024-11-22 02:06:47

好的,看来我在模板中编辑了错误的代码。 添加

{% for field in form.visible_fields %}

我已将注释掉的部分 到模板中(我发现注释行很难在模板上看到)。一切都按照我的模板中的以下代码进行预期工作:

{% if form.non_field_errors %}
        <div class="form_errors">
            {{ form.non_field_errors }}
        </div>
    {% endif %}

    {% for field in form.visible_fields %}
    <div class="field_content">
        <label>{{ field.label_tag }}</label>  
    <div class="field">

        {% if field.help_text %}
        <div class = "help_text">
            {{ field.help_text }}
        </div>
        {% endif %}

        {{ field }}
        {{ field.errors }}
    </div> 
    </div>
    {% endfor %}

向所有花时间在这方面的人致歉(我本来会提前发布,但作为 Stackoverflow 的新手,我不被允许在发布后 8 小时内回答我自己的问题)。

OK, looks like I was editing the wrong code in my template. I'd added

{% for field in form.visible_fields %}

to a part of the template that I'd commented out (I find commented lines difficult to see on templates). Everything works as expected with the code below in my template:

{% if form.non_field_errors %}
        <div class="form_errors">
            {{ form.non_field_errors }}
        </div>
    {% endif %}

    {% for field in form.visible_fields %}
    <div class="field_content">
        <label>{{ field.label_tag }}</label>  
    <div class="field">

        {% if field.help_text %}
        <div class = "help_text">
            {{ field.help_text }}
        </div>
        {% endif %}

        {{ field }}
        {{ field.errors }}
    </div> 
    </div>
    {% endfor %}

Apologies to anyone who spent time on this (I would have posted early but being new to Stackoverflow I wasn't allowed to answer my own question within 8 hours of posting).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文