Django添加/编辑表单在初始化时未返回初始值/默认值

时间:2019-04-11 04:26:45

标签: python django django-forms django-views

我有用于添加和编辑模型表单的视图。编辑表单工作正常,但是在加载添加表单时,我通过Python代码设置的初始值未显示。

Views.py(1):

def tracker_edit(request, track_id=None, template_name='posts/tracker_edit.html'):
    if track_id is not None:
        track = get_object_or_404(Post, pk=track_id)
    else:
        track = Post()
    tracker = CreateArticle(request.POST or None, instance=track)
    if request.POST and tracker.is_valid():
        tracker.save()
        redirect_url = reverse('posts:tracker_list')
        return redirect(redirect_url)

    return render(request, template_name, {
        'tracker': tracker
    })

Forms.py:

    Day_Of_Week=(('Weekday','Weekday'),('Weekend','Weekend'))
    weekno = datetime.datetime.today().weekday()

    if weekno<5:
        x = ("Weekday")
    else:
        x = ("Weekend")

    Day_Of_Week = forms.ChoiceField(choices=Day_Of_Week, widget=forms.RadioSelect, initial=x)

例如,从forms.py中,您可以看到我希望单选按钮被自动选择为工作日或周末。但是没有选择。我很困惑,我的get / put做错了吗?上面的任何修复将不胜感激..

1 个答案:

答案 0 :(得分:0)

我通过添加python代码在models.py而不是forms.py中产生初始值来解决这个问题。

models.py

weekno = datetime.datetime.today().weekday()
    if weekno < 5:
        x = ("Weekday")
    else:
        x = ("Weekend")
    Day_Of_Week = models.TextField(null=False, db_column='dayofweek', default=x)