NOT NULL constraint failed: IntegrityError - django-models

Trying a django project from the documentations.
This is my Models.py I am trying to make a simple employee goals management system. I have also used DRF and serializers, integrated swagger for only doing 'GET' of the models below. I have removed (commented out) all ForeignKey and ManyToMany Fields yet, when I add modify the goal or project I get this error. I cant seem to solve this, please help.
class Department(models.Model):
department_name = models.CharField(max_length=200)
department_location = models.CharField(max_length=200)
department_region = models.CharField(max_length=200)
department_site = models.CharField(max_length=200)
department_job_titles = models.CharField(max_length=200)
def __str__(self):
return self.department_name
class Employee(models.Model):
#department_name = models.ManyToManyField(Department)
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
email_id = models.CharField(max_length=100)
#employee_id = models.IntegerField()
supervisor_name = models.CharField(max_length=100)
designation = models.CharField(max_length=100)
doj = models.DateTimeField('date joined')
def __str__(self):
return self.first_name
class Objectives(models.Model):
objective_name = models.CharField(max_length=200)
#employee = models.ManyToManyField(Employee)
def __str__(self):
return self.objective_name
class Project(models.Model):
#employee = models.ManyToManyField(Employee)
project_name = models.CharField(max_length=200)
def __str__(self):
return self.project_name
class Goals(models.Model):
goal_id = models.IntegerField()
goal_name = models.CharField(max_length=200)
#department = models.ManyToManyField(Department)
role = models.CharField(max_length=200)
#objective_id = models.ManyToManyField(Objectives)
goal_start = models.DateTimeField('date goal added')
goal_end = models.DateTimeField('date goal ends')
#employee = models.ManyToManyField(Employee)
def __str__(self):
return self.goal_name
This is my views.py
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import Employee
from .models import Goals
from .models import Objectives
from .models import Department
from .models import Project
from .serializers import EmployeeSerializer
from .serializers import ProjectSerializer
from .serializers import GoalsSerializer
from .serializers import ObjectivesSerializer
from .serializers import DepartmentSerializer
from django.http import HttpResponse
from rest_framework_swagger.views import get_swagger_view
schema_view = get_swagger_view(title='UpYourGame API')
#just a view if someone hits the index
def index(request):
return HttpResponse("Hello and Welcome to UpyourGame")
# this will be the URL /employee/
class Employee(APIView):
def get(self, request):
employee = Employee.objects.all()
serializer = EmployeeSerializer(employee, many=True)
return Response(serializer.data)
class Project(APIView):
def get(self, request):
project = Project.objects.all()
serializer = ProjectSerializer(project, many=True)
return Response(serializer.data)
class Goals(APIView):
def get(self, request):
goals = Goals.objects.all()
serializer = GoalsSerializer(goals, many=True)
return Response(serializer.data)
class Objectives(APIView):
def get(self, request):
objectives = Objectives.objects.all()
serializer = ObjectivesSerializer(objectives, many=True)
return Response(serializer.data)
#class Company(APIView):
# def get(self, request):
# company = Company.objects.all()
# serializer = CompanySerializer(company, many=False)
# return Response(serializer.data)
class Department(APIView):
def get(self, request):
department = Department.objects.all()
serializer = DepartmentSerializer(Department, many=True)
return Response(serializer.data)
This is myproject/urls.py
from django.conf.urls import include, url
from django.contrib import admin
from enterprise import views
urlpatterns = [
url(r'^$', views.schema_view, name='schema_view'),
url(r'^enterprise/', include('enterprise.urls')),
url(r'^admin/', admin.site.urls),
url(r'^employee/', views.Employee.as_view()),
url(r'^goals/', views.Goals.as_view()),
url(r'^department/', views.Department.as_view()),
url(r'^department/', views.Department.as_view()),
url(r'^objectives/', views.Objectives.as_view()),
url(r'^project/', views.Project.as_view()),
]
This is my serializers.py
from rest_framework import serializers
from .models import Employee
from .models import Goals
from .models import Objectives
from .models import Department
from .models import Project
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = '__all__'
#class EmployeeDetailsSerializer(serializers.ModelSerializer):
# class Meta:
# model = EmployeeDetails
# fields = '__all__'
class ObjectivesSerializer(serializers.ModelSerializer):
class Meta:
model = Objectives
fields = '__all__'
class DepartmentSerializer(serializers.ModelSerializer):
class Meta:
model = Department
fields = '__all__'
#class CompanySerializer(serializers.ModelSerializer):
# class Meta:
# model = Company
# fields = '__all__'
class GoalsSerializer(serializers.ModelSerializer):
class Meta:
model = Goals
fields = '__all__'
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = '__all__'

The SQLlite DB was corrupt due to too many migrations, it can happen. I deleted SQLlite and all my migrations, I retried migrate, makemigrate and sqlmigrate, it resolved the issue.
If you run into a similar issue in a dev environment please try the following
1. Delete all your migrations in the migrations folder
2. Delete db.sqlite3
3. Run python manage.py migrate
4. Run python manage.py makemigrations
5. Run python manage.py sqlmigrate appname 0001
This will fix this issue.

Related

AbstractBaseUser.get_username() missing 1 required positional argument: 'self' | Error while accessing current user's username

I am trying to access the Id of current logged in User. but i am getting the below error.
models.py of derived model
from django.db import models
from django.urls import reverse, reverse_lazy
from django.utils import timezone
from accounts.models import CustomUser
# Create your models here.
class PostProblem(models.Model):
problem_type_choices = (
('c','Confidential'),
('sc','Semi-confidential'),
('p','Public')
)
problem_category_choices = (
('agriculture','Agriculture'),
('computer_science','Computer Science'),
('social_studies','Social Studies'),
('environment','Environmental Science'),
('mathematics','Mathematics'),
('engineering','Engineering'),
('physics','physics'),
('chemistry','chemistry'),
('other','Other')
)
author = models.ForeignKey("accounts.CustomUser", verbose_name= "Creater", default = CustomUser.get_username ,on_delete=models.CASCADE)
problem_title = models.CharField(max_length=200, verbose_name="Problem's title")
problem_type = models.CharField(choices=problem_type_choices,max_length=5, verbose_name='Confidentiality of the problem ')
problem_category = models.CharField(choices=problem_category_choices, max_length=50, verbose_name="Catrgory of the problem")
problem_brief = models.CharField(max_length=1000, verbose_name='Breif description of the problem ')
problem_description = models.TextField(verbose_name='Problem complete description ')
problem_reward = models.IntegerField(verbose_name='Prize money for providing the solution ')
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now
self.save()
def __str__(self):
return self.problem_title
def get_absolute_url(self):
return reverse("problem_detail", kwargs={"pk": self.pk})
def approve_solutions(self):
return self.solutions.filter(approved_solutions = True)
views.py
from django.shortcuts import render
from django.urls import reverse_lazy
from django.utils import timezone
from django.contrib.auth.mixins import LoginRequiredMixin
from problems.models import PostProblem, Solutions
from problems.forms import PostProblemForm, SolutionsForm
from django.views.generic import TemplateView, CreateView, DetailView, DeleteView, UpdateView, ListView
# Create your views here.
class PostProblemCreateView(CreateView, LoginRequiredMixin):
login_url = 'login/'
redirect_field_name = 'problems/problem_detail.html'
form_class = PostProblemForm
model = PostProblem
forms.py
from django import forms
from problems.models import PostProblem, Solutions
class PostProblemForm(forms.ModelForm):
class Meta:
model = PostProblem
fields = ("problem_title","problem_type","problem_category","problem_brief","problem_description","problem_reward")
widgets = {
'problem_title':forms.TextInput(attrs={'class':'textinputclass'}),
'problem_type': forms.TextInput(attrs={'class':'choice_input'}),
'problem_category':forms.TextInput(attrs={'class':'choice_input'}),
'problem_brief': forms.Textarea(attrs={'class':'editable medium-editor-textarea post_brief'}),
'problem_description': forms.Textarea(attrs={'class':'editable medium-editor-textarea post_complete'}),
'problem_reward': forms.TextInput(attrs={'class':'textinputclass'})
}
model.py of base model
from django.db import models
from django.contrib import auth
from django.urls import reverse
# Create your models here.
# for custom user
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, User
from .managers import CustomUserManager
class CustomUser(AbstractBaseUser, PermissionsMixin):
'''Model representation for user'''
user_type_choices = (
('ps','Problem Solver'),
('pp','Problem Provider')
)
account_type_choices = (
('o','Organization'),
('i','Individual')
)
user_type = models.CharField(max_length=5, choices=user_type_choices, default='pp', verbose_name="Who you are? ")
account_type = models.CharField(max_length=5, choices= account_type_choices, default='o', verbose_name="Account Type ")
email = models.EmailField(max_length=50, unique=True, blank=False, verbose_name="Your Email ")
is_active = models.BooleanField(default=True) # anyone who signs up for thsi application is by default an active user
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False) # the person who has highest level of control over database
# need to specify manager class for this user
objects = CustomUserManager()
# we are not placing password field here because the password field will always be required
REQUIRED_FIELDS = ['user_type', 'account_type']
USERNAME_FIELD = 'email'
EMAIL_FIELD = 'email'
I searched the web for answers but they have mentioned only about accessing current user id in function based views. How can I resolve this kind of error? I am new to Django.

Cannot access database instances with id=pk

Here is my views.py file. I input the required fields through form like this:
from django.shortcuts import render, redirect
from .models import nekor_Table
from .forms import user_form
def home(request):
user_form_obj = user_form()
if request.method == "POST":
form = user_form(request.POST)
if form.is_valid():
form.save()
else:
form = user_form_obj()
context = {'user_form_obj': user_form_obj}
return render(request, 'polls/home.html', context )
def nav(request):
return render(request, 'navbar.html')
def display(request, pk):
display_table_obj = nekor_Table.objects.get(id=pk)
context = {'display_table_obj': display_table_obj}
return render(request, 'polls/display_page.html', context)
i have two tables and when i try to get individual instance with id=pk, and running http://127.0.0.1:8000/display/1/ in my browser it gives me: nekor_Table matching query does not exist, error. what am i missing here? this was working just fine in my previous project but doesnt work in this one.
here is my urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('index/', views.home, name='home'),
path('navbar/', views.nav, name='navbar'),
path('display/<int:pk>/', views.display, name='display')
]
and here is my models.py
from django.db import models
from django.contrib.auth.models import User
class nekor_Table(models.Model):
title = models.CharField(max_length=200, null=True, blank=False)
place = models.CharField(max_length=200, null=True, blank=False)
deity = models.CharField(max_length=200, null=True, blank=False)
description = models.TextField(null=True, blank=False)
teachers = models.CharField(max_length=200, null=True, blank=False)
architecture = models.CharField(max_length=200, null=True, blank=False)
def __str__(self):
return self.title

__str__ returned non-string (type Category). when I add post from admin

After I added user and date_added in the Photo models, when I add post from admin its throws me an error saying: str returned non-string (type Category), when I click on the addpost link in the home template its throw another error: 'tuple' object has no attribute 'name'. how can I solve that ?
the models.py:
from django.db import models
from cloudinary.models import CloudinaryField
from django.contrib.auth.models import User
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=100, null=False, blank=False)
def __str__(self):
return self.name
class Photo(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True,
blank=True)
image = CloudinaryField('image')
description = models.TextField(null=True)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.category
the view.py file:
def home(request):
category = request.GET.get('category')
if category == None:
photos = Photo.objects.all()
else:
photos = Photo.objects.filter(category__name=category)
categories = Category.objects.all()
context = {'categories': categories, 'photos': photos}
return render(request, 'home.html', {'categories': categories, 'photos': photos} )
def viewPhoto(request, pk):
photo = Photo.objects.get(id=pk)
return render(request, 'photo.html', {'phpto': photo})
class PostCreativeView(LoginRequiredMixin, CreateView):
model = Photo, Category
fields = ['description', 'image', 'category', 'name']
template_name = 'post_create.html'
def form_valid(self, form):
form.instance.user = self.request.user
return super (PostCreativeView, self).form_valid(form)
Well it has to do with your category name and model you added into post create view.py and so you
have do something like this:
views.py
class PostCreativeView(LoginRequiredMixin, CreateView):
model = Photo
fields = ['description', 'image', 'category']
template_name = 'post_create.html'
def form_valid(self, form):
form.instance.user = self.request.user
return super (PostCreativeView, self).form_valid(form)
#.......
# Models.py
class Photo(models.Model):
#>>>...
def __str__(self):
return str(self.category)
You should return the str(…) of the category, so:
class Photo(models.Model):
# …
def __str__(self):
return str(self.category)

django 'User' object has no attribute 'profile' while using post_save

This error is showing while login to admin panel " 'User' object has no attribute 'profile' "
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.
class Student(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='student')
age = models.IntegerField(max_length=2)
standard = models.CharField(max_length=15)
def __str__(self):
return self.user.username
#receiver(post_save, sender=User)
def create_student_profile(sender, instance, created, **kwargs):
if created:
Student.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_student_profile(sender, instance, **kwargs):
instance.profile.save()
subject_choices = [
('math','math'),
('science','science'),
('physics','physics'),
]
class Teacher(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='teacher')
subject = models.CharField(max_length=20, choices=subject_choices)
def __str__(self):
return self.user.username
#receiver(post_save, sender=User)
def create_teacher_profile(sender, instance, created, **kwargs):
if created:
Teacher.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_teacher_profile(sender, instance, **kwargs):
instance.profile.save()
batch_choices = [
('10','10:00 AM'),
('12','12:00 PM'),
('02','02:00 PM'),
('04','04:00 PM')
]
class Batch(models.Model):
b_name = models.CharField(max_length=20)
b_time = models.CharField(max_length=10, choices=batch_choices)
also I want that whenever a student registers, a batch is created named by the time field in it and on every 41st student, creates another batch having the next time choice

Where is the error ValueError: ModelForm has no model class specified

I can't fix the problem. I want to generate weeks and give it a name but it returns an error --> ValueError: ModelForm has no model class specified.
Django version 2.2.24
Python3
CODE:
models.py
from django.db import models
from django.forms import ModelForm
class Semana(models.Model):
nombre = models.CharField(max_length=30)
lunes_inicio = models.TimeField()
lunes_fin = models.TimeField()
martes_inicio = models.TimeField()
martes_fin = models.TimeField()
miercoles_inicio = models.TimeField()
miercoles_fin = models.TimeField()
jueves_inicio = models.TimeField()
jueves_fin = models.TimeField()
viernes_inicio = models.TimeField()
viernes_fin = models.TimeField()
sabado_inicio = models.TimeField()
sabado_fin = models.TimeField()
domingo_inicio = models.TimeField()
domingo_fin = models.TimeField()
forms.py
from django import forms
from TaskManager.models import Semana
class FormularioSemana(forms.ModelForm):
class meta:
model = Semana
fields = '__all__'
widgets = {'lunes_inicio': forms.TimeInput(attrs={'type': 'time'})}
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpRequest
from .models import Semana
from .forms import FormularioSemana
def task(request):
return HttpResponse("Hello, world. You're at the polls index.")
class FormularioSemanaView(HttpRequest):
def index(request):
semana = FormularioSemana()
return render(request, "semana.html", {"form":semana})
def procesar(request):
semana = FormularioSemana(request.post)
if semana.is_valid():
semana.save()
semana = FormularioSemana()
return render(request, "semana.html", {"form":semana, "mensaje": OK})
urls.py
from django.urls import path
from . import views
from .views import FormularioSemanaView
urlpatterns = [
path('task/', views.task, name='task' ),
path('semana/', FormularioSemanaView.index, name='semana'),
path('guardarSemana/', FormularioSemanaView.procesar, name='guardarSemana')
]
I'm starting to despair
I tried with several columns with attrs time and only one how this example, left only two columns,

Resources