簡體   English   中英

如何遍歷下拉模型表單字段以僅顯示Django中的某些值

[英]How do I loop through a drop down model form field to display only some values in Django

我有4個選擇

target = (('Week', 'Weekly target'),
          ('Day', 'Daily target'),
          ('Verify', 'Verify'),
          ('Done', 'Done'))

這是我實現選擇的模型:

class GoalStatus(models.Model):

    target = models.CharField(max_length=100, choices=target, default="Week")
    name = models.ForeignKey(ScrummyUser, on_delete=models.CASCADE)
    goal_status = models.ForeignKey(ScrummyGoals, on_delete=models.CASCADE)

這是我的模特表格

class ChangeTaskForm(forms.ModelForm):

    class Meta:
        model = GoalStatus
        fields = '__all__'

這是我的html文件

{% if user.is_authenticated %}
{% if request.user|has_group:"ADMIN" %}

    <form action="{% url 'myapp:move_goal' %}"  method="post">
        {% csrf_token %}
        {% for field in form.data.target %}
            {% for foo in field %}
                {% if foo == Day %}
                    {{ foo }}
                {% endif %}
            {% endfor %}

        {% endfor %}
    </form>

我如何遍歷表單中的下拉列表,以僅向有權選擇“天”的用戶顯示所需的選擇,例如“天”。 我是Django的新手。

在將表單發送到模板之前,所有邏輯都可以在后端( your views )中完成:

if request.user.groups.filter(name__iexact="ADMIN").exists():
    form.fields['target'].choices = ( ('Day', 'Daily target'))

由於您使用的是Django CBV,因此請重寫get_form()方法

def get_form(self, *args, **kwargs):
    form = super(ClassBasedView, self).get_form(*args, **kwargs)
    if self.request.user.groups.filter(name__iexact="ADMIN").exists():
        form.fields['target'].choices = ( ('Day', 'Daily target'))
    return form

您可以在ModelForm( 此處的ModelForm文檔 )中修改選擇。

以您的形式:

from ____ import target # idk where your target variable is but it needs to be visible to your ChangeTaskForm in here. So you may have to import it.

class ChangeTaskForm(forms.ModelForm):

    class Meta:
        model = GoalStatus
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super(ChangeTaskForm, self).__init__(*args, **kwargs)
        self.initialize_widgets()

    def initialize_widgets(self):
        """
        Initializes widgets for the form. This is not a built in
        method. It's a method I'm adding. You can manipulate any field 
        in the form along with their widgets. This is where the choices 
        can be filtered down from the overall choices to specific 
        choices.
        """
        target_choices_for_field = []
        for target_option_tuple in target: # loop through each option.
            can_choose_option = ... # This is where you do the logic to determine whether or not the option should be available.
            if can_choose_option:
                target_choices_for_field.append(target_option_tuple)
        self.fields["target"].widget = forms.Select(choices=target_choices_for_field)

然后,在您的html中:

{% if user.is_authenticated %}
{% if request.user|has_group:"ADMIN" %}

<form action="{% url 'myapp:move_goal' %}"  method="post">
    {% csrf_token %}
    {% form %}
    <input type="submit" value="submit">Submit</input>
</form>

現在,ModelForm已經處理了過濾代碼中的選項,因此您無需在模板中對此做任何事情。 通常最好將這樣的邏輯盡可能往下推。 因此,應該在表單類而不是模板中設置表單選擇。 附帶說明一下,您的驗證應執行相同的操作(將邏輯推得盡可能低)。 視圖修飾符@user_passes_test一起使用以處理組以進行身份​​驗證。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM