[Answered ]-How to set foreign by post method in django?

1👍

You should assign the primary key to course_id, so:

def Examadd(request):
    mycourses = Courses.objects.all()
    context = {'mycourses': mycourses}
    if request.method == 'POST':
        newexam = request.POST.get('examname')
        course = request.POST.get('courses')
        examtime = request.POST.get('time')
        new = Exam.objects.create(
            exam_name=newexam, course_id=course, exam_time=examtime
        )
        messages.success(request, "Course created successfully")
        return redirect('Courselist')
    return render(request, 'addexam.html', context)

I would however advise to use a ModelForm, this makes saving the data easier and less error-prone, but will also do proper validation: for example checking that time is indeed passed, and that it is formatted as a correct datetime string.


Note: normally a Django model is given a singular name, so Course instead of Courses.


Note: Normally model fields have no prefix with the name of the model. This makes
queries longer to read, and often want uses inheritance of (abstract) models to
inherit fields, so using a prefix would make it less reusable. Therefore it
might be better to rename your field course_name to name.

0👍

At first, create() method doesn’t require save() method to be called, and you can directly assign course id in the Exam model, so the view should be:

def Examadd(request):
    mycourses = Courses.objects.all()
    context = {'mycourses': mycourses}
    if request.method == 'POST':
        newexam = request.POST.get('examname')
        course = request.POST.get('courses')
        examtime = request.POST.get('time')
        new = Exam.objects.create(exam_name=newexam,course__id=course,exam_time=examtime)
        messages.success(request, "Course created successfully")
        return redirect('Courselist')
    return render(request,'addexam.html',context)

Leave a comment