Django filter from another model - python

In models.py I have following models:
class Project(models.Model):
project_name = models.CharField(max_length=255, unique=True, blank=False)
def __str__(self):
return str(self.project_name)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
role = models.CharField(choices=ROLE_CHOICES, max_length=255, default='Agent')
town = models.CharField(max_length=100)
project = models.ManyToManyField(Project)
def __str__(self):
return str('Advanced user informations')
class News(models.Model):
title = models.CharField(max_length=255, blank=False)
content = HTMLField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
In my views.py I have:
def news(request):
news_list = News.objects.all().order_by('-id')
paginator = Paginator(news_list, 5)
page = request.GET.get('page')
news = paginator.get_page(page)
return render(request, 'news.html', {'news': news})
Now I want to achieve that a User can only see news for a project he participates.
Something like:
News.objects.filter(News with a project that the User is linked to)
But I am not sure what could be a valid way to solve this. Maybe someone has a tip?

What about this,
News.objects.filter(project__in=request.user.profile.project.all())

This should do it:
News.objects.filter(project__profile_set__user=request.user)

Related

many to many field error __call__() missing 1 required keyword-only argument: 'manager'

error image
I'm using the model and I keep running into problems with many to many. At first, I made it without giving an id value, but it seems that the id value is not entered, so when I put the id value directly, the same problem as above occurs. But in the Post model below, the same form of likes is used. Why?
from django.db import models
# from django.contrib.auth.models import User
from django.conf import settings
# from server.apps.user.models import Profile
# Create your models here.
class Clothes(models.Model):
CATEGORYS =[
(0, '상의'), #상의
(1, '하의'), #하의
(2, '아우터'), #아우터
(3, '신발'), #신발
(4, '악세사리'), #악세사리
]
category = models.IntegerField(default=0,choices=CATEGORYS)
id = models.IntegerField(primary_key=True)
img = models.ImageField(upload_to='main/images/clothes/%Y/%m/%d')
save = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='Pickitems', blank=True)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
buying = models.TextField(null=True, blank=True)
def __str__(self):
return f'{self.id}: {self.category}'
#pk가 존재하지 않는것 같음.
# class SavePeople(models.Model):
class Post(models.Model):
main_img = models.ImageField(upload_to='main/images/post/%Y/%m/%d')
title = models.CharField(max_length=100)
content = models.TextField()
private = models.BooleanField(default=False)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
clothes = models.ManyToManyField(Clothes,related_name='Clothes')
likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='Likes', blank=True)
def __str__(self):
return f'{self.pk}: {self.title}'
def get_absolute_url(self):
return f'/community/'
#이거 나중에 detail page로 바꿔주세요
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
content = models.TextField()
create_date = models.DateTimeField(auto_now_add=True)
update_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'({self.author}) {self.post.title} : {self.content}'
class Commu(models.Model):
COMMU_CHOICES = [
('buying', 'buying'), #공동구매
('openrun', 'openrun'), #오픈런
('question', 'question'), #고민방
]
category = models.CharField(max_length=20, choices=COMMU_CHOICES)
img = models.ImageField(upload_to='main/images/commu/%Y/%m/%d', null=True, blank=True)
title = models.CharField(max_length=100)
content = models.TextField()
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
def __str__(self):
return f'{self.pk}: {self.title}'
def get_absolute_url(self):
return f'/community/commu'
I added the code saves= models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='Save', blank=True) to the Clothes model to make a save of Clothes in the same way as the likes of the Post model, but an error like the attached picture is displayed. occurred. When I searched, it seemed that the pk value did not exist.
The issue is the id field that you explicitly provided, Django itself creates an id field as a primary key for each model if you don't specify one. So, it is not necessary to add it to the model. Kindly remove it through the Clothes model and run migration commands.
And it doesn't give in case of likes since there is no extra field id in Post model unlike that of Clothes.
Note: Models in Django doesn't require s to be added as suffix, as it is automatically done, so you may change Clothes to Cloth.

Way to Filter by DB Field in Django using Class Views

I tried to search for answers, but after a few days, I'm here asking:
I'm a beginner, making a todo list app - expanding on a tutorial I followed. Currently, it's filtering by user, which is fine, but I also want to filter by a field in the DB (list).
Models:
class ToDoList(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
title = models.CharField(max_length=200)
description = models.CharField(max_length=200)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class Meta:
ordering = ['created']
class Task(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
title = models.CharField(max_length=200)
description = models.TextField(null=True, blank=True)
complete = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
list = models.ForeignKey(ToDoList, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Meta:
ordering = ['complete']
View I'm trying to change:
class TaskList(LoginRequiredMixin, ListView):
model = Task
context_object_name = "tasks"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['tasks'] = context['tasks'].filter(user=self.request.user)
context['count'] = context['tasks'].filter(complete=False).count
search_input = self.request.GET.get('search-area') or ''
if search_input:
context['tasks'] = context['tasks'].filter(title__startswith=search_input)
context['search_input'] = search_input
return context
Also, is there a way to access the list variable in the html component, like here?
url:
path('tasks/<list>/create', TaskCreate.as_view(), name="task-create"),
html:
← Back

Django: How do I check if a User has already read/seen an article?

I am building a web-application for my senior design project with Python and Django. I have a user model that is able to read/write articles to display on the website. I have some tasks I want to accomplish.
I want to make it so that if an article is accessed (read) by a user, it is indicated for only that user that the article has been previously accessed. If I were to log into a brand new user account, the same article wouldn't be indicated as "accessed" for the new account.
How would I be able to present on the front-end side that the article has been viewed by the user logged in? (ie: make the article title bolded or a different color to indicate its been already visited)
Below are my models and views:
User model
class User(AbstractBaseUser, PermissionsMixin):
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30, blank=True)
email = models.EmailField(unique=True, max_length=255, blank=False)
university = models.CharField(max_length=200, null=True, blank=True)
newsletter_subscriber = models.BooleanField(default=False)
is_email_verified = models.BooleanField(default=False)
is_staff = models.BooleanField(
default=False,
help_text=(
'Designates whether the user can log into '
'this admin site.'
),
)
is_active = models.BooleanField(
default=True,
help_text=(
'Designates whether this user should be '
'treated as active. Unselect this instead '
'of deleting accounts.'
),
)
date_joined = models.DateTimeField(default=timezone.now)
objects = UserManager()
USERNAME_FIELD = 'email'
def __str__(self):
return self.email
Article model
class Article(models.Model):
user = models.ForeignKey(
User, on_delete=models.DO_NOTHING, null=True, blank=True)
title = models.CharField(max_length=200, null=True, blank=False)
author = models.CharField(max_length=200, null=True, blank=False)
year = models.CharField(max_length=200, null=True, blank=False)
journal = models.CharField(max_length=200, null=True, blank=False)
description = models.TextField(null=True, blank=True)
URL = models.CharField(max_length=200, null=True, blank=False)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class MetaData:
ordering = ['-created']
Article detail view
class ArticleDetail(LoginRequiredMixin, DetailView):
model = Article
context_object_name = 'articles'
template_name = 'home/article_detail.html'
Thank you!
You could create an extra table.
class ArticleSeenRecord(models.Model):
user = models.ForeignKey("django.contrib.auth.models.User", on_delete=models.CASCADE)
article = models.ForeignKey(Article, on_delete=models.CASCADE)
And then in your article view, create a new record when one doesn't exist, for that article combined with the authenticated user.
class ArticleDetail(LoginRequiredMixin, DetailView):
model = Article
context_object_name = 'articles'
template_name = 'home/article_detail.html'
def get_object(self, queryset=None):
obj = super().get_object(queryset)
record, created = ArticleSeenRecord.objects.get_or_create(user=self.request.user, article=obj)
return obj
class Article(models.Model):
...
def seen_by_user(self, user):
return self.atricleseenrecord_set.objects.filter(user=user).exists()
I added the extra function here. You will also need to add a template tag which you can ideally copy from this example
#register.simple_tag
def article_seen_by_user(article, user):
return article.seen_by_user(user)
For further guidance on how to use and register custom template tags, please refer to this page of the documentation:
https://docs.djangoproject.com/en/4.0/howto/custom-template-tags/
Specifically this section:
https://docs.djangoproject.com/en/4.0/howto/custom-template-tags/#django.template.Library.simple_tag

model.objects.all() doesn't find anything when foreign key in model

when I load the website i get this error
my models.py file looks like:
# Create your models here.
class Information(models.Model):
id = models.CharField(max_length=200, primary_key=True)
title = models.CharField(max_length=500)
link = models.CharField(max_length=100)
summary = models.CharField(max_length=1000)
published = models.CharField(max_length = 100)
def __str__(self):
return self.title
class Search(models.Model):
id = models.CharField(max_length=100, primary_key=True)
searched_titles = models.CharField(max_length=100)
searched_topics = models.CharField(max_length=100)
number_found_articles = models.IntegerField()
def __str__(self):
return self.id
class Article_search(models.Model):
id = models.AutoField(primary_key=True)
found_articles = models.ForeignKey(
Information, on_delete=models.CASCADE)
search_details = models.ForeignKey(
Search, on_delete=models.CASCADE)
def __str__(self):
return self.id
in my view.py file:
def show_articles_with_this_filter_id(request):
all = Article_search.objects.all()
print(all)
return render(request, 'show_article.html')
when I get to the print statement I get the error shown in the picture:
Unknown column 'database_article_search.found_articles_id' in 'field list'
why is the part _id pasted behind found_articles?
this is the error i get when i remove the id from article_search
id error when printing Article_search.objects.all()
# Create your models here.
class Information(models.Model):
title = models.CharField(max_length=500)
link = models.CharField(max_length=100)
summary = models.CharField(max_length=1000)
published = models.CharField(max_length = 100)
def __str__(self):
return self.title
class Search(models.Model):
searched_titles = models.CharField(max_length=100)
searched_topics = models.CharField(max_length=100)
number_found_articles = models.IntegerField()
def __str__(self):
return self.searched_titles
class Article_search(models.Model):
found_articles = models.ForeignKey(
Information, on_delete=models.CASCADE)
search_details = models.ForeignKey(
Search, on_delete=models.CASCADE)
Make model like this and then run two commands
1.python manage.py makemigrations and then 2.python manage.py migrate
"In your views.py file"
def show_articles_with_this_filter_id(request,id):
all = Article_search.objects.filter(id=id)
print(all)
return render(request, 'show_article.html')

Django model field is showing in django admin

In my django admin model(Profile), I am not able to see my StudentID field declared in django model.
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
StudentID = models.AutoField(primary_key=True, verbose_name='SID')
Branch = models.CharField(max_length=255, choices=Departments, default="CSE")
YearOfStudy = models.IntegerField(default=1)
ContactNumber = PhoneField(help_text='Contact phone number')
image = models.ImageField(default='default.jpeg', upload_to='profile_pics', blank=True)
parentsContactNumber = PhoneField(help_text="Parent's phone number", blank=True)
def __str__(self):
return f'{self.user.username} Profile'
To reflect your StudentID in the admin page you must return it in the str function
def __str__(self):
return self.StudentID

Categories

Resources