I have a Django Rest Framework project, users can post,comment any post and like any post. I can't figure it out the logic in models.py
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=100)
body = models.CharField(max_length=100)
post_author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='posts')
def __str__(self):
return self.title
class Comment(models.Model):
body=models.CharField(max_length=100)
commet_post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments')
comment_author = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.body
class Like(models.Model):
like_post = models.ForeignKey(Post,on_delete=models.CASCADE)
like_author=models.ForeignKey(User,on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
You could make two endpoints for like: 1) for create & 2) for delete. Whenever someone clicks on the like button, it will hit the create endpoint and create a Like object. When someone clicks on unlike, it will hit the delete endpoint and delete the object. Like model will have a one-to-one relationship with User and Post model. You can count likes by a query such as: Like.objects.filter(like_post=post.id).aggregate(Count('pk'))
Related
I just started with django and I want to make a spotify clone. I want to make it so then when you click on an album it shows the songs for that album.
this is my models.py
from django.db import models
class album(models.Model):
title = models.CharField(max_length=50)
artist = models.IntegerField()
genre = models.CharField(max_length=20)
id = models.AutoField(primary_key=True)
artwork = models.CharField(max_length=1000)
class artist(models.Model):
name = models.CharField(max_length=50)
id = models.AutoField(primary_key=True)
class song(models.Model):
name = models.CharField(max_length=60)
artist = models.IntegerField()
album = models.IntegerField()
id = models.AutoField(primary_key=True)
This is my views.py
from django.shortcuts import render
from .models import album, song
def home(request):
context = {
'albums': album.objects.all(),
}
return render(request, 'main/index.html', context)
For that particular album for which the button is clicked, or all albums, please clarify your question.
Well, it cane achieved through frontend using dropdowns and much more components, or simply redirecting to another page which will show relevant albums.
Through django, if you need to see all albums so you are doing correct.
But if you see a particular album by clicking, so you have to pass that album's id or name or you can pass anything which is unique.
urls.py
path('particular-album/<int:id>/,views.particular_album,name='particular')
Html file
{% for album in albums %}
see particular album
Views.py
def particular_album(req,id):
one_album=album.objects.get(id=id)
return render(req,"main/particular.html",{'one':one_album})
Then in your template file without running the loop you can get all the properties of this object.
If there are more than one objects, so you can use album.objects.filter(field_name=variable) same as like one object, but it gives you more than one, and the variable you have to pass must not be associated with unique constraint.So, it gives you all objects which belong to particular category.Then, you have to run loop in your template file.
I have a model called listings and I want staff users to only be able to view, edit, delete listings in the admin panel that they created. Currently staff users can view edit and delete all of the listings
here is my listings/admin.py
from django.contrib import admin
from .models import Listing
class ListingAdmin(admin.ModelAdmin):
list_display =('id','Full_Name','Is_Published','Town_Or_City','District','Region','List_Date')
list_display_links = ('id','Full_Name')
list_editable = ('Is_Published',)
search_fields = ('Full_Name','Town_Or_City','District','Region',)
admin.site.register(Listing, ListingAdmin)
here is my listings/models.py
from django.db import models
from datetime import datetime
from FuneralHomes.models import FuneralHome
class Listing(models.Model):
index = models.ForeignKey(index, on_delete=models.DO_NOTHING,blank=True)
Full_Name = models.CharField(max_length=200)
First_Name = models.CharField(max_length=200)
Last_Name = models.CharField(max_length=200)
Nee = models.CharField(max_length=200, blank=True)
Town_Or_City = models.CharField(max_length=200)
District = models.CharField(max_length=200, blank=True)
Region = models.CharField(max_length=200)
List_Date = models.DateField(max_length=200)
Photo = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True)
Is_Published = models.BooleanField(default=True)
List_Date = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return self.Full_Name
The admin panel really isn't the place for things like this (as explained in the first paragraph of the Django documentation).
A quick a dirty way of accomplishing what you're trying to do is probably overriding the delete method for this model to check if the user created it. For only listing the user's posts you could utilize the Manager class. Finally, to handle editing, you would have to override the save method to see if it already exists and if the user created it.
you can override get_queryset function and just filter listings related to that user , in this case user can only see his listings .
class ListingAdmin(admin.ModelAdmin):
def get_queryset (self, request):
return Listing.objects.filter(listing_user = request.user)
I am trying to learn Django by creating something similar to Reddit. I have models for Post and User, and now I want to create one for "Community". I have looked at this post:
How to store an array of users in django?
However, I am unsure if the ManyToMany relationship is right here (perhaps it is).
I want the Community Model to contain Posts and Users registered with the Community. Each Community can have many posts, and each user can belong to multiple communities. When a Community is deleted, only delete the posts in that community, not the users. Similarly, when a User is deleted or a Post deleted, just remove that aspect from the Community.
If anyone has done this before or knows of a resource to learn this please let me know.
Here is my Post model so far. Note my Communities are called "Bands". Thus all of my references to "Community" will be "Bands" in my project.
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
# each class is its own table in the data
class Post(models.Model):
# each attribute is a different field in the data
title = models.CharField(max_length=100)
content = models.TextField()
# pass in the function as the default val, but do NOT execute yet!
date_posted = models.DateTimeField(default=timezone.now)
# foreign keys link two tables together
# on delete of User, we delete the user's post as well
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
Here is my Band model:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from home.models import Post
class Band(models.Model):
name = models.CharField(max_length = 100)
date_created = models.DateTimeField(default=timezone.now)
users = (settings.AUTH_USER_MODEL)
def __str__(self):
return "{self.name}"
I have two models, one for uploaded files and one for comments. I now want to display the comments in the Admin view of each uploaded file. So for example, if I upload a file TestFile1, once I click on it in the
Uploaded view in Django admin, I want to have all of the comments associated with that file. Is this possible?
class Uploaded(models.Model):
objects: models.Manager()
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="users")
file = models.FileField(upload_to=user_directory_path)
def __str__(self):
return f"{self.description} {self.file}"
class Comment(models.Model):
objects: models.Manager()
file = models.ForeignKey('Uploaded', on_delete=models.CASCADE, related_name='comments')
text = models.TextField()
def __str__(self):
return self.text
Yes, what you need is to write InlineModelAdmin for your models.
In your case, that would be something like:
from django.contrib import admin
class CommentInlineAdmin(admin.TabularInline):
model = Comment
class UploadedAdmin(admin.ModelAdmin):
inlines = [CommentInlineAdmin]
admin.register(Uploaded, UploadedAdmin)
i have two models
class Reporter(models.Model):
full_name = models.CharField(max_length=70)
# On Python 3: def __str__(self):
def __unicode__(self):
return self.full_name
class Article(models.Model):
pub_date = models.DateField()
headline = models.CharField(max_length=200)
content = models.TextField()
reporter = models.ForeignKey(Reporter)
now in the admin site i want to register the reporter's model and then when it is clicked the Article model objects can be added from within that reporter's model .. is it possible ?? if yes how to accomplish this ??
You need inline model admin. In your admin.py, add the following:
from django.contrib import admin
from .models import Article, Reporter
class ArticleInline(admin.TabularInline):
model = Article
class ReporterAdmin(admin.ModelAdmin):
inlines = [
ArticleInline,
]
admin.site.register(Reporter, ReporterAdmin)