V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
python30
V2EX  ›  Python

django 的一对多栏目,怎么在 modelform 里设置默认选项。如下图

  •  
  •   python30 · 2019-12-27 19:53:17 +08:00 · 3185 次点击
    这是一个创建于 1581 天前的主题,其中的信息可能已经有所发展或是发生改变。
    上面图片是 html 代码里 下面是外凤 怎么样让里面的 ------- 改成: 请选择一个默认栏目 ?

    下面是在 forms.ModelForm 里的设置不起作用。

    category = forms.ModelChoiceField(queryset=Category.objects.all(), widget=forms.Select(), initial={'headline': '请选择一个默认栏目'})

    在 forms.ModelForm 里 init 里 设置 self.initial['category'] = ['1'] 只对显示已有的栏目。 不知怎么让 ------- 显示 请选择一个默认栏目 难道要用前端 js?

    document.getElementById("id_category").innerHTML="请选择一个栏目";

    document.getElementById("id_category").value ="请选择一个栏目";

    好像都不行。请各位朋友帮忙看看? 谢谢。

    4 条回复    2019-12-28 12:34:17 +08:00
    lenqu
        1
    lenqu  
       2019-12-27 20:01:39 +08:00
    在 option 加属性 selected = "selected" 试一下
    python30
        2
    python30  
    OP
       2019-12-27 22:29:05 +08:00
    @lenqu
    我是用的 {{form.category}} 输出的

    这样 怎么给 option 加属性 selected = "selected"?
    lenqu
        3
    lenqu  
       2019-12-28 11:50:36 +08:00
    class CommentForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields['name'].widget.attrs.update({'class': 'special'})
    self.fields['comment'].widget.attrs.update(size='40')

    或者

    >>> from django import forms
    >>> name = forms.TextInput(attrs={'size': 10, 'title': 'Your name'})
    >>> name.render('name', 'A name')
    '<input title="Your name" type="text" name="name" value="A name" size="10">'
    python30
        4
    python30  
    OP
       2019-12-28 12:34:17 +08:00
    @lenqu
    多谢。用你的第二个方法可以成功
    不过我用的
    js 前端解决了
    document.querySelector("option")
    获得页面上第一个 option 的元素
    然后用 js 写上就 OK 了

    谢谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3317 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 107ms · UTC 12:36 · PVG 20:36 · LAX 05:36 · JFK 08:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.