I tried to create a new Comment based on these models :
class Answer(models.Model):
answer = models.TextField()
author = models.ForeignKey(CustomUser, on_delete = models.CASCADE,
related_name="written_answers")
question = models.ForeignKey(Question, on_delete = models.CASCADE, related_name="answers")
upvoters = models.ManyToManyField(CustomUser, related_name="upvoted_answers")
created_at = models.DateTimeField(auto_now_add = True, blank = True)
updated_at = models.DateTimeField(blank = True, null=True)
def __str__(self):
return str(self.id)
class Comment(models.Model):
comment = models.CharField(max_length = 200)
author = models.ForeignKey(CustomUser, on_delete = models.CASCADE,
related_name = "written_comments")
answer = models.ForeignKey(Answer, on_delete = models.CASCADE, related_name="comments")
upvoters = models.ManyToManyField(CustomUser, related_name="upvoted_comments")
parent_comment = models.ForeignKey("self", on_delete = models.CASCADE,
related_name="next_in_thread", null=True, blank=False)
created_at = models.DateTimeField(auto_now_add = True, blank = True)
updated_at = models.DateTimeField(null=True, blank = True)
class Meta:
ordering = ('created_at', )
But I get the following error : no such table : main.core_answer__old
What did I do wrong? I tried to delete the SQLite table and the migrations and start over, but this error still persists. Please help.
Edit :
I'm using a populating script after migrating, which creates Questions and Answers, if that makes a difference.
core/models.py
from django.db import models
from users.models import CustomUser
class Genre(models.Model):
name = models.CharField(max_length=84)
subscribers = models.ManyToManyField(CustomUser, related_name="subscribed_genres")
def __str__(self):
return self.name
class Topic(models.Model):
name = models.CharField(max_length=84)
followers = models.ManyToManyField(CustomUser, related_name="followed_topics")
def __str__(self):
return "#" + self.name
class Question(models.Model):
question = models.CharField(max_length = 128, blank = False)
asker = models.ForeignKey(CustomUser, on_delete = models.CASCADE,
related_name="asked_questions")
requested = models.ManyToManyField(CustomUser, related_name="answer_requests")
genres = models.ManyToManyField(Genre, related_name = "questions")
followers = models.ManyToManyField(CustomUser, related_name="followed_questions")
topics = models.ManyToManyField(Topic, related_name="questions")
url = models.CharField(max_length = 150, unique=True)
created_at = models.DateTimeField(auto_now_add = True, blank = True)
updated_at = models.DateTimeField(null=True, blank = True)
class Meta:
ordering = ('-created_at', )
def __str__(self):
return self.question
class Answer(models.Model):
answer = models.TextField()
author = models.ForeignKey(CustomUser, on_delete = models.CASCADE,
related_name="written_answers")
question = models.ForeignKey(Question, on_delete = models.CASCADE, related_name="answers")
upvoters = models.ManyToManyField(CustomUser, related_name="upvoted_answers")
created_at = models.DateTimeField(auto_now_add = True, blank = True)
updated_at = models.DateTimeField(blank = True, null=True)
def __str__(self):
return str(self.id)
class Comment(models.Model):
comment = models.CharField(max_length = 200)
author = models.ForeignKey(CustomUser, on_delete = models.CASCADE,
related_name = "written_comments")
answer = models.ForeignKey(Answer, on_delete = models.CASCADE, related_name="replied_comments")
upvoters = models.ManyToManyField(CustomUser, related_name="upvoted_comments")
parent_comment = models.ForeignKey("self", on_delete = models.CASCADE,
related_name="next_in_thread", null=True, blank=False)
created_at = models.DateTimeField(auto_now_add = True, blank = True)
updated_at = models.DateTimeField(null=True, blank = True)
class Meta:
ordering = ('created_at', )
[RESOLVED] : Upgraded from Django==2.1 to Django==2.2
Related
I am importing Profile from profiles.models into meta.models, but showing the subject error. Can't find cutom solution, even though there are similar problems with different solutions out there but not working in my case.
Here is my profiles.models
from django.db import models
from django.contrib.auth.models import User
from meta.models import Designation
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, help_text = 'Foreign Key From User')
avatar = models.ImageField(upload_to='avatars', default='no_picture.png')
designation = models.ForeignKey(Designation, on_delete = models.CASCADE, null=True)
def __str__(self):
return str(self.user)
Here is my meta.models, where i am importing from profiles.models
from django.db import models
from profiles.models import Profile
class Designation(models.Model):
DesignationName = models.CharField(max_length = 20, blank=True,null= True)
DesignationScale = models.PositiveIntegerField()
def __str__(self):
return str(self.DesignationName)
class DutyPlaceSensitivity(models.Model):
sensitivity = models.CharField(max_length = 12, blank=True, null = True)
def __str__(self):
return str(self.sensitivity)
class DutyPlaces(models.Model):
DutyPlaceName = models.CharField(max_length =20, blank = True, null = True)
sensitivity = models.ForeignKey(DutyPlaceSensitivity, on_delete=models.CASCADE)
class ActingAs(models.Model):
acting_as_title = models.CharField(max_length = 12)
def __str__(self):
return str(self.acting_as_title)
class PlaceOfPosting(models.Model):
UserProfile = models.OneToOneField(Profile, on_delete=models.CASCADE)
acting_as = models.ForeignKey(ActingAs, on_delete = models.CASCADE)
def __str__(self):
return f"{self.UserProfile} - {self.acting_as}"
class TaskType(models.Model):
taskTypeName = models.CharField(max_length=20)
taskDescription = models.TextField(null = True, blank=True)
def __str__(self):
return str(self.taskTypeName)
class TaskPriority(models.Model):
priority_title = models.CharField(max_length = 12)
def __str__(self):
return str(self.priority_title)
class Tasks(models.Model):
task_name = models.CharField(max_length=120)
task_description = models.TextField()
task_type = models.ForeignKey(TaskType, on_delete=models.CASCADE)
assign_by = models.ManyToManyField(Profile, on_delete = models.CASCADE)
assign_to = models.ManyToManyField(Profile, on_delete = models.CASCADE)
task_priority = models.ForeignKey(TaskPriority, on_delete = models.CASCADE)
#time_stamp = models.DateField()
created = models.DateTimeField(auto_add_now = True)
updated = models.DateTimeField(auto_add = True)
def __str__(self):
return f"{self.task_name} --{self.assign_by}"
To summarize the issues:
1/ To avoid cicular imports, you can use strings to declare foreign key target model, syntax: "app.Model".
class PlaceOfPosting(models.Model):
UserProfile = models.OneToOneField("profiles.Profile", on_delete=models.CASCADE)
2/ On_delete is not available on ManyToManyField since Django will handle the intermediate table for you.
3/ When a model has multiple FK or M2M on the same second model, related_name must be defined (https://docs.djangoproject.com/en/4.1/ref/models/fields/#django.db.models.ForeignKey.related_name)
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)
class Assignatura(models.Model):
"""docstring for Assignatura"""
nom = models.CharField(max_length = 40)
codi = models.IntegerField()
any_academic = models.CharField(max_length = 7)
class Matricula(models.Model):
"""docstring for Matricula"""
nia_alumne = models.ForeignKey(Alumne, null = False, on_delete=models.CASCADE, verbose_name = 'Nom alumfne')
codi_assignatura = models.ForeignKey(Assignatura, null = False, on_delete=models.CASCADE)
any_academic = models.CharField(max_length = 7)
image = models.ImageField(upload_to="matriculas", null=True)
i Want that codi_assignatura gets only codi from Assignatura
You can make the code field of the Assignatura unique:
class Assignatura(models.Model):
"""docstring for Assignatura"""
nom = models.CharField(max_length=40)
codi = models.IntegerField(unique=True)
any_academic = models.CharField(max_length=7)
If the target field is unique, then you can specify a to_field=… parameter [Django-doc] in the ForeignKey:
class Matricula(models.Model):
"""docstring for Matricula"""
nia_alumne = models.ForeignKey(Alumne, null=False, on_delete=models.CASCADE, verbose_name='Nom alumfne')
codi_assignatura = models.ForeignKey(Assignatura, to_field='codi', null=False, on_delete=models.CASCADE)
any_academic = models.CharField(max_length=7)
image = models.ImageField(upload_to="matriculas", null=True)
Now the codi_assignatura_id field will store the code of the Assignatura to which it is referring.
I looked at a ton of these issues on stack overflow, but none of the solutions seemed to help me. I've tried Null=True and Blank=True as well as default=None and they all give errors. Anyone have any ideas? Thanks so much!
The error I'm getting is this:
NOT NULL constraint failed: first_app_trip.messages_id
My models:
class Trip(models.Model):
title = models.CharField(max_length = 50)
destination = models.CharField(max_length = 255)
description = models.TextField()
start_date = models.DateField(auto_now_add=False)
end_date = models.DateField(auto_now_add=False)
creator = models.ForeignKey(User, related_name="created_trips")
participants = models.ManyToManyField(User, related_name="joined_trips", default=None)
messages = models.ForeignKey(Message, related_name="messages", default=None )
notes = models.ForeignKey(Note, related_name="notes", default=None)
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now_add = True)
class Message(models.Model):
content = models.TextField()
author = models.ForeignKey(User, related_name="author")
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now_add = True)
class Note(models.Model):
content = models.CharField(max_length=45)
user = models.ForeignKey(User, related_name="notes")
My Views:
def create(request):
user = current_user(request)
print user.id
return render(request, 'first_app/create_trip.html')
def add(request):
user = current_user(request)
print user
trip = Trip.objects.create(
title = request.POST.get('title'),
destination = request.POST.get('destination'),
description = request.POST.get('description'),
start_date = request.POST.get('start_date'),
end_date = request.POST.get('end_date'),
creator = user
)
print trip
return redirect('/user_profile')
Python case sensitive
try it
class Trip(models.Model):
messages = models.ForeignKey(Message, related_name="messages", null=True, blank=True )
# in this line case sensitive ^^^^^^^^^^^^^^^^^^^
next:
./manage.py makemigrations first_app
./manage.py migrate first_app
after it try your action
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.