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
Related
I want to make the string representation of a field show data based on a JOIN, for instance:
For Penciler - I want the string representation to resolve to
John Doe (DC) - But the publisher value in that class is a Foreign Key - How do I reference the publisherName?
from django.db import models
class Series(models.Model):
seriesId = models.AutoField(primary_key=True)
series_name = models.CharField(max_length=300)
publisher = models.ForeignKey('Publisher', on_delete = models.PROTECT)
first_published = models.DateField()
last_published = models.DateField()
discontinued = models.BooleanField(default=False)
def __str__(self):
return f'{self.series_name} - {self.publisher} ({self.first_published - self.last_published})'
class Meta:
ordering = ['publication_year','title']
class Publisher(models.Model):
publisherId = models.AutoField(primary_key=True)
publisherName = models.CharField(max_length=250, null=False)
def __self__(self):
return self.publisherName
class Penciler(models.Model):
pencilerID = models.AutoField(primary_key=True)
pencilerName = models.CharField(max_length=200)
publisher = models.ForeignKey('Publisher', on_delete= models.PROTECT)
def __str__(self):
return self.pencilerName (self.publisher)
You can access the related Publisher instance through the ForeignKey field and get the publisherName in the __str__() method so:
def __str__(self):
publisher_name = self.publisher.publisherName
return f'{self.pencilerName} ({publisher_name})'
Additionally, I'd recommend you to use string formatting, such as using f-strings.
It is as simple as that:
def __str__(self):
return f"{self.pencilerName} ({self.publisher})"
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
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 to create a view which returns me the posts of a particular owner/author
This error in coming from view bellow. I know this is a simple thing that I am missing. Please help me on this: (marlm is the ID I created to test)
def view_by_owner(request):
user = request.user.username
posts_owner = Post.objects.filter(owner=user)
return render_to_response('view_post.html',{'view_owner':posts_owner})
Models:
from django.db import models
from django.db.models import permalink
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
datposted = models.DateTimeField('date posted')
category = models.ForeignKey('Category')
owner = models.ForeignKey('UserProfile')
def __str__(self):
return '%s' % self.title
class Category(models.Model):
title = models.CharField(max_length=100)
def __str__(self):
return self.title
class UserProfile(models.Model):
# This line is required. Links UserProfile to a User model instance.
user = models.OneToOneField(User)
# The additional attributes we wish to include.
website = models.URLField(blank=True)
picture = models.ImageField(upload_to='profile_images', null=True)
# Override the __unicode__() method to return out something
def __unicode__(self):
return self.user.username
class Logout(User):
force_logout_date = models.DateTimeField(null=True, blank=True)
The problem is that owner is a foreign key to User, not the value of the user name. To lookup by that, you will need to span that relationship, like so:
posts_owner = Post.objects.filter(owner__user__username=user)
Or, more simply, you could do this:
posts_owner = Post.objects.filter(owner__user=request.user)