Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Store the Data in Database from dropdown in Djngo

Here is my code

I am working on student management project and I am unable to get the branch for student as it is foreignkey of Course model to Student model and I want to get the selected option into student model in branch row

models.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Course(models.Model):
    id=models.AutoField(primary_key=True)
    course = models.CharField(max_length=50)
    course_code = models.BigIntegerField(null=True)
    
    def __str__(self):
        return self.course

class Student(models.Model):
    id=models.AutoField(primary_key=True)
    user=models.OneToOneField(User,on_delete=models.CASCADE)
 
 
 
 branch=models.ForeignKey(Course,on_delete=models.CASCADE,null=True,blank=True)
    middle_name=models.CharField(max_length=50,null=True)
    roll_no=models.IntegerField()
    mobile_no=PhoneNumberField(default='')
    parents_mobile_no=PhoneNumberField(default='')
    division=models.CharField(max_length=10,null=True)
    batch=models.CharField(max_length=10,null=True)
    
    def __str__(self):
        return self.user.first_name + " " + self.user.last_name

views.py

def studentregister(request):
    if request.method == 'POST':
        first_name = request.POST['first_name']
        middle_name = request.POST['middle_name']
        last_name = request.POST['last_name']
        email = request.POST['email']
        branch= request.POST['branch']
        division = request.POST['division']       
        roll_no = request.POST['roll_no']
        mobile_no = request.POST['mobile_no']
        parents_mobile_no = request.POST['parents_mobile_no']
        pass1 = request.POST['password']
        pass2 = request.POST['confirmpassword']
        
        if pass1 == pass2 :
            if User.objects.filter(email=email).exists():
                return HttpResponse('User already exsits')
            else:
                user = User.objects.create_user(email=email, password=pass1, first_name=first_name, last_name=last_name)
                user.save();
                studentdetails = Student ( user=user, middle_name=middle_name,roll_no=roll_no,mobile_no=mobile_no,parents_mobile_no=parents_mobile_no, branch=branch,division=division)
                studentdetails.save();
                return render (request, 'ms/homepage/index.html')
        else:
            return HttpResponse('password does not match')
    else:
        return HttpResponse('failed')

def staffstudent(request):
    if request.user.is_authenticated and request.user.user_type==3:
        courses = Course.objects.all()
        return render(request, 'ms/staff/student.html',{'courses':courses})
    else:
        return render(request,'ms/login/login.html')

html file as student.py

<form action="studentregister" method="POST" style = "background-color:#011B3C;">
            {% csrf_token %}
<div class="form-group" name="branch">
            <select >
                <option selected disabled="true">Branch</option>
                {% for course in courses%}
                <option>{{course.course}}</option>
                {%endfor%}
            </select>
            </div> 
</form>

The error I am getting is
MultiValueDictKeyError at /staff/studentregister
‘branch’

Please help me with this as soon as possible

>Solution :

You haven’t named that <select> (<select name="branch">) so any choice you make in it will not be transmitted to the server, and that’s why you get a key error.

In addition, the <option>‘s value must be the course’s id:

<option value="{{ course.id }}">{{ course.course }}</option>

… so you can look it up in the view:

branch = Course.objects.get(id=request.POST['branch'])

However, please look at Django’s built-in forms functionality, especially model forms – you would be done in a fraction of the HTML and Python code you have now, plus you’d actually have correct data validation.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading