python - 如何通过模板在 django 模型选择中添加选项

标签 python django django-models django-templates

我正在学习 Django,我需要允许应用程序的用户能够通过模板向 item_name 字段添加更多选项,但我不知道如何实现这一点。谢谢您的帮助。

这是我的模型

class ItStore(models.Model):
    type_choice = (
            ('Printer Catridge', 'Printer Catridge'),
            ('UPS', 'UPS'),
            ('UPS Battery', 'UPS Battery'),
            ('Mouse', 'Mouse'),
            ('Keyboard', 'Keyboard'),
        )
    item_name = models.CharField(max_length='100', blank=True, null=False, choices=type_choice)
    quantity = models.IntegerField(default='', blank=True, null=False)

这是我的观点

def itstore_create(request):
    form = ItStoreCreateForm(request.POST or None)
    submit = "Create IT Store Items"
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        message = instance.item_name + " Successfully Created"
        messages.success(request, message)
        return redirect("items:itstore_list")
    context = {
        "form": form,
        "title": "CREATE ITEM", 
    }
    return render(request, "store_form.html", context)

这是我的表格

class ItStoreCreateForm(forms.ModelForm):
    class Meta:
        model = ItStore
        fields = ['item_name', 'quantity']

最佳答案

您无法在模型上定义choices=。而是在模型之外定义默认选择列表。

my_choices = (
    "foo",
    "bar",
    "pop",
)
class MyModel(models.Model):
    my_field = models.CharField(max_length=100)

然后在您的 View 中,您需要导入该元组并将其传递给您的模板:

from my_app.models import my_choices

def my_view(request, *a, **kw):
    # view logic
    return render(request, "path/to/my/template", choices=my_choices)

然后在您的模板中,您可以有一个包含默认选项和字符串值的选择框。还有一个可选的input type=text,如果填充,它将保存到该字段。

类似于:

<select name="my_field">
<option value="" selected="selected">-----</option>
{% for choice in choices %}
    <option value="{{ choice }}">{{ choice }}</option>
{% endfor %}
</select>

将为您提供默认选择。然后添加一个同名的输入,这将作为一个可选的新选择。

<input type="text" name="my_field"/>

您可以选择编写 JavaScript 逻辑来确保仅提交选择框或文本字段。

关于python - 如何通过模板在 django 模型选择中添加选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37868084/

相关文章:

python - MongoDB Python 和 C++ 客户端 - 多个实例出错

python - 用矢量移动字符

mysql - 使用 powershell 开发脚本启动 docker

python - 使用 Python 编写的谷歌图像抓取器与网络浏览器之间的不同 html 代码结果(UI)

python - 为什么 Theano 测试会因许多 "KnownFailureTest"而失败?

python - 上传文件时无法通过 'tuple' 对象没有属性 'startswith' 错误

django session key 在身份验证时更改

python - 如何转换为批量插入

python - 如何在 Django 管理详细信息页面中添加下载文件的链接?

django - Django order_by属性