class Organization(models.Model):
mLeader = models.ForeignKey(User)
mName = models.CharField(max_length=30, default='-')
mTel = models.CharField(max_length=15, default='-')
mAddress = models.TextField(default='-')
mType = models.CharField(max_length=1, default='A') # A : Daycare Center, B : private educational institute, C : Church, D : ...
owner = models.ForeignKey('auth.User', related_name='Organization')
def __str__(self) :
return self.mName
class OrganizationLeader(models.Model):
#private info
mUser = models.ForeignKey(User)
owner = models.ForeignKey('auth.User', related_name='Leader')
# mName = models.CharField(max_length=30, default='-')
class BusLine(models.Model):
mOrganization = models.ForeignKey(Organization)
mName = models.CharField(max_length=30, default='-')
mIsPrivate = models.BooleanField(default=True)
mCreated = models.DateTimeField(auto_now_add=True)
mIsCycle = models.BooleanField(default=False)
owner = models.ForeignKey('auth.User', related_name='lines')
class Meta:
ordering = ('mCreated', )
class BusStation(models.Model):
mName = models.CharField(max_length=30, default='-')
mCreated = models.DateTimeField(auto_now_add=True)
mOrder = models.IntegerField(default=None)
mIsStart = models.BooleanField(default=False)
mIsEnd = models.BooleanField(default=False)
mBusLine = models.ManyToManyField('BusLine', blank=True, null=True)
#변수명이 고정돼있어 접미사 붙이지 않음
mpoint = models.PointField(default=None)
objects = models.GeoManager()
Latitude = models.DecimalField(default=0.0, max_digits=10, decimal_places=6)
Longitude = models.DecimalField(default=0.0, max_digits=10, decimal_places=6)
owner = models.ForeignKey('auth.User', related_name='stations')
class Meta:
ordering = ['mOrder']
class Bus(models.Model):
mDriver = models.ForeignKey(User)
mDriving = models.BooleanField(default=False)
mCurrentStation = models.IntegerField(default=0)
mCreated = models.DateTimeField(auto_now_add=True)
mName = models.CharField(max_length=100)
mBusLine = models.ForeignKey('BusLine', on_delete=models.CASCADE, blank=True, null=True)
mArrive = models.BooleanField(default=False)
#LSB Data
#변수명이 고정돼있어 접미사 붙이지 않음
mpoint = models.PointField(default=None)
objects = models.GeoManager()
Latitude = models.DecimalField(default=0.0, max_digits=10, decimal_places=6)
Longitude = models.DecimalField(default=0.0, max_digits=10, decimal_places=6)
owner = models.ForeignKey('auth.User', related_name='buses')
def save(self, *args, **kwargs):
self.Latitude = self.mpoint.y
self.Longitude = self.mpoint.x
super(Bus, self).save(*args, **kwargs)
class Meta:
ordering = ('mCreated', )
class PassengerLogManager(models.Manager):
def create_log(self, id):
log = self.create(mBusId = id)
return log
class PassengerLog(models.Model):
mBusId = models.IntegerField()
mCreated = models.DateTimeField(auto_now_add=True,)
#JSON 필드에 버스의 한 회차 정류장당 탑승자 리스트가 저장됨
mLog = JSONField()
objects = PassengerLogManager()
class AppUser(models.Model):
#private info
mUser = models.ForeignKey(User)
mBaseDestination = models.ForeignKey(
BusStation,
verbose_name = 'BaseDestination',
default = '-',
)
mName = models.CharField(
verbose_name = 'UserName',
max_length=30,
blank = False,
default = '-'
)
mChild = models.ManyToManyField(
'self',
through = 'ParentToChildEntry',
verbose_name = 'Child',
through_fields = ('mParent','mChild'),
symmetrical = False,
)
owner = models.ForeignKey('auth.User', related_name='User')
def __str__(self) :
return self.mName
class ParentToChildEntry(models.Model) :
mName = models.CharField(
max_length = 20,
verbose_name = 'Title',
blank = False,
default = '-'
)
mParent = models.ForeignKey(
AppUser,
verbose_name = 'Parent',
related_name = 'Parent',
)
mChild = models.ManyToManyField(
AppUser,
verbose_name = 'Child',
related_name = 'Child',
)
def __str__(self) :
return self.mName
class OrganizationToUserEntry(models.Model) :
mName = models.CharField(
max_length = 20,
verbose_name = 'Title',
blank = False,
default ='-'
)
mOrganizations = models.ForeignKey(
Organization,
verbose_name = 'Organization'
)
mUsers = models.ManyToManyField(
AppUser,
verbose_name = 'Users'
)
def __str__(self) :
return self.mName
The code above is a Bus managing system model.(Django version 1.11.4)
Firstly when I tried to start and test this in admin,
the error (1054, "Unknown column 'DataMng_appuser.mBaseDestination_id' in 'field list'")
aroused so I flushed DB and migrated model.
However, When I tried to migrate this model, system returned me
[WARNINGS: DataMng.BusStation.mBusLine: (fields.W340) null has no effect on ManyToManyField.]
I repeatedly found how to solve this problem but I couldn't find.
Please tell me what I should do T_T. Thank you for reading.
Related
Does anyone know how can I successfully solve this am getting detail not found error and am trying to get object using ModelView set and raw query
this is my class
class jointtableapi(viewsets.ModelViewSet):
queryset = JoinStudentPadTable.objects.raw('SELECT regno, first_name, last_name, school_name,collection_date, last_collected, served_by FROM fulalapp_studentregistrationdetails INNER JOIN fulalapp_studentpadcollectiondetails ON fulalapp_studentregistrationdetails.id = fulalapp_studentpadcollectiondetails.regno_id')
serializer_class = JoinStudentPadTableSerializer
lookup_field = 'regno_id'
and the url
path('padcollectionjoin-detail/<regno_id>/', jointtableapi.as_view({'get':'retrieve'}), name='padcollectionjoin-detail')
am getting the detail not found error
My Models
from datetime import datetime
from pyexpat import model
from django.db import models
from django.utils import timezone
def user_directory_path(instance, filename):
return 'img/{0}'.format(filename)
Create your models here.
class StudentRegistrationDetails(models.Model):
student_status = (
('present', 'Present'),
('absent', 'Absent'),
)
#student details
regno = models.CharField(max_length=30)
first_name = models.CharField(max_length=30, blank = True, verbose_name = 'First Name')
last_name = models.CharField(max_length=30, blank = True, verbose_name = 'Last Name')
dob = models.DateField(verbose_name = 'Date Of Birth')
county = models.CharField(max_length=30, blank = True, verbose_name = 'County')
constituency = models.CharField(max_length=30, blank = True, verbose_name = 'Constituency')
school_name = models.CharField(max_length=30, blank = True, verbose_name = 'School Name')
grade = models.CharField(max_length=10, blank = True, verbose_name = 'Class/Grade')
dom = models.DateField(verbose_name = 'Date Of Menstruation')
photoid = models.ImageField(null = True, blank = True)
status = models.CharField(max_length=11, choices=student_status, default='present')
created = models.DateTimeField(default=timezone.now)
#parent details
parent_name = models.CharField(max_length=30, blank = True, verbose_name = 'Parent/Guardian Name')
phoneno = models.CharField(max_length=30, blank = True, verbose_name = 'Phone Number')
def __str__(self):
return str(self.regno)
class Meta:
verbose_name_plural = "Student Registration Details"
class StudentPadCollectionDetails(models.Model):
collection_date = models.DateField(default=datetime.now, verbose_name='Collection Date')
last_collected = models.DateField(verbose_name='Last collection Date')
served_by = models.CharField(max_length=30, verbose_name='Served BY')
regno = models.ForeignKey("StudentRegistrationDetails", related_name='pad_collection' , verbose_name=("Student ID"), on_delete=models.CASCADE)
def _str_(self):
return str(self.regno)
class Meta:
verbose_name_plural = 'Student Pad Collection Details'
class JoinStudentPadTable(models.Model):
regno = models.CharField(primary_key=True, max_length=30)
first_name = models.CharField(max_length=30, blank = True, verbose_name = 'First Name')
last_name = models.CharField(max_length=30, blank = True, verbose_name = 'Last Name')
school_name = models.CharField(max_length=30, blank = True, verbose_name = 'School Name')
collection_date = models.DateField(default=datetime.now, verbose_name='Collection Date')
last_collected = models.DateField(verbose_name='Last collection Date')
served_by = models.CharField(max_length=30, verbose_name='Served BY')
def _str_(self):
return str(self.regno)
class Meta:
verbose_name_plural = 'Joint Student Pad Collection Details'
I want that in my project the members who are having role as manager should not be able to see the priority field while updating the form
models.py
class Ticket(models.Model):
status_choice = (
("Approval", "Approval"),
("Assigned", "Assigned"),
("Scoping", "Scoping"),
("In Progress", "In Progress"),
("Completed", "Completed"),
("Cancelled", "Cancelled"),
("Rejected", "Rejected"),
)
priority_choice = (
("High", "High"),
("Moderate", "Moderate"),
("Low", "Low"),
)
category = models.ForeignKey("vats.Category", on_delete=models.CASCADE)
subcategory = models.ForeignKey("vats.Subcategory", on_delete=models.CASCADE)
title = models.CharField(
_("Title"),
max_length=50,
)
problem_descp = models.TextField(_("Problem Description"), max_length=500)
created_by = models.ForeignKey("registration.User", related_name=_("Issues"), on_delete=models.CASCADE)
priority = models.CharField(_("Priority"), max_length=50, null=True, blank=True, choices=priority_choice)
start_date_time = models.DateTimeField(_("Start Date Time"), auto_now_add=True)
end_date_time = models.DateTimeField(_("End Date Time"), null=True, blank=True)
assigned_to = models.ForeignKey("registration.User", related_name=_("Tasks"), on_delete=models.SET_NULL, null=True, blank=True)
status = models.CharField(_("Status"), max_length=50, choices=status_choice, null=True, blank=True)
class Meta:
verbose_name = _("Ticket")
verbose_name_plural = _("Tickets")
def __str__(self):
return self.title
def is_open(self):
if self.status == "Completed" or self.status == "Cancelled":
return False
return True
forms.py
class TicketForm(forms.ModelForm):
# subcategory = forms.ModelChoiceField(queryset=Subcategory.objects.filter(category__id = self.fields['category']))
class Meta:
model = Ticket
fields = ("category", "subcategory", "title", "problem_descp")
class TicketUpdateForm(forms.ModelForm):
class Meta:
model = Ticket
fields = ("category", "subcategory", "title", "problem_descp", "status", "assigned_to", "priority")
def __init__(self, *args, **kwargs):
super(TicketUpdateForm, self).__init__(*args, **kwargs)
self.fields["category"].disabled = True
self.fields["subcategory"].disabled = True
self.fields["title"].disabled = True
self.fields["problem_descp"].disabled = True
I have three Models, in third models Foreign Key and ManyToMany fields are linked, which are:
Personal_info Models.py
class Personal_info(models.Model):
gen_choices = (
("पुरुष", "पुरूष"),
("महिला", "महिला"),
("तेस्रो", "तेस्रो"),
)
pinfo_id = models.AutoField(primary_key=True)
userid = models.OneToOneField(User, on_delete=models.CASCADE)
nfullname = models.CharField(validators=[max_len_check], max_length=128)
efullname = models.CharField(validators=[max_len_check], max_length=128)
dob_ad = models.DateField()
dob_bs = models.DateField()
gender = models.CharField(max_length=6, choices=gen_choices)
citizen_no = models.CharField(max_length=56)
cissue_dist = models.ForeignKey(District, on_delete=models.CASCADE)
cissue_date = models.DateField()
language = models.CharField(max_length=56)
p_district = models.CharField(max_length=56)
p_vdc = models.CharField(max_length=56)
p_ward = models.CharField(max_length=2)
p_city = models.CharField(max_length=56)
t_district = models.CharField(max_length=56)
t_vdc = models.CharField(max_length=59)
t_ward = models.CharField(max_length=2)
t_city = models.CharField(max_length=56)
telephone = models.BigIntegerField(null=True, blank=True)
mobile = models.BigIntegerField()
mother_name = models.CharField(validators=[max_len_check], max_length=128)
mother_cit = models.CharField(max_length=10, null=True)
father_name = models.CharField(validators=[max_len_check], max_length=128)
father_cit = models.CharField(max_length=10, null=True)
gfather_name = models.CharField(validators=[max_len_check], max_length=128)
gfather_cit = models.CharField(max_length=10, null=True)
spose_name = models.CharField(validators=[max_len_check], max_length=128, null=True)
spose_cit = models.CharField(max_length=10, null=True, blank=True)
image = models.FileField(upload_to="photos/", null=True, blank=True)
cit_image = models.FileField(upload_to="citizens/")
inclu_image = models.FileField(upload_to="inclusions/", null=True)
active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
def __str__(self):
return str(self.efullname)
Educational Models.py
class Education(models.Model):
edu_id = models.AutoField(primary_key=True)
userid = models.ForeignKey(User, on_delete=models.CASCADE)
institute = models.CharField(max_length=255, validators=[max_len_check])
board = models.CharField(max_length=128, validators=[max_len_check1])
pexam = models.CharField(max_length=16, choices=exam_choices)
faculty = models.CharField(max_length=16, choices=fac_choices)
division = models.CharField(max_length=16, validators=[max_len_check2])
tmarks = models.IntegerField()
percent = models.FloatField(null=True, blank=True)
mainsub = models.CharField(max_length=16, validators=[max_len_check2])
image = models.FileField(upload_to="educations/", null=True, blank=True)
active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
def __str__(self):
return str(self.userid)
V_applied models.py
class V_applied(models.Model):
appNo = models.IntegerField(null=True, blank=True, default=add_one)
p_srlno = models.IntegerField(blank=True, null=0, default=0)
userid = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Vacancy,on_delete=models.CASCADE)
inclusive = models.ManyToManyField(Inclusive)
bank = models.CharField(max_length=128)
v_no = models.CharField(max_length=32, validators=[max_len_check1])
dep_date = models.DateField()
ser_fee = models.IntegerField()
image = models.FileField(upload_to="vouchers/")
personal_info = models.ForeignKey(Personal_info, on_delete=models.CASCADE, blank=True)
education = models.ManyToManyField(Education, blank=True, default=0)
active = models.BooleanField(default=True)
status = models.CharField(max_length=10, validators=[max_len_check], default="Pending")
remarks = models.CharField(max_length=56, validators=[max_len_check1], default="Pending")
comment = models.CharField(max_length=128, validators=[max_len_check2], blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
#property
def per_info(self):
return (self.personal_info.efullname, self.personal_info.gender, )
'''
def __str__(self):
return str(self.userid) + ':' + str(self.post)
Here I want to make auto save method in CreateView for ForeignKey & ManyToMany fields of V_applied models, for this I tried views.py as below:
#method_decorator(login_required(login_url='login'), name='dispatch')
class v_appliedadd(CreateView):
form_class = V_appliedForm
template_name = 'v_applied/v_applied_form.html'
success_url = '/v_applied/vapp_details/'
def form_valid(self, form):
form.instance.userid = self.request.user
form.instance.personal_info = Personal_info.objects.get(userid=self.request.user)
educationall = Education.objects.filter(userid=self.request.user)
for edu in educationall:
form.instance.education.add(edu)
return super().form_valid(form)
While saving data Error display like this:
ValueError at /v_applied/v_appliedadd/
"<V_applied: testuser>" needs to have a value for field "id" before this many-to-many relationship can be used.
Request Method: POST
Request URL: http://localhost:8000/v_applied/v_appliedadd/
Django Version: 3.0.8
Exception Type: ValueError
Exception Value:
"<V_applied: testuser>" needs to have a value for field "id" before this many-to-many relationship can be used.
Exception Location: C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related_descriptors.py in __init__, line 846
Python Executable: C:\Users\User\AppData\Local\Programs\Python\Python38\python.exe
Python Version: 3.8.1
Python Path:
['D:\\DjangoProject\\app_epf',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\DLLs',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\lib',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38',
'C:\\Users\\User\\AppData\\Roaming\\Python\\Python38\\site-packages',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages']
Server time: Mon, 14 Sep 2020 23:09:21 +0545
I am new in python-django, please help me how to solve it.
form.instance.userid = self.request.user
form.instance.personal_info = Personal_info.objects.get(userid=self.request.user)
instance_from = form.save()
educationall = Education.objects.filter(userid=self.request.user)
for edu in educationall:
instance_edu = Education.objects.get(pk=edu.pk)
instance_from.education.add(instance_edu)
instance_from.save()
return super().form_valid(form)
I have made this function that runs every time a user logs in. I want to get the branch from 'user' but every time the session is set it's only available to the function even after setting it to BRANCH_ID in the settings file. any help? plus I don't want to do anything in view function with the request as it's not accessible from models
EDIT
I have added all the models
def perform_some_action_on_login(sender, request, user, **kwargs):
"""
A signal receiver which performs some actions for
the user logging in.
"""
request.session[settings.BRANCH_ID] = user.profile.branch_id
branch = request.session.get(settings.BRANCH_ID)
print(branch)
user_logged_in.connect(perform_some_action_on_login)
class WaybillTabularInlineAdmin(admin.TabularInline):
model = WaybillItem
extra = 0
# form = WaybillItemForm
fk_name = 'waybill'
autocomplete_fields = ('product',)
class WaybillAdmin(admin.ModelAdmin):
list_display = (
'from_branch',
'to_branch',
'updated_by',
)
list_filters = (
'from_branch',
'to_branch',
'product',
)
inlines = [WaybillTabularInlineAdmin]
readonly_fields = ("updated_by",)
what I was trying to do is products by the branch
class Waybill(models.Model):
from_branch = models.ForeignKey(
Branch,
default=1,
on_delete=models.CASCADE, related_name='from_branch')
to_branch = models.ForeignKey(
Branch, on_delete=models.CASCADE, related_name='to_branch')
comments = models.CharField(max_length=1024, blank=True)
created_date = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(
User, on_delete=models.CASCADE,
blank=True, null=True,
related_name='waybill_created')
updated = models.BooleanField(default=False)
updated_by = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='waybill_user')
def __str__(self):
return 'from {} to {}'.format(
self.from_branch.branch_name,
self.to_branch.branch_name,
)
class WaybillItem(models.Model):
waybill = models.ForeignKey(Waybill, on_delete=models.CASCADE)
product = models.ForeignKey(ProductDetail, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField()
def __str__(self):
return 'from {} to {}'.format(
self.waybill.from_branch,
self.waybill.to_branch
)
class Product(models.Model):
item = models.ForeignKey(
Item, on_delete=models.CASCADE, related_name="product")
branch = models.ForeignKey(
Branch, default=1, on_delete=models.CASCADE)
in_stock = models.BooleanField(default=True)
created_date = models.DateTimeField(auto_now_add=True)
updated_date = models.DateTimeField(auto_now=True)
objects = ProductManager()
class Meta:
verbose_name = "Inventory"
verbose_name_plural = "Inventories"
ordering = ("-created_date",)
constraints = [
models.UniqueConstraint(
fields=['item', 'branch'], name='unique product'),
]
def __str__(self):
return self.item.item_description
class ProductDetail(models.Model):
ITEM_CONDITION_CHOICES = (
("NEW", "New"),
("BROKEN", "Broken"),
("FAIRLY USED", "Fairly Used"),
)
condition = models.CharField(max_length=12, choices=ITEM_CONDITION_CHOICES,
default=ITEM_CONDITION_CHOICES[0][0])
product = models.ForeignKey(Product, on_delete=models.CASCADE)
short_description = models.CharField(max_length=255, blank=True)
color = models.CharField(max_length=15, blank=True)
bought_price = models.PositiveIntegerField(default=0.00)
sales_price = models.PositiveIntegerField(default=0.00)
retail_price = models.PositiveIntegerField(default=0.00)
item_code = models.CharField(max_length=15, default=0)
item_model_number = models.CharField(max_length=20, default=0)
quantity = models.PositiveIntegerField(default=0)
manufacturer_website = models.CharField(max_length=255, blank=True)
generated_url = models.CharField(max_length=255, blank=True)
created_date = models.DateTimeField(default=timezone.now)
updated_date = models.DateTimeField(auto_now=True)
# objects = ProductDetailManager()
I want to use a raw query in order to make a JOIN in a many to many relationship, and show it in the Django Rest Framework.
But the "SELECT" part of the query is not working, and it shows whatever the serializer has in "fields" and thus the JOIN is also not working.
serializers.py:
class UserTestSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = "__all__"
views.py:
class UserTestQuery(viewsets.ModelViewSet):
queryset = User.objects.raw('SELECT * ' +
'FROM users_user ' +
'INNER JOIN sysadmin_works_as ON users_user.user_id = sysadmin_works_as.employee_id;')
serializer_class = UserTestSerializer
I want to show a join in the API with these 3 models, so I must use raw SQL. Why is it not working?
And the models I'm using are:
class User(AbstractUser):
first_name = None
last_name = None
username = None
user_id = models.AutoField(primary_key=True)
email = models.EmailField(_('email address'), unique=True)
national_id_number = models.CharField(max_length=30)
f_name = models.CharField(max_length=100)
l_name = models.CharField(max_length=100)
star_count = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True,null=True)
is_superuser = models.BooleanField(default = False)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
updated_at = models.DateTimeField(auto_now=True,null=True)
deleted_at = models.DateTimeField(blank = True, null=True)
date_joined = models.DateTimeField(auto_now_add=True,null=True)
app_role = models.ForeignKey(App_roles,related_name='employee',on_delete=models.SET_NULL,blank=True,null=True) #Un Rol_de_Aplicacion le pertenece a muchos usuar
class Works_as(models.Model):
work_id = models.AutoField(primary_key=True)
started_at = models.DateTimeField(auto_now_add=True)
updates_at = models.DateTimeField(auto_now=True)
r_created_at = models.DateTimeField(auto_now_add=True)
r_updated_at = models.DateTimeField(auto_now=True)
r_deleted_at = models.DateTimeField(auto_now=False,blank=True,null=True)
employee = models.ForeignKey(User,related_name='works_as',on_delete=models.SET_NULL,blank=True,null=True)
position = models.ForeignKey(Position,related_name='works_as',on_delete=models.SET_NULL,blank=True,null=True)
class Position(models.Model):
position_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
description = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
deleted_at = models.DateTimeField(blank=True,null=True)
upper_position = models.ForeignKey('self',on_delete=models.SET_NULL,blank=True,null=True)
department = models.ForeignKey(Department,related_name='positions',on_delete=models.SET_NULL,blank=True,null=True)
hierarchy_level = models.OneToOneField(Employee_Hierarchy,related_name='position',on_delete=models.SET_NULL,blank=True,null=True)