【问题标题】:Django - Select field not showing OptionsDjango - 选择字段不显示选项
【发布时间】:2018-12-30 20:05:11
【问题描述】:

模型.py

from django.db import models
from django import forms
class CharApp(forms.Form):
    VAMPIRE = 'VP'
    DRAUGR = 'DR'
    BAELNORN = 'BN'
    LICH = 'LH'
    SHADOW = 'SW'
    RACE_CHOICES = (
        ('VP', 'Vampire'),
        ('DR', 'Draugr'),
        ('BN', 'Baelnorn'),
        ('LH', 'Lich'),
        ('SW', 'Shadow'),
    )
    app_id = models.AutoField(primary_key=True)
    char_name = models.CharField(max_length=80, verbose_name='Character Name')
    race = forms.Form(forms.ChoiceField( choices = RACE_CHOICES))
    date_applied = models.DateTimeField(verbose_name='Date Applied')
    background = models.TextField(verbose_name='Background')
    account_id = models.IntegerField(default=1, verbose_name='Account ID')
    submitted = models.BooleanField(default=False)

创建.html

    <p><label for="race">Race:</label>
        <select name="{{ form.race.choices }}">
            {% for choices in form.race.choices %}
                {{ form.race.choices }}
            {% endfor %}
        </select>

由于某种原因,html 的选择部分根本不循环,并且根本不显示任何值或文本。

【问题讨论】:

  • 您自己指定选择有什么原因吗?
  • 我不确定我为什么要自己指定选择。它使表单只能从这些选项中读取和选择吗? - 我不确定我是否理解正确。
  • 你在这里混淆了很多东西。表单使用来自django.forms.fields 模块的字段,而不是来自django.db.models 的模型字段。其次,您不需要将字段包装到 Form 实例中。您是从哪里获取这些信息的?
  • 我在谷歌上搜索了同样的错误并看到了类似的结果。并且正在试用它们。
  • 此外,对于本文的最初部分,我正在关注如何通过github.com/evennia/evennia/wiki/Web-Character-Generation 此页面制作 Web 文档。但它不包含有关选择字段的信息,并且文本都在一行中。所以我不得不重新格式化 HTML 页面。我试图让它看起来更好,并首先完成页面。

标签: python html django forms select


【解决方案1】:

为什么你不使用内置的 django Select?

from django import forms
>>> CHOICES = (('1', 'First',), ('2', 'Second',))
>>> choice_field = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)
>>> choice_field.choices
[('1', 'First'), ('2', 'Second')]
>>> choice_field.widget.choices
[('1', 'First'), ('2', 'Second')]
>>> choice_field.widget.choices = ()
>>> choice_field.choices = (('1', 'First and only',),)
>>> choice_field.widget.choices
[('1', 'First and only')]

https://docs.djangoproject.com/en/2.0/ref/forms/widgets/#widgets-inheriting-from-the-select-widget

编辑:当我查看您的代码时,您做了一些非常奇怪的事情......您可以在您的模型中定义您的表单并在您的表单中设置模型字段?我猜你放错了概念

models.py

from django.db import models

# THIS IS YOUR MODEL, WILL BE PERSISTED IN YOUR DATABASE
class Race(models.Model):
    ... # Here you will place fields related to the race, as name, date and etc...


class CharApp(models.Model):
    VAMPIRE = 'VP'
    DRAUGR = 'DR'
    BAELNORN = 'BN'
    LICH = 'LH'
    SHADOW = 'SW'
    RACE_CHOICES = (
        ('VP', 'Vampire'),
        ('DR', 'Draugr'),
        ('BN', 'Baelnorn'),
        ('LH', 'Lich'),
        ('SW', 'Shadow'),
    )

    app_id = models.AutoField(primary_key=True)
    char_name = models.CharField(max_length=80, verbose_name='Character Name')
    race = models.ForenignKey(Race, related_name="charapp_race")
    date_applied = models.DateTimeField(verbose_name='Date Applied')
    background = models.TextField(verbose_name='Background')
    account_id = models.IntegerField(default=1, verbose_name='Account ID')
    submitted = models.BooleanField(default=False)

forms.py #在你的应用文件夹中创建这个文件

from django.forms import ModelForm
from myapp.models import Article

from .models import CharApp, RACE_CHOICES

# this is your form
class CharAppForm(ModelForm):
    # Here you can change the widget or add new fields that is not related your model form
    race = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES) #if you want to change the default form widget to this field

    class Meta:
        model = CharApp
        fields = ['__all__'] # This will get all fields from your form, or just place each field you want to display

请记住在 view.py 中创建表单实例

from .models import CharApp
from .forms import CharAppForm

# The function that will render your html or give you responses from your backend to your frontend

def your_view(request): 
    form = ConfigAppForm() # This will render your form with no value (so when pages render)
    if request.method == "POST:
        form = ConfigAppForm(request.POST) # This will bring the data that user have filled at your html and sended to your backend
        if form.is_valid(): # Check if the form is valid and able to save
            form.save() # will save the instance of your ConfigApp at your database

在你的html中你可以调用

<!-- This will render your entire form -->
{{ form.as_p}}
<!-- Obs: If you need to add css class or something like it you can override the widget at your form.py and add this classes thought attr of your field -->

以下一些指南来理解 MVC(或 django 的 MTV)的概念

MVC:https://softwareengineering.stackexchange.com/questions/127624/what-is-mvc-really

MTV Django:https://docs.djangoproject.com/en/2.0/faq/general/

Django 浏览量:https://docs.djangoproject.com/en/2.0/topics/http/views/

Django 模型:https://docs.djangoproject.com/en/2.0/topics/db/models/

Django 模型表单:https://docs.djangoproject.com/en/2.0/topics/forms/modelforms/

编辑

如果你想让你的代码在不做我之前说的任何事情的情况下工作,那就去做吧

VAMPIRE = 'VP'
DRAUGR = 'DR'
BAELNORN = 'BN'
LICH = 'LH'
SHADOW = 'SW'
RACE_CHOICES = (
    ('VP', 'Vampire'),
    ('DR', 'Draugr'),
    ('BN', 'Baelnorn'),
    ('LH', 'Lich'),
    ('SW', 'Shadow'),

class CharApp(forms.Form):
    ...
    race = forms.Form(forms.ChoiceField( choices = RACE_CHOICES))

【讨论】:

  • 我尽量保持代码紧凑。这似乎是我所需要的过于复杂了。
  • 如果你需要紧凑的代码,你应该使用flask而不是django
  • 我的意思是我试图按照本教程github.com/evennia/evennia/wiki/Web-Character-Generation - 获得一个网页字符生成页面。但它没有解释如何进行选择/列表。
  • 当然——我想把它设计成 HTML(因此我改成另一种格式),这样我就可以让它看起来不错。
  • 然而,这段代码遵循 Django 指南,而你的则没有
【解决方案2】:

您必须将表单中的种族字段清除为 CharField 而不是表单。看这个

race = forms.ChoiceField(choices = RACE_CHOICES, widget=forms.Select())

然后在您的模板打印选项中像这样

{% for key, value in form.race.choices %}
    <option value="{{ key }}">{{ value }}</option>
{% endfor %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-19
    • 2013-05-15
    • 2016-05-29
    • 1970-01-01
    • 2015-12-10
    • 2012-02-20
    • 1970-01-01
    • 2012-04-17
    相关资源
    最近更新 更多