Home > database >  IntegrityError at /update_dept/1/ NOT NULL constraint failed: main_department.dept_name
IntegrityError at /update_dept/1/ NOT NULL constraint failed: main_department.dept_name

Time:10-14

I am creating a simple django models of doctors and department. there is not link between them and when I try to update the department then it is show me this error IntegrityError at /update_dept/1/ NOT NULL constraint failed: main_department.dept_name this error is new for me. I check other similar question also but didn't get much. so pls help me.

here is my view.py file

from django.shortcuts import render
from .forms import Doctorslist,Departmentform
from .models import Department, Doctor
from django.shortcuts import redirect
from django.views.generic import (CreateView, DetailView, UpdateView, ListView, TemplateView, DeleteView) 
from django.contrib.messages import constants as messages
import os
# Create your views here.


def add_show(request):
    form = Doctorslist()
    if request.method == "POST":
        form = Doctorslist(request.POST, request.FILES)
        form.save()
        return redirect('/')
    else:
        form = Doctorslist()
    stud = Doctor.objects.all
    context = {'form':form,
                'stu':stud
                }
    return render(request, 'main/index.html', context)


def update_data(request, id):
    prod = Doctor.objects.get(id=id)

    if request.method == "POST":
        prod.doc_image = request.FILES['doc_image']
        prod.kycdocument = request.FILES['kycdocument']
        prod.name = request.POST.get('name')
        prod.phone_number = request.POST.get('phone_number')
        prod.email = request.POST.get('email')
        prod.city = request.POST.get('city')
        prod.speciality = request.POST.get('email')
        prod.save()
        messages.success(request, "Product Updated Successfully")
        return redirect('/')

    context = {'prod':prod}
    return render(request, 'main/update_doc.html', context)

def delete_data(request,id):
    if request.method =='POST':
        pi = Doctor.objects.get(pk = id)
        pi.delete()
        return redirect('/')

def add_show_dept(request):
    form = Departmentform()
    if request.method == "POST":
        form = Departmentform(request.POST)
        form.save()
        return redirect('/')
    else:
        form = Departmentform()
    dept = Department.objects.all
    context = {'form':form,
                'stu':dept
                }
    return render(request, 'main/pages-profile.html', context)


def update_dept_data(request, id):
    prod = Department.objects.get(id=id)

    if request.method == "POST":
        prod.dept_name = request.POST.get('dept_name')
        prod.dept_Email = request.POST.get('dept_Email')
        prod.save()
        messages.success(request, "Product Updated Successfully")
        return redirect('/')

    context = {'prod':prod}
    return render(request, 'main/update_dept.html', context)

here is model.py

from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
import os 
# Create your models here.
import datetime
def get_file_path(request, filename):
    filename_original = filename
    nowTime = datetime.datetime.now().strftime('%Y%m%d%H:%M:%S')
    filename = "%s%s" % (nowTime, filename_original)
    return os.path.join('uploads/', filename)


class Doctor(models.Model):
    name = models.CharField(max_length=20)
    phone_number = PhoneNumberField(null=False, blank=False, unique=True)
    email = models.EmailField(max_length = 100)
    city = models.CharField(max_length=100)
    speciality =  models.CharField(max_length=50)
    doc_image = models.ImageField(upload_to = get_file_path)
    kycdocument = models.ImageField(upload_to = get_file_path, null = True, blank = True)


class Department(models.Model):
    dept_name = models.CharField(max_length=20)
    dept_Email = models.EmailField(max_length=100)
    dept_password = models.CharField(max_length=200)

here is forms.py file

from django import forms
from phonenumber_field.modelfields import PhoneNumberField
from .models import Doctor,Department


class Doctorslist(forms.ModelForm):
    class Meta:
        model = Doctor
        fields = ('name','phone_number','email', 'city', 'speciality', 'doc_image', 'kycdocument')
        # widgets = {
        #     'name':  forms.TextInput(attrs = {'class': 'form-control'}),
        #     'email':  forms.EmailInput(attrs={'class': 'form-control'}),
        #     'city':  forms.CharField(attrs={'class': 'form-control'}),
        #     'speciality': forms.CharField(attrs={'class': 'form-control'}),
        # }   


class Departmentform(forms.ModelForm):
    class Meta:
        model = Department
        fields = ('dept_name','dept_Email','dept_password')
        widgets = {'dept_password': forms.PasswordInput()}

here is update_dept.html file

{% extends 'base.html' %}

{% block content %}
<div class="row justify-content-center">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header">
                <h2 class="fw-bold">Edit Product</h2>
            </div>
            <div class="card-body">
                <form action="" method="POST" enctype="multipart/form-data">
                    {% csrf_token %}
                    <div class="mb-3">
                        <label for="" class="form-label">Name</label>
                        <input type="text" Required name="name" value="{{ prod.dept_name }}" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label for="" class="form-label">Email</label>
                        <input type="text" Required name="price" value="{{ prod.dept_Email }}" class="form-control">
                    </div>
                    <button type="submit" class="btn btn-warning">Update</button>
                </form>
            </div>
        </div>
    </div>
</div>

{% endblock %}

CodePudding user response:

Your HTML form uses the wrong names, and therefore request.POST does not contain any entries like dept_name and dept_Email. You should specify name="dept_name" instead of name="name" and name="dept_Email" instead of name="price":

<div class="mb-3">
    <label for="" class="form-label">Name</label>
    <input type="text" Required name="dept_name" value="{{ prod.dept_name }}" class="form-control">
</div>
<div class="mb-3">
    <label for="" class="form-label">Email</label>
    <input type="text" Required name="dept_Email" value="{{ prod.dept_Email }}" class="form-control">
</div>

That being said, I would strongly advise that you use a ModelForm, you can make a second ModelForm for the department where you leave out the dept_password.

You can see the Rendering fields manually section of the documentation that shows how you can render you Django form with custom HTML.

  • Related