推荐学习书目
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 · Dec 27, 2019 · 3751 views
    This topic created in 2338 days ago, the information mentioned may be changed or developed.
    上面图片是 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 replies    2019-12-28 12:34:17 +08:00
    lenqu
        1
    lenqu  
       Dec 27, 2019
    在 option 加属性 selected = "selected" 试一下
    python30
        2
    python30  
    OP
       Dec 27, 2019
    @lenqu
    我是用的 {{form.category}} 输出的

    这样 怎么给 option 加属性 selected = "selected"?
    lenqu
        3
    lenqu  
       Dec 28, 2019
    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
       Dec 28, 2019
    @lenqu
    多谢。用你的第二个方法可以成功
    不过我用的
    js 前端解决了
    document.querySelector("option")
    获得页面上第一个 option 的元素
    然后用 js 写上就 OK 了

    谢谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2858 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 04:53 · PVG 12:53 · LAX 21:53 · JFK 00:53
    ♥ Do have faith in what you're doing.