Hi I'm a Django newbie writing my first application. I have a basic model:
from django.db import models
from django_extensions.db.fields import AutoSlugField
class Tag(models.Model):
name = models.CharField(max_length=100)
slug = AutoSlugField(populate_from='name', unique=True)
class Listings(models.Model):
listing = models.CharField(max_length=50)
description = models.CharField(max_length=500)
email = models.EmailField(max_length=75)
tag = models.ManyToManyField(Tag)
pub_date = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.listing
I've added a few tags from terminal but all are surfacing as Tag Object. How do I get the name of the tag to show?
Also, how would I enable the admin to add tags, instead of adding via terminal each time?
Thanks very much!
You were missing a unicode attribute in the Tag model
class Tag(models.Model):
name = models.CharField(max_length=100)
slug = AutoSlugField(populate_from='name', unique=True)
def __unicode__(self):
return "%s"% self.name
Also, Fix the indentation of your unicode block for Listings model
class Listings(models.Model):
listing = models.CharField(max_length=50)
description = models.CharField(max_length=500)
email = models.EmailField(max_length=75)
tag = models.ManyToManyField(Tag)
pub_date = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.listing
Related
I'm making a searchbar for a site I'm working on and I'm having trouble when I want to filter different fields from different models (related between them) Here are my models:
class Project(models.Model):
name = models.CharField(max_length=250)
objective = models.CharField(max_length=250)
description = models.TextField()
launching = models.CharField(max_length=100, null=True, blank=True)
image = models.ImageField(
upload_to='imgs/', null=True, blank=True)
image_thumbnail = models.ImageField(
upload_to='thumbnails/', null=True, blank=True)
slug = models.CharField(max_length=250)
class Meta:
db_table = 'project'
def __str__(self):
return self.name
class Institution(models.Model):
name = models.CharField(max_length=250)
project = models.ManyToManyField(Proyecto)
class Meta:
db_table = 'institution'
def __str__(self):
return self.name
And I want to be able to search by the name of the project or the institution, but my code only takes the institution's name.
def searchbar(request):
if request.method == 'GET':
search = request.GET.get('search')
post = Project.objects.all().filter(name__icontains=search, institution__name__icontains=search)
return render(request, 'searchbar.html', {'post': post, 'search': search})
How can I search for all the projects that match by its name OR the institution's name?
BTW, I'm using SQL, not sure if it's relevant, but I thought I should add that info.
You can .filter(…) [Django-doc] with Q objects [Django-doc]:
from django.db.models import Q
Project.objects.filter(Q(name__icontains=search) | Q(institution__name__icontains=search))
or you can work with the _connector parameter:
from django.db.models import Q
Project.objects.filter(
name__icontains=search,
institution__name__icontains=search,
_connector=Q.OR
)
I have start fresh with Django.
I am creating a blog and I need a hint now.
I want to add tags to my posts.
So I created a model for my tags:
class Tag(models.Model):
name = models.CharField(max_length=200, unique=True)
def __str__(self):
return self.name
This is my Post Model
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
updated_on = models.DateTimeField(auto_now= True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
What is the best way, that the user can select in the admin area tags for the post and more than one or create a new tag?
In the Post class, add a field ManyToMany
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
updated_on = models.DateTimeField(auto_now= True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
tag = models.ManyToManyField(Tag)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
You are looking for InlineModelAdmin particulary section regarding
Working with many-to-many models
something as following:
class TagInline(admin.TabularInline):
model = Post.tags.through
class PostAdmin(admin.ModelAdmin):
inlines = [
TagInline,
]
Also you are missing relationship on your model which should be ManyToMany
class Post(models.Model):
...
tags = models.ManyToManyField(Tag)
I've made a foreign key relationship with django User model, the forward lookup is working fine but when I try to backward is throwing this error:
'QuerySet' object has no attribute 'urlpost_set'
I have also tried the related name! Also note that the Catagory to PostUrl and PostUrl to Catagory is working just fine!
My models.py:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Catagory(models.Model):
title = models.CharField(max_length=15, unique=True)
created = models.DateField(auto_now_add=True)
updated = models.DateField(auto_now=True)
def __str__(self):
return self.title
class Meta:
verbose_name_plural = 'catagory'
class UrlPost(models.Model):
STATUS_CHOICES = (
('public', 'Public'),
('private', 'Private'),
)
profile = models.ForeignKey(User, related_name='user_post', on_delete=models.CASCADE)
catagory = models.ForeignKey(Catagory, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
url = models.URLField()
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='public')
note = models.TextField(blank=True)
created = models.DateField(auto_now_add=True)
updated = models.DateField(auto_now=True)
class Meta:
ordering = ['-created']
verbose_name_plural = 'url Post'
def __str__(self):
return self.title
You have set related_name='user_post' while defining ForeignKey relation between your User model and UrlPost.
You have to use .user_post.all() instead of .urlpost_set.all() in your queryset.
What I want to do is simply match the images to the department model through tags. How do I write a view for my department page to do this? I have looked everywhere but can't find the answer. Please help!
Models:
class Tag(models.Model):
tag_title = models.CharField(max_length=200)
slug = models.CharField(max_length=200)
def __str__(self):
return self.tag_title
class Image(models.Model):
image_url = models.CharField(max_length=200)
title = models.CharField(max_length=200)
tags = models.ManyToManyField(Tag, blank=True)
def __str__(self):
return self.title
class Department(models.Model):
page_title = models.CharField(max_length=200)
slug = models.CharField(max_length=200)
content = models.TextField()
tags = models.ManyToManyField(Tag, blank=True)
def __str__(self):
return self.page_title
Try this:
Image.objects.filter(tags__department=d) #where d is your deparment.
Something like this should work:
Given a Department object department_obj:
images = Image.objects.filter(tags__in=department_obj.tags.all())
I am new to Python and Django.
I am trying to build myself very simple blog application.
So I have this 2 models :
class Tag(models.Model):
name = models.CharField(max_length=250)
slug = models.SlugField(unique=True)
def __unicode__(self):
return self.name
class Blogpost(models.Model):
title = models.CharField(max_length=300)
content = tinymce_models.HTMLField()
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
tags = models.ManyToManyField(Tag)
def __unicode__(self):
return self.title
As you can see Blogpost can contain many Tags,
my question is how can I query Blogpost.objects.all() to get Blogposts list by specific Tag?
Thank you.
I think related manager is your answer
t = Tag.objects.get(name="Some tag")
t.blogpost_set.all()