ModelForm返回字段是必需的,而不是保存到sqliteDB

时间:2016-01-14 19:44:16

标签: python django django-models django-forms django-views

每当我尝试保存表单时,我的模板都会返回"此字段是必需的"。问题是我填写了这个领域,这是我需要填写的唯一领域..我有点沮丧,我觉得这个论坛会让我分开问这个问题,但有人可以看一看在它,告诉我我做错了什么。提前谢谢!

models.py

class TimeClockIN(models.Model):
    timestamp = models.DateTimeField()
    driver_number = models.IntegerField(max_length=8)   
    driver = models.ForeignKey(Driver, blank=True)

forms.py

class ClockInForm(forms.ModelForm):
    class Meta:
        model = models.TimeClockIN
        fields = [
           'driver_number',

       ]

views.py:

def clock_in_view(request):
    form = forms.ClockInForm()
    pull_all = Driver.objects.all()

    if request.method == 'POST':
        form = forms.ClockInForm(request.GET)
        if form.is_valid(): 
            for driver in pull_all:
                if request in driver.driver_number:
                    time_in_instance = form.save(commit=False)
                    time_in_instance.timestamp = timezone.now()
                    time_in_instance.save()
                    messages.add_message(request, messages.SUCCESS,
                                        "Clocked IN")
                    return HttpResponseRedirect(reverse('clockin'))
            else:
                form = forms.ClockInForm()




    return render(request, 'clockinform.html', {'form': form})  

2 个答案:

答案 0 :(得分:1)

您将错误的内容传递给表单实例化。

form = forms.ClockInForm(request.POST)

答案 1 :(得分:0)

您不需要在TimeClockIN模型中具有driver_number字段(它已存在于驱动程序字段中)。您可以创建一个正常的django表单来检索driver_number。然后,尝试从db获取驱动程序,如果存在,则使用相应的数据创建一个新的TimeClockIN实例并保存。这假设每个driver_number在Drivers中是唯一的。

如果您以后需要从TimeClockIN模型获取driver_number,您只需按照驱动程序外键并从那里获取它。

型号:

class TimeClockIN(models.Model):
    timestamp = models.DateTimeField()
    driver = models.ForeignKey(Driver, blank=True)

形式:

class ClockInForm(forms.Form):
    driver_number = forms.IntegerField(required=True, max_length=8)

查看:

def clock_in_view(request):
    form = forms.ClockInForm()

    if request.method == 'POST':
        form = forms.ClockInForm(request.POST)
        if form.is_valid(): 
            try: 
                driver = Driver.objects.get(driver_number=form.cleaned_data['driver_number'])
                time_in_instance = TimeClockIN()
                time_in_instance.timestamp = timezone.now()
                time_in_instance.driver = driver
                time_in_instance.save()
                messages.add_message(request, messages.SUCCESS,
                                    "Clocked IN")
                return HttpResponseRedirect(reverse('clockin'))
            except Driver.DoesNotExist:
                form = forms.ClockInForm()
    return render(request, 'clockinform.html', {'form': form})