Django DateField TypeError预期的字符串或类似字节的对象

时间:2018-12-14 04:40:41

标签: python django

我是Django新手, 提交并尝试保存在下拉列表之一中选择的更新值时出现错误。
我认为这与传递给表单的日期有关,但我不确定如何解决。

回溯错误:

match = date_re.match(value)
     

TypeError:预期的字符串或类似字节的对象

我的模型。py

  from django.db import models

    class Person(models.Model):
        person_name = models.CharField(max_length=50, unique=True)
        person_dept = models.ForeignKey('Department',
                                         default='1',
                                         on_delete=models.CASCADE)
        number = models.CharField(max_length=10, unique=True)
        email = models.EmailField(max_length = 100, unique=True)

        class Meta():
            db_table = 'person'

        def save(self, *args, **kwargs):
            for field_name in ['person_name']:
                val = getattr(self, field_name, False)
                if (val):
                    setattr(self, field_name, val.title())
            super(Person, self).save(*args, **kwargs)

        def __str__ (self):
            return self.person_name

    class Department(models.Model):
        dept_desc = models.CharField(max_length=100, unique=True)
        class Meta():
            db_table = 'dept'

        def __str__ (self):
            return self.dept_desc

    class Roster(models.Model):
        roster_date = models.DateField()
        oss_person = models.ForeignKey('Person',
                                    on_delete=models.CASCADE,
                                    related_name='+',
                                    limit_choices_to={'person_dept': 1},)
        nw_person = models.ForeignKey('Person',
                                   on_delete=models.CASCADE,
                                   related_name='+',
                                   limit_choices_to={'person_dept': 2},)
        class Meta():
            db_table = 'roster'

        def __str__(self):
            return str(self.roster_date)

我的forms.py

 from datetime import datetime, timedelta

    from django import forms
    from django.core import validators

    from roster.models import Roster, Person, Department

    class UpdateRosterForm(forms.ModelForm):
        class Meta():
            model = Roster
            fields = '__all__'
            labels = {
                       "roster_date":"Start On Call Date",
                       "oss_person":"Servers",
                       "nw_person":"Networks",
                      }

    def __init__(self, *args, **kwargs):
        super(UpdateRosterForm, self).__init__(*args, **kwargs)
        self.today = datetime.now()
        self.min_date = (self.today - timedelta(days=self.today.weekday())
                                    + timedelta(days=0)).date()
        self.fields['roster_date'] = forms.ModelChoiceField(
                                         queryset=Roster.objects.filter(
                                         roster_date__gte=self.min_date),
                                         initial = 0,
                                         label='Start On Call Date')

        def clean(self):
            roster_date = self.cleaned_data.get("roster_date")
            oss_person = self.cleaned_data.get("oss_person")
            nw_person = self.cleaned_data.get("nw_person")

我的模板文件

{% extends "roster/base.html" %}
{% block title %}Update On Call Roster{% endblock %}
{% block extra_js %}
{% load staticfiles %}
 <script type="text/javascript" src='{% static "js/roster_selector.js" %}'></script>
{% endblock extra_js %}
{% block body_block %}
    <p>
      <div class="container">
        <form name="status_form" method="POST">
        {% include 'roster/messages.html' %}
          {% block content %}
          {% endblock %}
        </form>
      </div>
    <div class="container">
      <table class="table table-bordered table-striped table-dark table-primary">
        <colgroup span="3"></colgroup>
        <thead>
          <th scope="col">On Call Start Date</th>
          <th scope="col">Server</th>
          <th scope="col">Networks</th>
        </thead>
        <trbody>
         <form method="POST">
         <tr>
         {% for field in form %}
            <td> {{ field }} </td>
         {% endfor %}
         </tr>
         {% csrf_token %}
       </trbody>
      </table>
      <input class="btn btn-primary" type="submit" value="submit">
    </div>
{% endblock %}

我的views.py

def update(request):
    form = forms.UpdateRosterForm()
    if (request.method == 'POST'):
        form = forms.UpdateRosterForm(request.POST)
        if (form.is_valid()):
            form.save()
            form = forms.UpdateRosterForm()
            messages.success(request,"Roster Has Been Updated Successfully")
        else:
            messages.warning(request,"Something Went Wrong!")
    return render(request, 'roster/update.html', {'form': form})

def send_selected_date(request):
    if (request.method == "GET"):
        sel_date = request.GET.get('selected_date')
        oncall_ids = Roster.objects.filter(
             roster_date = sel_date).values_list('oss_person_id','nw_person_id')
        oncall_ids_json = dumps(list(oncall_ids), cls=DjangoJSONEncoder)
        return HttpResponse(oncall_ids_json)

追踪

Traceback:

    File "/Users/msl/Documents/scripts/django/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
      34.             response = get_response(request)

    File "/Users/msl/Documents/scripts/django/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
      126.                 response = self.process_exception_by_middleware(e, request)

    File "/Users/msl/Documents/scripts/django/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
      124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

    File
    "/Users/msl/Documents/scripts/django/oncall_roster/roster/views.py" in update
      115.         if (form.is_valid()):

    File "/Users/msl/Documents/scripts/django/env/lib/python3.6/site-packages/django/forms/forms.py" in is_valid
      185.         return self.is_bound and not self.errors

    File "/Users/msl/Documents/scripts/django/env/lib/python3.6/site-packages/django/forms/forms.py" in errors
      180.             self.full_clean()

    File "/Users/msl/Documents/scripts/django/env/lib/python3.6/site-packages/django/forms/forms.py" in full_clean
      383.         self._post_clean()

     File "/Users/msl/Documents/scripts/django/env/lib/python3.6/site-
       packages/django/forms/models.py" in _post_clean
          403.             self.instance.full_clean(exclude=exclude,
    validate_unique=False)

    File "/Users/msl/Documents/scripts/django/env/lib/python3.6/site-packages/django/db/models/base.py" in full_clean
      1130.             self.clean_fields(exclude=exclude)

    File "/Users/msl/Documents/scripts/django/env/lib/python3.6/site-packages/django/db/models/base.py" in clean_fields
      1172.                 setattr(self, f.attname, f.clean(raw_value, self))

    File "/Users/msl/Documents/scripts/django/env/lib/python3.6/site-packages/django/db/models/fields/__init__.py" in clean
      630.         value = self.to_python(value)

    File "/Users/msl/Documents/scripts/django/env/lib/python3.6/site-packages/django/db/models/fields/__init__.py" in to_python
      1230.             parsed = parse_date(value)

    File "/Users/msl/Documents/scripts/django/env/lib/python3.6/site-packages/django/utils/dateparse.py" in parse_date
      74.     match = date_re.match(value)

    Exception Type: TypeError at /update_roster/
    Exception Value: expected string or bytes-like object

1 个答案:

答案 0 :(得分:0)

在模型中,您具有roaster_date一个DateField,但是从Form您正在发送一个Roaster对象,这就是您面临此问题的原因。因此,像这样更新表单:

days = self.today - self.min_date
choices = list()
choices.append((self.today, str(self.today)))
new_date = self.today
for i in range(days):
   new_date = new_date - datetime.timedelta(days=1)
   choices.append((new_date, str(new_date)))


self.fields['roster_date'].widget = forms.Select(choices=choices)