IntegrityError at /resultcreate/ NOT NULL constraint failed: studentportal_studentresult.student_id

Hi all, please I’m getting the this error when I render ResultModelForm in the template.

Here is models.py

class Student(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
profile_pic = models.ImageField(upload_to=student_image, verbose_name=“ProfilePicture”, blank=True)
level = models.CharField(max_length=50)
guardian_email = models.EmailField()
guardian_phone = models.IntegerField()

def __str__(self):
    return self.first_name

def get_absolute_url(self):
    #return f"/polls/{ self.id }/"  static
    
    return reverse("studentportal:student_detail", kwargs={"pk": self.id}) # dynamic
#def __str__(self):
    #return "%s - %s" % (self.first_name, self.last_name, self.profile_pic, self.level, self.guardian_email, self.guardian_phone)

class StudentResult(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name=‘myresult’)

 english = 'english'
 mathematic = 'mathematic'
 physic = 'physic'
 chemistry = 'chemistry'
 computer = 'computer'
 agric = 'agric'
 subject = [
    (english, 'english'),
    (mathematic, 'mathematic'),
    (physic, 'physic'),
    (chemistry, 'chemistry'),
    (computer, 'computer'),
    (agric, 'agric'),
    
 ]
 subject = models.CharField(max_length=50, choices=subject)

 
 exam = models.IntegerField()
 test = models.IntegerField()
 total = models.IntegerField()
 
 def __str__(self):
     return self.subject

Forms.py
from django import forms
from .models import Student, StudentResult

class StudentModelForm(forms.ModelForm):
class Meta:
model = Student
fields = (‘first_name’,‘last_name’,‘profile_pic’,‘level’,‘guardian_email’,‘guardian_phone’)

class ResultModelForm(forms.ModelForm):
class Meta:
model = StudentResult
fields = (‘subject’,‘test’,‘exam’,‘total’)

Views.py

class ResultCreateView(CreateView):
template_name = ‘studentportal/result_create.html’
form_class = ResultModelForm
queryset = StudentResult.objects.all() # /_list.html
success_url = ‘/student_result’ #this has override the getAbsoluteUrl in d models

def form_valid(self, form):
    print(form.cleaned_data)
    return super().form_valid(form)

Here is My template

{% csrf_token %}
{{ form|crispy }}

        <button class="regBtn">Submit</button>
    <form/>

… Thank you all

I don’t see anywhere in your ResultModelForm where you assign a value to the Student model to satisfy the ForeignKey requirement.

1 Like

Also, when posting code, please enclose it between lines of three backtick - ` characters. That means you’ll have a line of ```, then your code, then another line of ```. This allows the forum software to keep your code properly formatted.

2 Likes

Thanks for your response. But I still dont get it. Please can you help with a written sample. I’m still very new to Django . Thanks

The ResultCreateView uses the ResultModelForm. The ResultModelForm is built from the StudentResult model. The StudentResult model has a field named student that refers to a Student. However, student is not a field in the ResultModelForm.

Have you worked your way through the Official Django Tutorial?

The Polls app you create in it is a direct parallel to what you’re trying to do here. It’s a very good example of working with related tables.

1 Like

Thanks a lot Ken. I got your explanation right. I didn’t consider that before. I will go through the Django documentation now.

Hi Ken. I just tried it using the admin page now, and it works fine. I’m able to add the subjects. So what could be wrong now

What is the problem you’re having at this point? (Have you made the change identified in my earlier response?)

If you’re still getting an error, please include the complete traceback message. Also, if it’s still a problem with a form or view, post the current complete view and form.

When posting your code, please enclose it between lines of three backtick - ` characters. That means you’ll have a line of ```, then your code, then another line of ```. This allows the forum software to keep your code properly formatted.

1 Like

Yes Ken. I had made the changes and my new forms.py looks like this

from django import forms
from .models import Student, StudentResult

class StudentModelForm(forms.ModelForm):
    class Meta:
        model = Student
        fields = ('first_name','last_name','profile_pic','level','guardian_email','guardian_phone')
        
class ResultModelForm(forms.ModelForm):
    class Meta:
        model = StudentResult
        fields = ('student','subject','test','exam','total')
        
        def __init__(self, user, *args, **kwargs):
            super(ResultModelForm, self).__init__(*args, **kwargs)
            self.fields['student'].queryset = Student.objects.filter(user=user)

So after that I’m getting this error when I submitted the form in y template :

Page not found (404)

Request Method: GET
Request URL: http://127.0.0.1:8000/student_result

Using the URLconf defined in portal.urls , Django tried these URL patterns, in this order:

  1. admin/
  2. [name=‘index’]
  3. registration/ [name=‘registration’]
  4. user_login/ [name=‘user_login’]
  5. logout/ [name=‘user_logout’]
  6. studentportal/
  7. ^media/(?P.*)$

The current path, student_result , didn’t match any of these.

You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False , and Django will display a standard 404 page.

But the inputs data is now saving to database

And here is my project’s urls.py:

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('account.urls')),
    path('studentportal/', include('studentportal.urls')),
]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


Cool! We’re past one problem and on to the next.

Let’s start with the information we have here - what’s your best guess as to what this error is telling you?
What do you think is happening here?

1 Like

The error is pointing to project’s urls.py and I couldn’t see what is wrong there

You’re really close - it’s not saying that there’s an error in the urls.py file, just that there’s no entry in the urls.py file for the url student_result. This does not necessarily mean that there’s something wrong with that file.

This actually means one of two things:

  • You’re not specifying the right url in your view to be redirected to after a successful form submission.
  • If this is the right url, you’re missing an entry for it in the urls.py.
1 Like

Thanks Ken. The views.py has get_success_uls and here is it

class ResultCreateView(CreateView ):
    template_name = 'studentportal/result_create.html'
    form_class = ResultModelForm
    queryset = StudentResult.objects.all()
    model = StudentResult
    
        
    def form_valid(self, form):
        print(form.cleaned_data)
        return super().form_valid(form)
        
    def get_success_url(self):
        return '/student_detail'
 

And for the second option, i don’t really understand that but here is my urls

app_name = 'studentportal'
urlpatterns = [
    path('student_list', StudentListView.as_view(), name='student_list'),
    path('<int:pk>/', StudentDetailView.as_view(), name='student_detail'),
    path('create/', StudentCreateView.as_view(), name='student_create'),
    path('<int:pk>/update/', StudentUpdateView.as_view(), name='student_update'),
    path('<int:pk>/delete/', StudentDeleteView.as_view(), name='student_delete'),
    
    path('resultcreate/', ResultCreateView.as_view(), name='result_create'),
    
    
]

Ok, in your studentportal urls, you have a named url student_detail, but not a url student_detail. If you’re looking to refer to that url by name, you need to use the reverse function.

Also note that the student_detail url requires a parameter to be passed to it, so your get_success_url needs to supply that parameter.

See the URL dispatcher docs for more details.

Alright, thanks for this. I’m very grateful. I will rectify that now

Hi, Ken. I have made the changes on both urls and views .
Urls.py

app_name = 'studentportal'
urlpatterns = [
    path('student_list', StudentListView.as_view(), name='student_list'),
    path('<int:pk>/', StudentDetailView.as_view(), name='student_detail'),
    path('create/', StudentCreateView.as_view(), name='student_create'),
    path('<int:pk>/update/', StudentUpdateView.as_view(), name='student_update'),
    path('<int:pk>/delete/', StudentDeleteView.as_view(), name='student_delete'),
    path('<int:pk>/result/', StudentResultView.as_view(), name='student_result'),
    path('result/resultcreate/', ResultCreateView.as_view(), name='result_create'),
    
]

Here is the views

class ResultCreateView(CreateView ):
    template_name = 'studentportal/result_create.html'
    form_class = ResultModelForm
    queryset = StudentResult.objects.all()
    model = StudentResult
    
    
        
    def form_valid(self, form):
        print(form.cleaned_data)
        return super().form_valid(form)
        
    def get_success_url(self):
        return HttpResponseRedirect(reverse('studentportal:student_detail'))

But I’m now getting this error after submitting the form

NoReverseMatch at /studentportal/result/resultcreate/

Reverse for ‘student_detail’ with no arguments not found. 1 pattern(s) tried: [‘studentportal/(?P[0-9]+)/result/$’]

And here is the template html

<form method="POST" action="">
            {% csrf_token %}
            {{ form|crispy }}
            
         
            <button class="regBtn">Submit</button>
        <form/>

This is the url you are rendering:

And so:

1 Like

Hello, I was just looking for a code example of such a code to understand which next step is correct.