2

I am doing an attendance system and the student is able to mark their attendance by looking for their name in the dropdown list value. The student will then press submit and the information will be stored in MarkAtt database. Currently it did not display the students name accordingly to class, and when i click submit it display the following errors: "valueerror" showed up. ValueError Exception Value: Cannot assign ", , ......"MarkAtt.studName" must be a "Namelist" instance. I need the selected name of the students to be stored in the database per one click....

 class MarkAtt(models.Model):
studName = models.ForeignKey(Namelist,on_delete=models.SET_NULL,blank=True, null=True, default=None)
classGrp = models.ForeignKey('GroupInfo', on_delete=models.SET_NULL, null=True)
currentDate = models.DateField(default=now())
week = models.IntegerField(default=0)
attendance = models.IntegerField(default=1) #1 is present

The Template displays the class information, today's date and the student's name in a drop drown list box.

   <form method="post" enctype="multipart/form-data">
{% csrf_token %}
Lab Group: {{group.classGrp}} //this is from another view
Day: {{group.day}} 
Time: {{group.time}} 
 Today's date: {{today.date}}
    {{form.as_p}} 

The view:

  def mark_stud(request,id):
group = GroupInfo.objects.get(id=id)
studName = Namelist.objects.filter(classGrp=id)
information = {}
information['group'] = group
information['studName'] =studName
if request.method == 'POST':        
    form = studentAttendanceForm(request.POST)
    if form.is_valid():
        att = form.save(commit=False)
        att.studName = information['studName']
        att.currentDate = datetime.datetime.now.date()
        form.save()
        return redirect('namelist.html')
else: 
    form = studentAttendanceForm()



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

Forms.py

class studentAttendanceForm(forms.ModelForm): class Meta: model = MarkAtt fields = ['studName'] label = { 'name': 'Student Name' }

def __init__(self,*args, **kwargs):
    super(studentAttendanceForm, self).__init__(*args,**kwargs)
    self.fields['studName'].label = "Select your name:" 

However, the form did not display in the template page and i am unable to save the value in the database. Really appreciate your help. Thank you so much.

2
  • Share your forms.py file Commented Sep 8, 2019 at 4:40
  • Sorry, edited my question above. Commented Sep 8, 2019 at 4:44

2 Answers 2

2

you have to separate GET and POST request in your view, for example:

if request.method == POST:
    form = studentAttendanceForm(request.POST)
    if form.is_valid():
        att = form.save(commit=False)
        att.studName = information['studName']
        att.currentDate = datetime.datetime.now.date()
        form.save()
        return redirect('namelist.html')
else: # for GET request
    form = studentAttendanceForm()

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

for your form, it would be better to use fields instead of exclude:

class studentAttendanceForm(forms.ModelForm):

    class Meta:
        model = MarkAtt 
        fields = ('studName')

    def __init__(self, *args, **kwargs):
        super(studentAttendanceForm, self).__init__(*args, **kwargs)
        self.fields['studName'].label = "Select your name:"

then in your template,
if you use form.as_p, you don't have to call form.att.label_tag, and don't have to place it inside <p> tag
see docs: form.as_p

<form method="post" enctype="multipart/form-data">
{% csrf_token %}
...
{{form.as_p}}
...

ok another problem is, what is group and today in your template?

Lab Group: {{group.classGrp}} 
Day: {{group.day}} 
Time: {{group.time}} 
Today's date: {{today.date}}

you didn't include group and today in your view, so it should be print nothing.
because in your render function, you only send information and form,
there's no group and today
return render(request, 'namelist.html', {'information' :information, 'form':form})
to increase readability code, it would be better to write like this:

context = {
    'information': information,
    'form': form,
    'group': ......, # fill this
    'today': ...... # fill this too
}
return render(request, 'namelist.html', context)

EDITED

to specify the dropdown list based on the group id, you can pass the group object and use .queryset in __init__ form

group = GroupInfo.objects.get(id=id)
if request.method == 'POST':
    form = studentAttendanceForm(request.POST, class_group=group)
    ...
else:
    form = studentAttendanceForm(request.POST, class_group=group)
def __init__(self,*args, **kwargs):
    class_group = kwargs.pop('class_group')
    super(studentAttendanceForm, self).__init__(*args,**kwargs)
    self.fields['studName'].label = "Select your name:" 
    self.fields['studName'].queryset = Namelist.objects.filter(classGrp=class_group)
Sign up to request clarification or add additional context in comments.

13 Comments

tried to change. but the form still does not display in my template page...
ok so there's several problems in your code, I've edited my answer
tried again but to no avail.. not sure why it is not displaying the dropdown list. Isit there anything i need to specify to let them know i want it to be in drop down list?
have you tried {{ form.studName }} instead of {{ form.as_p }} ?
It is successfully displayed because i did not call the view. When i click submit, an errorr, "valueerror" showed up. ValueError Exception Value: Cannot assign "<QuerySet [<Namelist: ABHISHEK SINGH>, <Namelist: AGGARWAL ANOUSHKA>, <Namelist: ARVIND KANNAYA SOMU>, <Namelist: : and etc. How do i submit the selected name to database
|
-1

I think your form won't show up because it is only defined inside the "try and except" part. Try having your code like this:

def mark_stud(request, class_id,id):
    form = studentAttendanceForm(request.POST)
    if (not class_id or not id):
        return HttpResponseForbidden()

    else:
        try:
            classGrp = None
            information = {}
            information['studName'] = Namelist.objects.get(name=id)


            if form.is_valid():
                att = form.save(commit=False)
                att.studName = information['studName']
                att.currentDate = datetime.datetime.now.date()
                form.save()
                return redirect('namelist.html')

        except ObjectsDoesNotExist:
            print("no entries")
            return redirect('namelist.html')        

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.