Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html Django自定义ChoiceField表单,带selected=selected_Html_Django_Forms_Choicefield - Fatal编程技术网

Html Django自定义ChoiceField表单,带selected=selected

Html Django自定义ChoiceField表单,带selected=selected,html,django,forms,choicefield,Html,Django,Forms,Choicefield,我有以下表格: POSSIBLE_POSITIONS = ( ('1', 'Brazo'), ('2', 'Muñeca'), ('3', 'Pierna'), ('4', 'Pie'), ) class PositionForm(forms.Form): position = forms.ChoiceField(choices = POSSIBLE_POSITIONS, label="", initial=1, widget=forms.Select(

我有以下表格:

POSSIBLE_POSITIONS = (
    ('1', 'Brazo'),
    ('2', 'Muñeca'),
    ('3', 'Pierna'),
    ('4', 'Pie'),
)

class PositionForm(forms.Form):
    position = forms.ChoiceField(choices = POSSIBLE_POSITIONS, label="", initial=1, widget=forms.Select(
        attrs={
            'class': 'form-control'
        }
    ))
以下是使用该位置的模型:

class User(models.Model):
    id = models.CharField(max_length=10, primary_key=True)
    position = models.CharField(max_length=1, choices=POSSIBLE_POSITIONS, default=1)
这是一种观点:

def modify(request):
    return render(request, 'interface/modify.html', {'user': User.objects.get(pk=id), 'device_list': Device.objects.all(), 'form': PositionForm()})
我想知道,如何根据当前user.Position选择默认位置

就像我在这里做的那样:

<select name="device_id" class="form-control">
   {% for device in device_list %}
      {% if device.id == user.device.id %}
         <option selected="selected">{{ device.id }}</option>
      {% else %}
         <option>{{ device.id }}</option>
      {% endif %}
   {% endfor %}
   {% if user.device.id == None %}
      <option selected="selected"> Sin dispositivo </option>
   {% else %}
      <option> Sin dispositivo </option>
   {% endif %}
</select>
但我不知道在这里怎么做:

<div class="form-group">
   <label>Posición actual dispositivo</label>
   {{ form }}
</div>

您可以通过在常规html中手动选择任何选项,就像这样

厚颜无耻 穆尼卡 彼尔纳 馅饼
如果我正确理解您的问题,您应该在您的观点中进行以下修改:

def modify(request):
    user = User.objects.get(pk=id)
    form = PositionForm(initial={'position': user.position})
    return render(request, 'interface/modify.html', {'user': user, 'device_list': Device.objects.all(), 'form': form})

如果我理解正确,你只需要做以下的姿势就可以了,1,2,3,4。我需要检查该用户的当前位置,并使该表单等于user.position所选的表单。你能告诉我密码吗?我不明白,我需要在多个地方加上那个表格。这也必须是一个模型的属性。如果我手动设置,我必须从所有位置手动更改可能性。