0👍
✅
You don’t need to have the driver_number field in the TimeClockIN model (it already exists in the driver field). You can create a normal django form where you retrieve the driver_number. Afterwards, try to get the driver from the db and if it exists, create a new TimeClockIN instance with the coresponding data and save it. This assumes that each driver_number is unique among Drivers.
If you later need to get the driver_number from the TimeClockIN model, you just follow the driver foreign key and get it from there.
Model:
class TimeClockIN(models.Model):
timestamp = models.DateTimeField()
driver = models.ForeignKey(Driver, blank=True)
Form:
class ClockInForm(forms.Form):
driver_number = forms.IntegerField(required=True, max_length=8)
View:
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})
1👍
You’re passing the wrong thing to the form instantiation.
form = forms.ClockInForm(request.POST)
Source:stackexchange.com