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

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

Related

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

Django - Query from a sub-table

I have an application that has a dropdown menu among other things.
The menu is created based on the requirements. I wrote a query that checks the statuses and calculates how many requirements are in a given status. Then he builds a menu out of it. However, I have a problem because sometimes a requisition has been created but no items have been added to it. In that case, my menu shows this as one of the items. This is not what he expects. I would like the query to return and count only those requirements in a given status that have children.
Below I paste the model code and inquiries.
class D_DemandStatus(ModelBaseClass):
status = models.CharField(max_length=20, unique=True)
name = models.CharField(max_length=50)
created_user = models.ForeignKey(User, on_delete=models.PROTECT)
def save(self, *args, **kwargs):
user = get_current_user()
if user and not user.pk:
user = None
if not self.pk:
self.created_user = user
self.modified_by = user
super(D_DemandStatus, self).save(*args, **kwargs)
def __str__(self):
return self.name
class Meta:
verbose_name = 'Demand status'
verbose_name_plural = 'Demands status'
class Demand(models.Model):
name = models.CharField(max_length=500)
status = models.ForeignKey(D_DemandStatus, default=3, on_delete=models.PROTECT, )
insert_user = models.ForeignKey(User, on_delete=models.PROTECT, editable=False)
insert_date = models.DateTimeField(default=datetime.datetime.now, editable=False)
def save(self, *args, **kwargs):
user = get_current_user()
if user and not user.pk:
user = None
if not self.pk:
self.insert_user = user
self.status = D_DemandStatus.objects.get(status='PREPARED')
self.modified_by = user
super(Demand, self).save(*args, **kwargs)
def __str__(self):
return self.name
def submitt(self, *args, **kwargs):
if self.pk :
dict_status = D_DemandStatus.objects.get(status='WAITING')
print(dict_status)
self.demanddetails_set.filter(demand_id = self.pk).update(status=dict_status)
self.status = dict_status
self.save()
def status_actualize(self, *args, **kwargs):
if self.pk :
dict_status = D_DemandStatus.objects.get(status='ORDERED')
items_status = DemandDetails.objects.filter(demand=self.pk).values('status').distinct()
if len(items_status) == 1 and items_status[0]['status'] == dict_status.id :
self.status = D_DemandStatus.objects.get(status='ORDERED')
#elif len(items_status) > 1 :
# self.status = D_DemandStatus.objects.get(status='INPROGRESS')
self.save()
class Meta:
verbose_name = 'Demand'
verbose_name_plural = 'Demands'
class DemandDetails(models.Model):
demand = models.ForeignKey(Demand, on_delete=models.CASCADE, related_name='items')
component = models.ForeignKey(Component, on_delete=models.CASCADE)
order_item = models.ForeignKey(OrderItem, null=True, on_delete=models.PROTECT, editable=False, related_name='demand_details_item')
quantity = models.IntegerField(default=1)
comment = models.CharField(max_length=150, blank=True)
status = models.ForeignKey(D_DemandStatus, default=3, on_delete=models.PROTECT, )
insert_user = models.ForeignKey(User, on_delete=models.PROTECT, editable=False)
insert_date = models.DateTimeField(auto_now_add=True)
def quantityUpdate(self, val):
if self.pk :
self.quantity = val
self.save()
def save(self, *args, **kwargs):
user = get_current_user()
if user and not user.pk:
user = None
if not self.pk:
self.insert_user = user
self.status = D_DemandStatus.objects.get(status='PREPARED')
if not self.pk:
try:
super(DemandDetails, self).save(*args, **kwargs)
except IntegrityError as e:
obj = DemandDetails.objects.get(demand_id=self.demand_id, component_id=self.component_id)
obj.quantity = obj.quantity + 1
obj.save()
else:
super(DemandDetails, self).save(*args, **kwargs)
def __str__(self):
return self.demand.name
class Meta:
verbose_name = 'Demand detail'
verbose_name_plural = 'Demand details'
constraints = [
models.UniqueConstraint(fields=['demand_id', 'component_id'], name='epm - DemandDetail (demand, component)' )
]
The query that works now looks like this:
demand_list = Demand.objects.values('status__name', 'status__id', 'status__status').annotate(count=Count('status__name')).filter(Q(status__status='WAITING') | Q(status__status='PREPARED')).order_by('-status__name')
In this case, however, even if the demand is empty (no items added), it is counted as 1
So I have changed the code a little, but it doesn't work as I would like, because it also counts the individual elements of the demand - which is obvious, because the query returns the subsequent rows that are counted.
demand_list = Demand.objects.values('status__name', 'status__id', 'status__status').annotate(count=Count('status__name'), piece=Count('demanddetails')).filter(Q(piece__gte=1)).filter(Q(status__status='WAITING') | Q(status__status='PREPARED')).order_by('-status__name')
I need to write the query in such a way that I get a list of statuses with numbers of demands only which have derived elements in DemandDetails. If a Demand exists but has no derived elements then it is not taken into account - rather it is counted as 0. This is important because in the extreme case there may be only one Demand which is empty and then I want to have information about it in the menu but with the number 0.
I hope I have managed to write clearly what I chaie.
Please help me to create a suitable query.
Regards

__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)

how to extend AbstractBaseUser with OneToOneFeild in django

I created AbstractBaseUser model and a BaseManager.
the model.py is given below
GENDER_CHOICES = (('M', 'Male'),('F', 'Female'))
class AccountManager(BaseUserManager):
def create_user(self,email,username,phone,gender,password=None,**extrafields):
if not email:
raise ValueError("email is needed")
if not username:
raise ValueError("uname is needed")
if not phone:
raise ValueError("Phone is needed")
if not gender:
raise ValueError("gender is needed")
user= self.model(
email=self.normalize_email(email),
username=username,
phone=phone,
gender=gender,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self,email,username,phone,gender,password,**extrafields):
user=self.create_user(
email=self.normalize_email(email),
password=password,
username=username,
phone=phone,
gender=gender,
)
user.is_admin=True
user.is_staff=True
user.is_superuser=True
user.save(using=self._db)
return user
class Account(AbstractBaseUser):
ACCTYPE = (
('Student', 'Student'),
('Staff', 'Staff')
)
email=models.EmailField(verbose_name='E-mail', max_length=30, unique=True)
username=models.CharField(verbose_name='Username', max_length=30, unique=True)
last_login=models.DateTimeField(verbose_name='Last Login', auto_now=True)
phone=models.CharField(verbose_name='Phone', max_length=50)
gender= models.CharField(choices=GENDER_CHOICES, max_length=128)
acctype = models.CharField(max_length=16, choices=ACCTYPE)
is_admin=models.BooleanField(default=False)
is_active=models.BooleanField(default=True)
is_staff=models.BooleanField(default=False)
is_superuser=models.BooleanField(default=False)
USERNAME_FIELD ='username'
REQUIRED_FIELDS=['email','phone','gender']
objects=AccountManager()
def __str__(self):
return self.username
def has_perm(self,perm,obj=None):
return self.is_admin
def has_module_perms(self, app_lebel):
return True
And I am also tried to extend this user model Into StudentAccnt and StaffAccnt.
class StudentAccnt(models.Model):
user=models.OneToOneField(Account,on_delete=models.CASCADE)
reg_number=models.CharField(verbose_name='Reg NO', max_length=10,unique=True)
class StaffAccnt(models.Model):
user=models.OneToOneField(Account,on_delete=models.CASCADE)
id_number=models.CharField(verbose_name='Id NO', max_length=10,unique=True)
I want to create user using UserRegistrarionForm and add to StudentAccnt and StaffAccnt tables by checking acctype.
how to do this??
Finally, I got a solution.
it can be created using signals
When I create views for this custom user registration form, it simultaneously creates a corresponding instance.
we need to import these
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.db import models
add this at end of the view
#receiver(post_save,sender=Account)
def create_usersaccnt(sender,instance,created,**kwrags):
if created and (instance.acctype=='Student'):
StudentAccnt.objects.create(user=instance)
elif created and (instance.acctype=='Staff'):
StaffAccnt.objects.create(user=instance)
#receiver(post_save,sender=Account)
def save_usersaccnt(sender,instance,created,**kwrags):
if instance.acctype=='Student':
instance.studentaccnt.save()
elif instance.acctype=='Staff':
instance.staffaccnt.save()
you can also specify it through additional python file called signals.py

NOT NULL constraint failed: IntegrityError

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.

Resources