Django,日历小部件不适用于ModelForm和Form Media

时间:2016-10-16 13:14:30

标签: javascript python css django forms

我找到一个blog。它解释了如何使用表单媒体应用日历小部件。这正是我想要做的。所以我按照说明进行操作。

但是js和css文件在widget中不起作用。我试图找出这个问题。我花了很多时间搜索和阅读东西。但我无法确切地解决我的情况。嗯,这可能是一个非常简单的问题,但如果你能给我任何暗示来解决这个问题,我将不胜感激!

model.py

class Birthday(models.Model):
    birthday = models.DateField(null=True)

views.py

def register_birthday(request):
    if request.method == 'POST':
        form = BirthdayForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/success')
    else:
        form = BirthdayForm()
    return render(request, 'sale/registerbirthday.html', {'form':form})

forms.py

class DateUIWidget(forms.TextInput):
    def _media(self):
        return forms.Media(css = {
            "all": ("tiny-date-picker.css",)
        },
        js = ("tiny-date-picker.js", "date-init.js",))
    media = property(_media)


class BirthdayForm(forms.ModelForm):
    class Meta:
        model = Birthday
        fields = ('birthday',)
        widgets = {
            "birthday" : DateUIWidget(attrs={'class':'dateuiwidget', 'id':'id_birthday'}),
        }

实际上我最初写的就像下面一样。但是当我使用媒体作为动态属性时,我改变了检查它是否有效。

class DateUIWidget(forms.TextInput):
    class Media:
        css = {
            "all": ("tiny-date-picker.css",)
        }
        js = ("tiny-date-picker.js", "date-init.js",)

forms.py首先

<form action="." method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>
{{ form.medai}}

我改变了它,因为我读到我改变后应该读这个。 As we have already seen, the string representation of a Media object is the HTML required to include the relevant files in the <head> block of your HTML page.

<html>

<head>
{{ form.media }}
</head>

<body>
<form action="." method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>
</body>

</html>

在myapp / static / date-init.js下

$(".dateuiwidget").each(function(){
    return TinyDatePicker(this);
});

我在myapp / static /下复制了两个文件(tiny-date-picker.js,tiny-date-picker.css)。 我从here

获得了两个文件

它以无错误的形式显示窗口小部件。我假设某些js,css文件不适用于此小部件。

html source code
<html>

<head>
<link href="/static/tiny-date-picker.css" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/static/tiny-date-picker.js"></script>
<script type="text/javascript" src="/static/date-init.js"></script>
</head>

<body>
<form action="." method="post">
<input type='hidden' name='csrfmiddlewaretoken' value='VC8ahwDLBOsy4IlAzf1iIiukK7ZvTcGDQjL9RxywlauCOX3c8rG7DVJ1ClozHEEW' />
<p><label for="id_birthday">Birthday:</label> <input class="dateuiwidget" id="id_birthday" name="birthday" type="text" required /></p>
<input type="submit">
</form>
</body>
</html>

0 个答案:

没有答案