Django form.is_valid给出False

时间:2019-04-09 12:38:15

标签: python django django-forms

ModelsForm以ISO格式返回日期时间,例如:

2019-04-10T06:30:00

views.py 中,我正在检查响应字符串中包含的字符“ T”,并将ISO转换为python datetime格式。之后,我将表单字段替换为新值。
如果字符串仅包含日期- 2019-04-10 ,则 event_form.is_valid()返回True,并且正在创建新的实例。但是,如果字符串包含时间,则 is_valid 返回False。

views.py

def event(request):
    all_events = Events.objects.all()
    if request.method == 'POST':
        event_form = ModelEventsForm(request.POST)
        start = (event_form['start_date'].value())
        end = (event_form['end_date'].value())
        if 'T' in start and end:#Check that time include in data string (for create events from daily and week view)
            start = datetime.strptime(start, "%Y-%m-%dT%H:%M:%S")
            end = datetime.strptime(end, "%Y-%m-%dT%H:%M:%S")
            event_form = ModelEventsForm(initial={'start_date': start, 'end_date': end})
        if event_form.is_valid():
            update = event_form.save(commit=False)
            update.owner = request.user.profile
            update.start_date = event_form.cleaned_data['start_date']
            update.end_date = event_form.cleaned_data['end_date']
            update.save()
        return redirect('events:event')
    else:
        event_form = ModelEventsForm()
    context = {
        "events": all_events,
        'event_form': event_form
    }
    return render(request, 'profile/event_management.html', context)

form.py

 <form method="POST">
              {% csrf_token %}
          <div class="form-group">
            <label for="event_name">Event name</label>
              {%  render_field  event_form.event_name class="form-control" id='event_name' %}

          </div>
             <div class="form-group">
             <label for="start-date">Event start</label>
              {%  render_field  event_form.start_date class="form-control datepicker" id='start-date' %}

          </div>
             <div class="form-group">
            <label for="end-date">Event end</label>
                 {%  render_field  event_form.end_date class="form-control datepicker" id='end-date' %}

          </div>
          <button type="submit" class="btn btn-primary">Создать событие</button>
        </form>

modelforms.py

class ModelEventsForm(forms.ModelForm):
    class Meta:
        model = Events
        exclude = ['event_type', 'owner']

models.py

class Events(models.Model):
    owner = models.ForeignKey(Profile, blank=True, null=True, on_delete=models.CASCADE)
    event_name = models.CharField(max_length=255)
    start_date = models.DateTimeField(null=True)
    end_date = models.DateTimeField(null=True)
    event_type = models.CharField(max_length=10)

开始结束值是合适的python日期时间格式

2019-04-09 19:00:00

1 个答案:

答案 0 :(得分:0)

使用此代码进行了

b