Home > database >  How to Store the Data in Database from dropdown in Djngo
How to Store the Data in Database from dropdown in Djngo

Time:07-07

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

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  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

CodePudding user response:

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.

CodePudding user response:

this is not the conventional way to deal with Forms in Django although it can be done. Convention would be:

creating a form in forms.py like so:

class MyForm(forms.Form):

dropdown_one = forms.ChoiceField(
    label="Country",
    widget=forms.Select(attrs={"class": "selecter form-control"}),
    choices=[],
)
dropdown_two = forms.ChoiceField(
    label="Category",
    widget=forms.Select(attrs={"class": "selecter form-control"}),
    choices=[(None, '...')],
    required=True

)

then use this form in views.py like so:

my_form = MyForm(initial={})
return render(request,{'my_form':my_form})

then finally in html file :

        {{my_form.media}}
        {% for item in my_form %}
        <div  id="dropdown-content">
          {{item.label_tag}}
          {{item}}
        </div>
        {% endfor %}  
      </div>

Hope this Helps. For more refer to this : https://docs.djangoproject.com/en/4.0/topics/forms/

  • Related