Django中选择字段的HTML标记

时间:2022-06-29 19:21:28

I cant seem to find ANYWHERE on how to do choicefield HTML tags in Django. I found radio buttons and other advance choice fields, but nothing on basic drop down HTML tags with Django. I have models.py and view.py set up passing list1 to the html pages, but cant seem to make it display anything except

我似乎无法找到如何在Django中选择HTML标签的任何地方。我找到了单选按钮和其他高级选择字段,但没有使用Django基本下拉HTML标签。我有models.py和view.py设置将list1传递给html页面,但似乎不能让它显示除了

<select style="width:300px">
  {% for choice in list1.VIEWS %}
  <option>{{choice}}</option>
  {{choice}}
  {% endfor %}
</select>

Help would be greatly appreciated

非常感谢帮助

models.py

class preset_list(models.Model):
    VIEWS = (
        ('1', 'X'),
        ('2', 'Y'),
    )
    query_choice = forms.ChoiceField(choices=VIEWS)

view.py

list1 = models.preset_list()
return render_to_response('services.html', 
         {'array':json.dumps(data, cls=SpecialEncoder),
         'list1':list1},
                          )

4 个解决方案

#1


6  

ModelForms are your friend here.

ModelForms是你的朋友。

models.py

class PresetList(models.Model):
    VIEWS = (
        ('1', 'X'),
        ('2', 'Y'),
    )
    query_choice = forms.ChoiceField(choices=VIEWS)

forms.py

from django.forms import ModelForm
from . import models

class PresetListForm(ModelForm):
    class Meta:
        model = models.PresetList

view.py

from . import forms

def my_view(request):

    preset_form = forms.PresetListForm()

    return render_to_response('services.html', {
        'array': json.dumps(data, cls=SpecialEncoder),
        'preset_form': preset_form,
    })

services.html

<form method=POST action="/somewhere">
    {{ preset_form.as_p }}
</form>

#2


2  

Give the generic CreateView a try.

尝试使用通用CreateView。

views.py

views.py

from django.views.generic.edit import CreateView
from .models import PresetList

class PresetListCreate(CreateView):
    model = PresetList

presetlist_form.html

presetlist_form.html

<form action="" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Create" />
</form>

#3


1  

Not sure what you want done, but if you eant to send 1 when X is displayed, the following should work:

不确定你想要做什么,但如果你想在显示X时发送1,以下应该有效:

<select style="width:300px">
  {% for choice in list1.VIEWS %}
  <option value={{choice.0}}>{{choice.1}}</option>
  {{choice}}
  {% endfor %}
</select>

#4


1  

You can create a form with a drop-down and tell it which values to populate it with like so:

您可以创建一个带有下拉列表的表单,并告诉它填充它的值如下:

Form

形成

class MyDropDownForm(forms.ModelForm):
    somerow = forms.ModelChoiceField(
        # change this queryset if you want to limit the options
        queryset= MyModel.objects.all().values('somerow'),
        widget=Select(),
        required=True,
    )        

    class Meta:
        model = MyModel
        fields = ['somerow']

View

视图

class MyView(DjangoTemplateView):

    def get(self, request):
        # you can set an instance when creating the form to set the value
        # to be that of an existing row in your model
        # MyDropDownForm(instance=MyModel.objects.filter(id=1))
        form = MyDropDownForm()
        return render_to_response('app/page.html', {'form': form})

    def post(self, request):
        # if you had set the instance in the get you want to do that again
        form = MyDropDownForm(data=request.POST)
        if form.is_valid():
            return render_to_response('app/success.html')
        return render_to_response('app/page.html', {'form': form})

Page.html

page.html中

<form method="post">
    {% csrf_token %}
    {{ form.id  }}
    {{ form.myrow }}
    {% if form.myrow.errors %}
        {% for error in form.myrow.errors %}<p>{{ error }}</p>{% endfor %}
    {% endif %}
    <button>Submit</button>
</form>

Take a look at the docs here for more info on creating model forms.

有关创建模型表单的更多信息,请查看此处的文档。

#1


6  

ModelForms are your friend here.

ModelForms是你的朋友。

models.py

class PresetList(models.Model):
    VIEWS = (
        ('1', 'X'),
        ('2', 'Y'),
    )
    query_choice = forms.ChoiceField(choices=VIEWS)

forms.py

from django.forms import ModelForm
from . import models

class PresetListForm(ModelForm):
    class Meta:
        model = models.PresetList

view.py

from . import forms

def my_view(request):

    preset_form = forms.PresetListForm()

    return render_to_response('services.html', {
        'array': json.dumps(data, cls=SpecialEncoder),
        'preset_form': preset_form,
    })

services.html

<form method=POST action="/somewhere">
    {{ preset_form.as_p }}
</form>

#2


2  

Give the generic CreateView a try.

尝试使用通用CreateView。

views.py

views.py

from django.views.generic.edit import CreateView
from .models import PresetList

class PresetListCreate(CreateView):
    model = PresetList

presetlist_form.html

presetlist_form.html

<form action="" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Create" />
</form>

#3


1  

Not sure what you want done, but if you eant to send 1 when X is displayed, the following should work:

不确定你想要做什么,但如果你想在显示X时发送1,以下应该有效:

<select style="width:300px">
  {% for choice in list1.VIEWS %}
  <option value={{choice.0}}>{{choice.1}}</option>
  {{choice}}
  {% endfor %}
</select>

#4


1  

You can create a form with a drop-down and tell it which values to populate it with like so:

您可以创建一个带有下拉列表的表单,并告诉它填充它的值如下:

Form

形成

class MyDropDownForm(forms.ModelForm):
    somerow = forms.ModelChoiceField(
        # change this queryset if you want to limit the options
        queryset= MyModel.objects.all().values('somerow'),
        widget=Select(),
        required=True,
    )        

    class Meta:
        model = MyModel
        fields = ['somerow']

View

视图

class MyView(DjangoTemplateView):

    def get(self, request):
        # you can set an instance when creating the form to set the value
        # to be that of an existing row in your model
        # MyDropDownForm(instance=MyModel.objects.filter(id=1))
        form = MyDropDownForm()
        return render_to_response('app/page.html', {'form': form})

    def post(self, request):
        # if you had set the instance in the get you want to do that again
        form = MyDropDownForm(data=request.POST)
        if form.is_valid():
            return render_to_response('app/success.html')
        return render_to_response('app/page.html', {'form': form})

Page.html

page.html中

<form method="post">
    {% csrf_token %}
    {{ form.id  }}
    {{ form.myrow }}
    {% if form.myrow.errors %}
        {% for error in form.myrow.errors %}<p>{{ error }}</p>{% endfor %}
    {% endif %}
    <button>Submit</button>
</form>

Take a look at the docs here for more info on creating model forms.

有关创建模型表单的更多信息,请查看此处的文档。