djangodjango-class-based-viewsdetailview

Django - How To Update Value From Views ? and How to Parse Id to get_success_url for DetailView?


How To Update Value From Views ? And Parse Id to DetailView ?

  1. Problem Update Value I Try to write query.attendance and query.status, to get data from database. but the error said "'QuerySet' object has no attribute 'attendance' / 'status'"

  2. Problem Parse Id I dont now how to parse this id to get_success_url

1. home/views.py

class HomeView(FormView):
     template_name = 'home/index.html'
     form_class = TicketForm

def form_valid(self, form):
    getId = form.cleaned_data['nomor_ticket']
    query = Graduates.objects.filter(ticket_id=getId)
    if query:
        **#FIRST ERROR (attendance and status has no attribute)**
        print(query.attendance == timezone.now())
        print(query.status == True)
        **#FIRST END ERROR**
        print('ticket available')
    else:
        print('no ticket not found ')
    print(query)
    return super().form_valid(form)
    

def get_success_url(self):
    return reverse('attendance:index' + how to get id ?)

2. attendance/models.py

class StudyProgram(models.Model):
    study_program_id = models.IntegerField()
    name = models.CharField(max_length=100)

def __str__(self):
    return self.name


class Graduates(models.Model):
   ticket_id = models.CharField(primary_key=True, max_length=16, unique=True, 
   default=custom_id)
   graduate_number = models.IntegerField()
   student_id = models.IntegerField()
   full_name = models.CharField(max_length=100)
   study_program = models.ForeignKey(StudyProgram, on_delete=models.CASCADE)
   attendance = models.DateTimeField(blank=True, null=True, editable=False) 
   status = models.BooleanField(default=False)

3. attendance/views.py

class Attendance(DetailView):
    model = Graduates
    template_name = "attendance/index.html"

 

4. attendance/urls.py

 from django.urls import path
 from . import views

 app_name = 'attendance'
 urlpatterns = [
    path('<pk>/', views.Attendance.as_view(), name='index'),
 ]

5. home/form.py

from django import forms
from attendance.models import Graduates

class TicketForm(forms.Form):
    nomor_ticket = forms.CharField(label="No Tiket ", required=True)

6. home/templates/home/index.html

#apart of index.html
....
<!-- Modal body -->
<div class="p-6 space-y-6">
  <form method="POST">
    {% csrf_token %}
    {{form.as_p}}
</div>
<!-- Modal footer -->
<div
  class="flex items-center p-6 space-x-2 rounded-b border-t border-gray-200 dark:border-gray-600"
>
  <button
    data-modal-toggle="defaultModal"
    type="submit"
    class="text-white bg-[#7f1d1d] hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-bold rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"
  >
    Cek Tiketmu
  </button>
</form>
....

Solution

  • 1 Your query object is of type QuerySet, not Graduate. You have to do something like:

    try:
        graduate = Graduate.objects.get(ticket_id=getId)
    except Graduate.DoesNotExist:
        print('no ticket not found ')
    

    2 Just forget get_success_url. Do the redirect in form_valid method. The last line in form_valid:

    return super().form_valid(form)
    

    is nothing more of doing a redirect.

    So your home/views.py would look like:

    class HomeView(FormView):
        template_name = 'home/index.html'
        form_class = TicketForm
    
        def form_valid(self, form):
            getId = form.cleaned_data['nomor_ticket']
            try:
                graduate = Graduate.objects.get(ticket_id=getId)
                print(graduate.attendance == timezone.now())
                print(graduate.status == True)
                print('ticket available')
            except Graduate.DoesNotExist:
                print('no ticket not found ')
            print(graduate)
            return redirect('attendance:index', graduate.ticket_id)