I am getting a integrity error, I have tried adding null=True
to auto id field then its working but auto_id
field must not be blank=True
or null=True
.These models are given by my superiors I am finding this hard to understand
This is the core app models.py
import uuid
from django.db import models
from django.db.models import Max
from django.utils import timezone
from decimal import Decimal
from django.utils.translation import gettext_lazy as _
from django.core.validators import MinValueValidator
from core.utils import DictField
from django.contrib.auth import get_user_model
from django.contrib.humanize.templatetags.humanize import naturaltime
def basedata(self, request):
# Check is create
if self._state.adding:
self.auto_id = (self.__class__.objects.aggregate(max_auto_id=Max('auto_id')).get('max_auto_id') or 0) 1
if request.user.is_authenticated:
self.creator = request.user
# If updating
if request.user.is_authenticated:
self.updater = request.user
self.date_updated = timezone.now()
class BaseModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
auto_id = models.PositiveIntegerField(db_index=True, unique=True)
creator = models.ForeignKey(get_user_model(), blank=True, related_name="creator_%(class)s_objects", limit_choices_to={'is_active': True}, on_delete=models.CASCADE)
updater = models.ForeignKey(get_user_model(), blank=True, related_name="updater_%(class)s_objects", limit_choices_to={'is_active': True}, on_delete=models.CASCADE)
date_added = models.DateTimeField(db_index=True, auto_now_add=True)
date_updated = models.DateTimeField(auto_now_add=True)
is_deleted = models.BooleanField(default=False)
class Meta:
abstract = True
def delete(self):
self.is_deleted = True
self.save()
def delete_with_user(self, user):
self.is_deleted = True
user = self.user
user.username = user.username '_deleted_' str(self.id)
user.save()
self.save()
@property
def date_added_natural(self):
return naturaltime(self.date_added)
class Mode(models.Model):
readonly = models.BooleanField(default=False)
maintenance = models.BooleanField(default=False)
down = models.BooleanField(default=False)
class Meta:
db_table = 'mode'
verbose_name = _('mode')
verbose_name_plural = _('mode')
ordering = ('id',)
class Admin:
list_display = ('id', 'readonly', 'maintenance', 'down')
def __str__(self):
return str(self.id)
class AppUpdate(models.Model):
date_added = models.DateTimeField(db_index=True, auto_now_add=True)
app_version = models.CharField(max_length=16)
force_upgrade = models.BooleanField(default=False)
recommended_upgrade = models.BooleanField(default=False)
ios_app_version = models.CharField(max_length=16)
ios_force_upgrade = models.BooleanField(default=False)
ios_recommended_upgrade = models.BooleanField(default=False)
class Meta:
db_table = 'app_update'
verbose_name = _('App update')
verbose_name_plural = _('App updates')
ordering = ('id',)
def __str__(self):
return str(self.id)
This is the university models.py
from django.db import models
from core.models import BaseModel
from versatileimagefield.fields import VersatileImageField
# Create your models here.
class Graduation(BaseModel):
name = models.CharField(max_length=200)
class Meta:
db_table = 'university_graduation'
verbose_name = ('Graduation')
verbose_name_plural = ('Graduation')
ordering = ('auto_id',)
def __str__(self):
return str(self.name)
class University(BaseModel):
title = models.CharField(max_length=200)
location = models.CharField(max_length=200)
location_url = models.URLField()
estd = models.CharField(max_length=4)
ranking = models.CharField(max_length=4)
intake = models.CharField(max_length=3)
acceptance_rate = models.CharField(max_length=3)
teacher_ratio = models.CharField(max_length=3)
about_university = models.TextField()
description = models.TextField()
graduation = models.ManyToManyField(Graduation)
logo = VersatileImageField('Logo', upload_to="university/logo")
image = VersatileImageField('Image', upload_to="university/image")
class Meta:
db_table = 'university_university'
verbose_name = ('University')
verbose_name_plural = ('University')
ordering = ('auto_id',)
def __str__(self):
return str(self.title)
class AdmissionRequirments(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
auto_id = models.PositiveIntegerField(db_index=True, unique=True)
date_added = models.DateTimeField(db_index=True, auto_now_add=True)
date_updated = models.DateTimeField(auto_now_add=True)
university = models.ForeignKey(University, limit_choices_to={'is_deleted': False}, on_delete=models.CASCADE)
requirement = models.CharField(max_length=200)
class Meta:
db_table = 'university_admission_requirements'
verbose_name = ('Admission Requirements')
verbose_name_plural = ('Admission Requirements')
ordering = ('auto_id',)
def __str__(self):
return str(self.id)
class Scholarship(BaseModel):
title = models.CharField(max_length=200)
eligibility = models.CharField(max_length=200)
applicability = models.CharField(max_length=200)
graduation = models.ManyToManyField(Graduation)
university = models.ManyToManyField(University)
class Meta:
db_table = 'university_scholarship'
verbose_name = ('Scholarship')
verbose_name_plural = ('Scholarship')
ordering = ('auto_id',)
def __str__(self):
return str(self.title)
This is the university form.py
from django.forms import forms
from university.models import University, Graduation
from django.contrib.auth.models import User
from django.contrib.auth import get_user
class CreateUniversityForm(forms.Form):
class Meta:
model = University
fields = '__all__'
def save(self):
user = self.cleaned_data.get("user")
university = University(
auto_id = self.cleaned_data.get('id'),
title = self.cleaned_data.get('title'),
location = self.cleaned_data.get('location'),
location_url = self.cleaned_data.get('location_url'),
estd = self.cleaned_data.get('estd'),
ranking = self.cleaned_data.get('ranking'),
intake = self.cleaned_data.get('intake'),
acceptance_rate = self.cleaned_data.get('acceptance_rate'),
teacher_ratio = self.cleaned_data.get('teacher_ratio'),
about_university = self.cleaned_data.get('about_university'),
description = self.cleaned_data.get('description'),
logo = self.cleaned_data.get('logo'),
image = self.cleaned_data.get('image')
)
graduation = Graduation.objects.get(name=self.cleaned_data.get("graduation"))
university.set_graduation = graduation
university.set_creator = user
university.set_updator = user
university.save()
return university
This is my university view.py to create a university
def create_university(request):
if request.method == 'POST':
user = get_user(request)
logo = request.FILES.get('logo')
image = request.FILES.get('image')
auto_id = int(request.POST.get('id'))
title = request.POST.get('title')
graduation = "berlin"
location = request.POST.get('location')
location_url = request.POST.get('location_url')
established = request.POST.get('established')
ranking = request.POST.get('ranking')
intake = request.POST.get('intake')
acceptance_rate = request.POST.get('acceptance')
teacher_ratio = request.POST.get('teacher')
about_university = request.POST.get('about')
description = request.POST.get('description')
data = {
'user': user,
'title': title,
'id': auto_id,
'location': location,
'location_url': location_url,
'estd': established,
'ranking': ranking,
'intake': intake,
'acceptance_rate': acceptance_rate,
'teacher_ratio': teacher_ratio,
'about_university': about_university,
'description': description,
'logo': logo,
'image': image,
'graduation': graduation}
print(data)
create_university_form = CreateUniversityForm(data=data)
if create_university_form.is_valid():
university = create_university_form.save()
context = {
'title': university.title
}
return JsonResponse(context)
else:
context = {
"validationerror": "validation error"
}
return JsonResponse(context)
All i wanted to do is to create a new univerisity object but this auto_id is killing me, also i cant understand this BaseModel system
File "C:\Users\abinp\Documents\projects\tegain\venv\lib\site-packages\django\db\backends\utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: null value in column "auto_id" of relation "university_university" violates not-null constraint
DETAIL: Failing row contains (c496cf2f-2966-49f3-b2d4-9efa4f3323b4, null, 2022-08-08 10:36:59.869385 00, 2022-08-08 10:36:59.869385 00, f, null, null, null, null, null, null, null, null, null, null, , , null, null).
CodePudding user response:
As the error says, you have a null value in the ID column.
auto_id = models.PositiveIntegerField(db_index=True, unique=True)
You have PositiveIntegerField
, that means that you have to fill it and you're probably not doing that in forms. For ID you should always use AutoField
.
So it returns null because there is nothing in your auto_id variable. I think replace this with AutoField
should solve the problem.
Documentation search for AutoField
:
https://docs.djangoproject.com/en/4.1/ref/models/fields/