I am trying to save my model. But when I try to save my model I throws the following error
TypeError at /admin/user/teacher/add/
can only concatenate str (not "ManyRelatedManager") to str
My models.py file looks like this
class Class(models.Model):
Class = models.CharField(max_length=50)
section_choices = (('A','A'),('B','B'),('C','C'),('D','D'),('E','E'))
Section = models.CharField(max_length=100, choices=section_choices)
def __str__(self):
return self.Class + "," + self.Section
class Subject(models.Model):
subject = models.CharField(max_length=100)
def __str__(self):
return self.subject
class Teacher(models.Model):
User = models.ForeignKey(User, on_delete=models.CASCADE)
Subject = models.ManyToManyField(Subject)
Name = models.CharField(max_length=50)
Profile = models.ImageField(upload_to = upload_teacher_profile_to, default =
'defaults/teacher_profile.png')
Class = models.ManyToManyField(Class)
Number = models.IntegerField(blank=True)
is_banned = models.BooleanField(default=False)
def __str__(self):
return self.Name + "of" + self.Class
Updated your Teacher Model def __str__(self) function to
def __str__(self):
return f"{self.Name} of {[class for class in self.Class.all()]}"
Class is a ManyToManyField in the Teacher Model, ManyToManyFields can contain many objects, hence you cannot use self.Class
You can learn more about ManyToManyField here
Try with(in class Teacher):
def __str__(self):
output=""
for x in self.Class.all():
output=output+' | '+str(x)
return output
Related
models.py:
class Post(models.Model):
title = models.CharField(max_length=255, verbose_name="ady")
text = RichTextField(verbose_name="text")
tagList = models.ManyToManyField(Tag, verbose_name="taglar", related_query_name="tagList")
image = models.ImageField(upload_to="postImage/", verbose_name="surat")
seen = models.ManyToManyField(UserId,verbose_name="görülen sany", blank=True, related_name="gorulen")
like = models.ManyToManyField(UserId,verbose_name="like sany", blank=True)
share = models.PositiveIntegerField(verbose_name="paýlaşylan sany", null=True, blank=True, default="0")
createdAt = models.DateTimeField(auto_now_add=True, verbose_name="goşulan güni")
class Meta:
verbose_name_plural="Makalalar"
# ordering = ("-createdAt",)
ordering = ["-hotness",]
def __str__(self):
return self.title
def likes(self):
return self.like.count()
likes.short_description = "Like sany"
likes.allow_tags = True
def seens(self):
return self.seen.count()
seens.short_description = "Görülen sany"
seens.allow_tags = True
#property
def hotness(self):
return self.likes() + self.seens() + self.share
How can I user hotness function value to ordering in meta class?
You can define a custom manager for the Post model and implement a custom queryset as:
class PostQuerySet(models.QuerySet):
def hotness_ordering(self):
return self.annotate(hotness=models.Count('like') + models.Count('seen') + models.F('share')).order_by('-hotness')
Then simply query as:
Post.objects.all()
This question is similar with others but it is a different one actually ! So, I have 3 models such as (I have deleted some unnecessary things for shorter code):
class Category(models.Model):
category_title = models.CharField(max_length=200)
category_content = models.TextField()
category_slug = models.CharField(max_length=200)
def __str__(self):
return self.category_title
class Classes(models.Model):
classes_title = models.CharField(max_length=200)
classes_content = models.TextField()
classes_category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT)
def __str__(self):
return self.classes_title
class Subjects(models.Model):
subject_title = models.CharField(max_length=200)
subject_content = models.TextField()
subject_class = models.ForeignKey(Classes, on_delete=models.SET_DEFAULT)
def __str__(self):
return self.subject_title
So let me give an example. I can have 2 categories and in those categories I can have "same named" classes. Lets think about maths is a class for both categories. When I want to add a new subject to maths I see 2 same named maths in admin page. So I want to know which one belongs to which category in admin page. So I can add my subject to right class.
class SubjectAdmin(admin.ModelAdmin):
fields = ('subject_title', 'subject_content', 'subject_class',)
So in this picture (Subjects = Konular) I am adding a new subject. I will have a foreign key to Class. However I have same name for classes that are coming from different categories. So in this dropdown how can I know which class belongs to which category ?
Try this...
class KonularAdmin(admin.ModelAdmin):
fields = ('subject_title', 'subject_content', 'subject_class', 'get_classes_category_title')
def get_classes_category_title(self, obj):
subject_object = Subjects.objects.get(id=obj.subject_class)
return str(subject_object.classes_category.category_title)
It returns the category title name
If I understood you correctly, This should work.
class Classes(models.Model):
classes_title = models.CharField(max_length=200)
classes_content = models.TextField()
classes_category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT)
def __str__(self):
return self.title
class Subjects(models.Model):
subject_title = models.CharField(max_length=200)
subject_content = models.TextField()
subject_class = models.ForeignKey(Classes, on_delete=models.SET_DEFAULT)
def __str__(self):
return f"{self.subject_title} - {str(self.subject_class)}"
You can use __str__() method to change the string representation of an object:
class Subjects(models.Model):
subject_title = models.CharField(max_length=200)
subject_content = models.TextField()
subject_class = models.ForeignKey(Classes, on_delete=models.SET_DEFAULT)
def __str__(self):
return f"{self.subject_title} - {self.subject_content} - {self.subject_class}"
# shorter version:
# return f"{self.subject_title[:10]} - {self.subject_content[:10]} - {self.subject_class[:10]}"
Check it with:
>>> print(Subjects.objects.first())
I am trying to create an instance in my app like this:
Views.py
new_quiz = Quiz.objects.create(owner=request.user, comments="Autogenerated", truck_type=truck_type_object,
truck_name=chosen_truck_object)
where chosen_truck_object is this:
chosen_truck_object = Truckdb.objects.filter(display_name=chosentruck)[0]
And Models.py
class Quiz(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='quizzes')
comments = models.TextField(max_length=256, blank=True)
truck_type = models.ForeignKey(truck_type, on_delete=models.CASCADE, related_name='trucks')
truck_name = models.ForeignKey(truck_name, on_delete=models.SET_NULL, null=True)
class truck_type(models.Model):
name = models.CharField(max_length=30)
color = models.CharField(max_length=7, default='#007bff')
def __str__ (self):
return self.name
class truck_name(models.Model):
truck_type = models.ForeignKey(truck_type, on_delete=models.CASCADE)
name = models.CharField(max_length=30)
def __str__ (self):
return self.name
How can I pass the truck_type and truck_name instance to the Quiz model in Quiz.objects.create ?
Firstly you need to follow the naming convention guidelines, so your models' name must be camelcase doc as like:
class TruckType(models.Model):
name = models.CharField(max_length=30)
color = models.CharField(max_length=7, default='#007bff')
def __str__ (self):
return self.name
class TruckName(models.Model):
truck_type = models.ForeignKey(TruckType, on_delete=models.CASCADE)
name = models.CharField(max_length=30)
def __str__ (self):
return self.name
And then please migrate your database and then for your problem you need to take TruckName object instead of Truckdb.
chosen_truck_object = TruckName.objects.filter(display_name=chosentruck)[0]
instead of filter use get method chosen_truck_object = TruckName.objects.get(display_name=chosentruck) it will save
I have a problem when I trying to run my unit tests.
Why does it give me that error message?
Code from tests.py:
class CourseTestCase(TestCase):
def create_category(name="English", imgpath="ImgPath"):
return Category.objects.create(name=name, imgpath=imgpath)
def setUp(self):
Course.objects.create(
name='English',
description='Sample text',
category_id=self.create_category().id,
logo='Logo'
)
def test_course_category(self):
english = Course.objects.get(name='English')
self.assertEqual(english.category_id, 1)
Models.py:
class Category(models.Model):
name = models.CharField(max_length=64)
imgpath = models.CharField(max_length=64)
def __str__(self):
return str(self.name)
class Course(models.Model):
name = models.CharField(max_length=64)
description = models.TextField()
category = models.ForeignKey(Category, on_delete=models.CASCADE, null=False)
logo = models.TextField()
def __str__(self):
return str(self.name)
ValueError: Cannot assign "'Category'": "Course.category" must be a "Category" instance.
try below code
class CourseTestCase(TestCase):
def setUp(self):
self.category = Category.objects.create(name="English", imgpath="ImgPath")
self.course = Course.objects.create(
name='English',
description='Sample text',
category=self.category,
logo='Logo'
)
def test_course_category(self):
english = Course.objects.get(name='English')
self.assertEqual(english.category_id, self.category.id)
Just change this:
category_id=self.create_category().id,
to this:
category=self.create_category(),
The error ValueError: Cannot assign "'Category'": "Course.category" must be a "Category" instance. is telling you that the attribute category are expecting a class instance of Category and not his id
In the django admin page, everything is just showing 'xxx object' and not the
name that i write in the model:
class categoria(models.Model):
nomeCategoria = models.CharField(max_length=50)
imagemCategoria = models.CharField(max_length=200)
def __str__(self):
return self.nomeCategoria
class post(models.Model):
tituloPost = models.CharField(max_length=200,default='tituloPost')
textoPost = models.TextField()
textoTagPost = models.TextField()
categoria = models.ForeignKey(categoria)
enviadoNewsletter = models.BooleanField(default=False)
def __str__(self):
return 'Post: ' + self.tituloPost
I'm using python 3.4
I also tried to put this code in admin.py:
class categoriaAdmin(admin.ModelAdmin):
list_display = ('nomeCategoria','imagemCategoria')
admin.site.register(categoria, categoriaAdmin)
but this only show the right name in the list.
I think the point of the str is to show the right field everywhere, or am I wrong?
I'm new in this , sorry about my english and hope someone can help.
str or better yet unicode need to be properly spaced over, so that the class has the method, not the module. Also, you should probably use titles for model classes (i.e. class Categoria)
class categoria(models.Model):
nomeCategoria = models.CharField(max_length=50)
imagemCategoria = models.CharField(max_length=200)
def __str__(self):
return self.nomeCategoria
class post(models.Model):
tituloPost = models.CharField(max_length=200,default='tituloPost')
textoPost = models.TextField()
textoTagPost = models.TextField()
categoria = models.ForeignKey(categoria)
enviadoNewsletter = models.BooleanField(default=False)
def __str__(self):
return 'Post: ' + self.tituloPost