Django CreateView自定义小部件覆盖

时间:2019-03-06 06:28:23

标签: django modelform django-widget

我想使用自定义小部件(XDSoft DateTimePicker)覆盖我的emailCreate(CreateView)ModelForm中sendDate字段中的DateTimeField小部件。

以下是常规格式的过程:https://simpleisbetterthancomplex.com/tutorial/2019/01/03/how-to-use-date-picker-with-django.html#xdsoft-datetimepicker

我的表单生成了,但是sendDate字段仍然不显示自定义窗口小部件。感谢您的帮助,这是我的代码:

forms.py

from django import forms
from django.forms import ModelForm
from .widgets import XDSoftDateTimePickerInput
from .models import email
from django.contrib.admin import ModelAdmin

class emailForm(forms.ModelForm):
    class Meta:
        model = email
        fields = ('name', 'sendDate', 'sendClassification')
        widgets = {
        'sendDate': XDSoftDateTimePickerInput()
        }

Models.py

from django.db import models
from django.urls import reverse
import datetime

# Create your models here.
class email(models.Model):
    name = models.CharField(max_length=250)
    sendDate = models.DateTimeField(null=True, blank=True)
    CLASSIFICATION_CHOICES = (
        ('Best Buy Movers Program', 'Best Buy Movers Program'),
        ('BestBuyConnect', 'BestBuyConnect'),
    )
    sendClassification = models.CharField(max_length=2,choices=CLASSIFICATION_CHOICES, default='BestBuyConnect')

    def get_absolute_url(self):
        # reverse expects the view name
        return reverse('formappdb')

Views.py

from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.template import loader
from .models import email
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from .forms import emailForm

def index(request):
    all_emails = email.objects.all()
    template = loader.get_template('formapp/index-brett.html')
    context = { 
        'all_emails': all_emails,
    }
    return HttpResponse(template.render(context, request))

class emailCreate(CreateView):
    model = email
    form_class = emailForm

Widgets.py

from django.forms import DateTimeInput

class XDSoftDateTimePickerInput(DateTimeInput):
    template_name = 'widgets/xdsoft_datetimepicker.html'

xdsoft_datetimepicker.html

{% include "django/forms/widgets/input.html" %}

<script>
  $(function () {
    $("input[name='{{ widget.name }}']").datetimepicker({
      format: 'd/m/Y H:i',
    });
  });
</script>

0 个答案:

没有答案