6

查看此链接并找到了一些帮助,但我想知道如何选择将 JQueryUI Datepicker 小部件用于我的 models.py 中的 DateField

模型.py


from django.db import models

class EModel(models.Model):

    date = models.DateField(blank=False)

表格.py


from django import forms
from models import EModel

class EForm(forms.ModelForm):
    class Meta:
        model = EModel

form.html - Django 如何呈现我的表单。不在管理页面

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Form</title>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <link rel="stylesheet" href="/resources/demos/style.css" />
</head>
<body>
    <form action="" method="post">{% csrf_token %}
        {{ form.date }} <!-- ***** -->
        <!-- The rest of my form -->
    </form>
</body>

我希望有一种方法可以使我的“日期”模型字段呈现为 JQueryUI Datepicker 小部件,但我四处搜索并发现无法链接两者(在我的情况下)。

解决方案








在我的 forms.py

from django import forms
from models import EModel

class EForm(forms.ModelForm):
    class Meta:
        model = EModel
        widgets = {
            'date' : forms.DateInput(attrs={'type':'date'})
        }
4

3 回答 3

9

在您的模型表单中编辑您的日期小部件属性,为它们提供类“.datepicker”,因为这就是 JQuery 日期选择器要查找的内容。所以你的 ModelForm 变成:

class EForm(forms.ModelForm):
    class Meta:
        model = EModel
        widgets = {'date': DateInput(attrs={'class': 'datepicker'})}

文档在这里

于 2013-08-07T17:20:40.683 回答
2

我使用以下代码,它对我来说很好。我已经提到了这个项目的所有文件,

模型.py

    from django.db import models
    class EModel(models.Model):
        date = models.DateField(blank=False)

表格.py

    from django import forms
    from testApp.models import EModel
    class EForm(forms.ModelForm):
        class Meta:
            model = EModel
            widgets = {'date': forms.DateInput(attrs={'class': 'datepicker'})}

表单.html

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Form</title>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
        <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
        <link rel="stylesheet" href="/resources/demos/style.css" />
        <script>
        $(function() {
            $( "#id_date" ).datepicker();
        });
        </script>
    </head>
    <body>
        <form action="/datepickerview/" method="post">{% csrf_token %}
            <!--{{ form.date }} -->
            <p>Date: <input name='date' type="text" id="id_date"></p>
            <!-- The rest of my form -->
            <input type="submit" value="login" />
        </form>
    </body>

视图.py

    from django.shortcuts import render
    from django.http import HttpResponse
    from django.template import Context
    from django.shortcuts import render_to_response
    from django.http import HttpResponseRedirect
    from django.core.context_processors import csrf
    from django.template import RequestContext
    from forms import EForm
    def datepickerview(request):
        # Get the context from the request.
        context = RequestContext(request)
        # A HTTP POST?
        if request.method == 'POST':
            form = EForm(request.POST)
            # Have we been provided with a valid form?
            if form.is_valid():
                form.save(commit=True)
                return HttpResponse("Successfully added the date to database");
            else:
                # The supplied form contained errors - just print them to the terminal.
                print form.errors
        else:
            # If the request was not a POST, display the form to enter details.
            form = EForm()
        return render_to_response('form.html', {'form': form}, context)

网址.py

    from django.conf.urls import patterns, include, url
    from django.contrib import admin
    admin.autodiscover()
    urlpatterns = patterns('',
    url(r'^datepickerview/$', 'testApp.views.datepickerview'),
    )

管理员.py

    from django.contrib import admin
    from testApp.models import EModel
    admin.site.register(EModel)
于 2014-06-30T13:50:51.680 回答
1

最好的办法是在您的应用程序的 widgets.py 文件中创建一个新的小部件:

这是我的颜色选择器示例:

-- 小部件.py --

from django import forms
from django.conf import settings
from django.utils.safestring import mark_safe

class ColorPickerWidget(forms.TextInput):
    class Media:
        css = {
            'all': (
                settings.STATIC_URL + 'colorpicker/css/colorpicker.css',
            )
        }
        js = (
            settings.STATIC_URL + 'js/jquery-1.8.3.min.js',
            settings.STATIC_URL + 'colorpicker/js/colorpicker.js',
        )

    def __init__(self, language=None, attrs=None):
        self.language = language or settings.LANGUAGE_CODE[:2]
        super(ColorPickerWidget, self).__init__(attrs=attrs)

    def render(self, name, value, attrs=None):
        rendered = super(ColorPickerWidget, self).render(name, value, attrs)
        return rendered + mark_safe(u'''
            <script type="text/javascript">
                jQuery('#id_%s').css("background-color", "#"+jQuery('#id_%s').val());
                jQuery('#id_%s').ColorPicker({
                    onSubmit: function(hsb, hex, rgb, el) {
                        jQuery(el).val(hex);
                        jQuery(el).css("background-color", "#"+hex);
                        jQuery(el).ColorPickerHide();
                    },
                    onBeforeShow: function () {
                        code = this.value
                        if (code.length==3) code = code.charAt(0)+code.charAt(0)+code.charAt(1)+code.charAt(1)+code.charAt(2)+code.charAt(2);
                        jQuery(this).ColorPickerSetColor(code);
                    }
                }).bind('keyup', function(){
                    el = jQuery(this);
                    code = el.val();
                    hex = '#'+code;
                    var isOk  = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
                    if (isOk) {
                        el.css("background-color", hex);
                        if (code.length==3) code = code.charAt(0)+code.charAt(0)+code.charAt(1)+code.charAt(1)+code.charAt(2)+code.charAt(2);
                        el.ColorPickerSetColor(code);
                    }
                    else if (code=="") el.css("background-color", "");
                });
            </script>
            ''' % (name, name, name))

--- 意见.py ---

from django import forms ColorPickerWidget
from myapp.widgets import
class EditBackgroundForm(forms.Form):
    background = forms.CharField(max_length=10, widget= ColorPickerWidget(), required = False, label="Background color")

此外,您还可以使用小部件创建自定义表单字段,并覆盖其clean()方法。

于 2013-08-07T14:56:02.570 回答