Home > OS >  Django: Update one data from Database
Django: Update one data from Database

Time:09-29

I have two html files for attendance_in and out, just a simple forms. If I want to punch in, the data was created (begin_time). I'm having a hard time updating the end_time. This is my code.

models.py

class Attendance(models.Model):
    begin_time = models.TimeField(verbose_name="in")
    end_time = models.TimeField(verbose_name="out")

views.py

def attendance_in(request):
    if request.method == 'GET':
        return render(request, 'attendance_in.html')
    if request.method =='POST':
        begin_time = request.POST.get('begin_time')
        Attendance.objects.create(begin_time=begin_time,)
        return redirect('/user/attendance/out')

def attendance_out(request):
    if request.method == 'GET':
        return render(request, 'attendance_out.html')
    if request.method =='POST':
      .......

urls.py

urlpatterns = [
    path('attendance/in/', views.attendance_in),
    path('attendance/out/', views.attendance_out),
]

The attendance_in was working. But I am not sure how to update the end_time.

CodePudding user response:

simply you can do like this:

   record = Record.objects.get(id=1)
   record.name = "new record name"
   record.save(update_fields=['name'])

This is the way you can update single field.

Update field must be inside save() method

CodePudding user response:

You need the id of that attendance object which is created with begin_time so that you can update the end_time of that object.

So the url for attendance out would be something like this.

path('attendance/<int:pk>/out/', views.attendance_out)

Now in the view

def attendance_out(request, pk):
    from django.utils import timezone
    from django.shortcuts import get_object_or_404, redirect 

    attendance = get_object_or_404(Attendance, pk=pk)
    if request.method =='POST':
      attendance.end_time = timezone.now()
      attendance.save()
      return redirect("/")
    return render(request, 'attendance_out.html')
  • Related