Reporting in django - python

I need some advice on what to do. I am developing an app for a course at my university. The userstory I working on at the moment is: "As a user I want to be able to report films that doesn´t exist."
My thought was to have a report-button at my film_detail.html, where clicking this button would trigger the BooleanField in my model, and mark the film as reported. When clicking the report-button I was thinking on just having a pop-up window to confirm the reporting, and I believe I won´t need to create a complete new view for this(?).
Does anyone have any idea on how to do this (cause I´m kinda stuck), or maybe having a better idea?
**models.py**
class Film(models.Model):
title = models.CharField(max_length=100)
title_short = models.CharField(max_length=17, default=None, null=True)
plot = models.TextField()
poster = models.ImageField(default="default.png", upload_to="posters")
release_date = models.DateField(blank=True, null=True)
date_posted = models.DateTimeField(default=timezone.now)
reported = models.BooleanField("Is reported", default=False)
#class Admin:
# list_display = ("is_reported")
#def is_reported(self):
# return self.reported == True
#is_reported.BooleanField = False
**HTML**
{% extends "board/base.html" %}
{% block content %}
<article class="media content-section">
<img class="rounded-circle film-img" src="/media/{{object.poster}}">
<!-- Mulighet for å ha en "add review"-knapp på siden der hvor filmene vises. -->
<!-- <i class="material-icons right">rate_review</i>add review -->
<a onclick="myFunction()" class="waves-effect waves-light red darken-4 btn"><i class="material-icons right">report</i>report</a>
<script>
function myFunction() {
alert("Are you sure you want to report this film?");
}
</script>
<div class="media-body">
<h2 class="film-title">{{ object.title }}</h2>
<p class="film-plot">{{ object.plot }}</p>
</div>
</article>
{% endblock content %}

There are definitely different ways on implementing it. One way is to expose an API with a url like: films/report with PUT method. After getting confirmation from the user, you can easily send an Ajax request.

Related

how to show the field data of one app model on the other app template?

Well, I am creating a user profile where the user can see his all posts which he has been uploaded. But I don't understand one thing that how could I possibly grab the fields of Post model from Posts/models.py and show them on the template which I have created in another app (Profiles) templates.
The reason I am trying to access them on other app is that I want to show them in the userprofile.html template. Just like Facebook posts. And please tell me if you know that it is not possible with django?
posts/models.py :
class Post(models.Model):
username = models.ForeignKey(User, verbose_name=("user name"), on_delete=models.CASCADE)
description = models.CharField(('Description'),max_length=250)
title = models.CharField(('Content Title'), max_length=250)
create_date = models.DateTimeField(default = timezone.now)
image_data = models.ImageField(upload_to='User_Posts', height_field=None, width_field=None, max_length=None)
def __str__(self):
return self.title
profiles/views.py
from posts.model import Post
from django.views.generic import ListView
class UserPostListView(ListView):
model = Post
context_object_name = 'userpost_list'
template_name = 'profiles/userprofile.html'
def get_queryset(self):
user = get_object_or_404(User, username = self.kwargs.get('username'))
return Post.object.filter(username = user).order_by('-create_date')
profiles/templates/profiles/userprofile.html
<div class="jumbotron">
{% for post in userpost_list %}
<div class="post">
<h1>{{ posts.post.title }} <img src="" alt="not found" height="60" width="60" style="float:right ;border-radius: 20px;" ></h1>
<div class="date">
<p>
<!-- Published on: {{ object.author.post.create_date|date:"D M Y" }} -->
</p>
</div>
</div>
{% endfor %}
</div>
</div>
You can access any app from any other app. You just need to do the necessary model imports which you are doing. Looks like you just need to tweak your line of code in the template from:
<h1><a href="">{{ posts.post.title }}...
to:
<h1><a href="">{{ post.title }}...
and when you decide to use it.
<!-- Published on: {{ object.author.post.create_date|date:"D M Y" }} -->
to:
<!-- Published on: {{ post.create_date|date:"D M Y" }} -->
The reason is that your queryset is returning a dataset of the Post model. So you are already in it.
It just done by importing model from the app you want to use model to other app. And that it. This is python OOP(object oriented programming) concept.

why are comment objects not deleted from database although the view is triggered?

I try to remove comment so, I tried the first time by the class-based view then I hashed it to try the second way by normal function to know what's going on here. so, when I try to delete the comment by ID nothing does happen it's just directing me to the web page without deleting the comment so in this case the program runs but doesn't remove the object so, what is going on here?
Note: the posts and comments on the same page and slug field on that page are following by post not comment.
if the title of the post is: new title so, the slug will be new-title depending on the post
question_view.html
<div class="user-answer">
<div class="row">
<div class="col-xs-12">
{% for comment in my_question.comment_set.all %}
<div class="comments">
<div class="col-xs-0">
<div class="avatar">
<a href="{% url 'account:view_profile' comment.username %}">
<img class="img-circle img-thumbnail" style="width:50px; height: 50px;" src="{{ comment.logo }}">
</a>
</div>
</div>
<div class="col-xs-10">
<!-- --Comment itself-- -->
<div class="user_comment">
<p>{{ comment }}</p>
<div class="fa fa-caret-left comment-arrow"></div>
</div>
<!-- start Options in comment -->
<div class="sub-options">
{% if request.user.username == comment.username %}
<!-- --Edit comment-- -->
<div class="edit-comment">
<a>Edit</a>
</div>
<!-- --Delete comment-- -->
<div class="delete-comment">
<form method="post" action="{% url 'community:delete_comment' comment.pk %}">
{% csrf_token %}
<input type="hidden" name="delete-comment" value="{{ comment.comment }}">
<input type="submit" value="delete">
</form>
</div>
{% endif %}
<!-- end Options in comment -->
<!-- --comment Date-- -->
<div style="display: inline-block;color: #8e8e8e" class="comment-date">
<p>{{ comment.date|time }}</p>
</div>
</div>
</div>
<div class="clearfix"></div>
</div>
{% endfor %}
</div>
</div>
</div>
views.py
# Delete post
# class DeleteComment(DeleteView, SingleObjectMixin):
# model = Comment
# pk_url_kwarg = 'pk'
# template_name = 'community/question_view.html'
# queryset = Comment.objects.all()
#
# def get_success_url(self):
# title = UserAsking.objects.get(title=self.object)
# slug = UserAsking.objects.get(title=title).ask_slug
# return reverse_lazy('community:question_view', kwargs={'user_slug': slug})
#
# def get_object(self, queryset=None):
# request_comment = self.request.POST['delete-comment']
# return self.get_queryset().filter(pk=request_comment).get()
def delete_comment(request, pk):
if request.method == 'POST':
comment = Comment.objects.get(pk=pk)
del comment
return redirect('community:user_questions')
urls.py
urlpatterns = [
# path('delete-comment/<int:pk>/', views.DeleteComment.as_view(), name="delete_comment"),
path('delete-comment/<int:pk>/', views.delete_comment, name="delete_comment"),
]
models.py
class Comment(models.Model):
userasking = models.ForeignKey(UserAsking, on_delete=models.CASCADE)
comment = models.TextField(max_length=500, blank=True)
date = models.DateTimeField(auto_now_add=True)
userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE, default=1)
name = models.CharField(max_length=30, blank=False, default='empty')
logo = models.ImageField(upload_to='images/', default='images/default-logo.jpg', blank=True)
username = models.CharField(max_length=30, blank=False, default='empty')
def __str__(self):
return self.comment
I hope if you can explain by class based-view what's happening I will appreciate that.
note that: if you could understand exactly what's happening you will know that is no error appears to me, therefore, I get no exception or traceback. thank you in advance.
Try this:
def delete_comment(request, pk):
if request.method == 'POST':
comment = Comment.objects.get(pk=pk).delete()
return redirect('community:user_questions')
Your function only deletes the object but not the database entry since you don't trigger a valid SQL operation (delete in this case).
You just delete the object comment again which was assigned previously, but you don't affect the database entry:
def delete_comment(request, pk):
if request.method == 'POST':
comment = Comment.objects.get(pk=pk)
del comment
return redirect('community:user_questions')
More on delete() in the official docu:
Deleting objects¶
Update on your comment:
You can't use Python's del statement to interact with database entries in Django.
Pythons del statement is used to delete objects initially created by Python like lists, variables, etc. etc.
In order to interact with your database in Django, you have to use the toolbox of Django's built-in Model instance which basically translates raw SQL operations into easy to use methods.
So maybe you can adapt a proper wording to highlight the differences by calling database "objects" entries and python objects: well, objects..
However, Django still offers the option to use raw SQL as fallback.

like and comment section: in django

I'd like to put like and comment section in my blog project with some info like no. of likes and comments and also show user who comment on it in django project but don't know how.
its a simple blog so i just want a like button and a comment button, above that its need to show how much likes and comment that post have and at least need to show one comment below that just like a normal blog have
her is my html code:
{% for post in post %}
<article class="media mt-4">
<div class="media-body">
<img class="rounded-circle article-img" id="dp" src="{{ post.author.profile.image.url }}">
<div class="article-metadata">
<a class="mr-2" href="{% url 'Love Travel-User' post.author.username %}">{{ post.author }}</a>
<small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small>
</div>
<h2><a class="article-title" href="{% url 'User-Posts-Details' post.id %}">{{ post.title }}</a></h2>
<img src="{{ post.img.url }}" class="article-img">
<p class="article-content">{{ post.content }}</p>
</div>
</article>
{% endfor %}
views.py
class PostListViews(ListView):
model = Post
template_name = 'userpost/posts.html'
context_object_name = 'post'
ordering = ['-date_posted']
paginate_by = 7
models.py
class Post(models.Model):
title= models.CharField(max_length=100)
img = models.ImageField(upload_to='pics')
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author= models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('User-Posts-Details', kwargs={'pk': self.pk})
any help is appreciated
I will not give the code but I will explain how to do it.
I will help you with the comments part.
You have to create a model Comment link with a Foreign key to Post model. This will allow you to create Comment objects, then you will be able to stock them in your database and display them.
For the view, I prefer Function Based View, it will be easier for you.
And you have to create a ModelForm. To simplify creation of comments you should create an other html page.
I hope it was clear,
Do not hesitate if you have any questions !

When published django-cms plugin from edit mode html template doesn't render model objects. But content reappears when switched to edit mode

Actually, I am new to Django-cms world. I tried almost every duplicate of this same question but none of them worked. I have created my custom plugin with just one ManyToManyField().
I went through Django-docs For many-to-many or foreign key relations to other objects but that didn't helped. Maybe I am lost somewhere, I would really appreciate any help. Thank you.
Try1 PluginModel :
class PortfolioPluginModel(CMSPlugin):
portfolio = models.ManyToManyField(Portfolio)
Try2 PluginModel :
class PortfolioPluginModel(CMSPlugin):
portfolio = models.ManyToManyField(Portfolio)
def copy_relations(self, oldinstance):
for p in oldinstance.portfolio.all():
p.pk = None
p.plugin = self
p.save()
Try3 PluginModel :
class PortfolioPluginModel(CMSPlugin):
portfolio = models.ManyToManyField(Portfolio)
def copy_relations(self, oldinstance):
self.portfolios = oldinstance.portfolios.all()
Apps Model:
class Portfolio(models.Model):
author = models.CharField(max_length = 100)
description = models.TextField()
image = models.ImageField(upload_to ='portfolioImage',blank = True, null = True)
published_at = models.DateTimeField(auto_now_add = True)
cms_plugins.py
#plugin_pool.register_plugin # register the plugin
class PortfolioPluginPublisher(CMSPluginBase):
model = PortfolioPluginModel # model where plugin data are saved
# model = Portfolio(CMSPlugin)
module = _("Portfolio")
name = _("Portfolio Plugin") # name of the plugin in the interface
render_template = "portfolio_cms_integration/portfolio_plugin.html"
cache = False
def render(self, context, instance, placeholder):
context.update({'instance': instance})
return context
portfolio_plugin.html
<div class="filters-content">
<div class="row grid">
{% for p in instance.portfolio.all %}
<div class="single-portfolio col-sm-4 all vector">
<div class="relative">
<div class="thumb">
<div class="overlay overlay-bg"></div>
<img class="image img-fluid" src="{{ p.image.url }}" alt="" style="width:399px; height: 400px;">
</div>
<a href="{{ p.image.url }}" class="img-pop-up">
<div class="middle">
<div class="text align-self-center d-flex"><img src="{% static 'img/preview.png' %}"
alt=""></div>
</div>
</a>
</div>
<div class="p-inner">
<h4>{{ p.author }}</h4>
<div class="cat">{{ p.description }}</div>
</div>
</div>
{% endfor %}
</div>
Expected output : When I publish my post I should see my model objects of portfolio app
Actual output: When I publish my post I dont see any model objects of portfolio app
Your last try works perfectly, you just need to delete the plugin and add it again. It should make use of the copy_relations function this time. You should then see your plugin inside the published view.
Don't forget copy_relations if you have ForeignKeys or ManyToManyField inside your CMSPlugin model.
Fore more information checkout Django CMS documentation about handling relations.

Django-CMS custom plugin not showing data in published pages

I created a custom plugin for my project in Django/Django-CMS and the plugin has a list of testimonials that the user pick when adding the plugin to the page. The model is this:
class TestimonialsPlugin(CMSPlugin):
n_testimonials = models.PositiveIntegerField(
verbose_name=_('Number of Testimonials'), default=5)
speed_autoplay = models.PositiveIntegerField(
verbose_name=_('Speed of slider (milliseconds)'), default=3000)
picked_testimonials = models.ManyToManyField(Testimonials,
verbose_name=_('picked_testimonials'),
blank=True, null=True)
In the edit mode I can se the testimonials in my page and I can publish without errors but when I see the published page the testimonials doesn't show. The plugin template is being rendered but the picked_testimonials gives None. Here's the template:
<div class="max-width1440 block clearfix relative">
<div class="small-only-text-left small-12 small-offset-0 medium-text-center medium-offset-1 medium-10 large-offset-1 large-10 column pt-px60 pb-px40 pl-px40 pr-px40 slider-testimonials">
{% for testimonial in instance.picked_testimonials.all %}
{% if forloop.counter0 < instance.n_testimonials %}
<div class="slider column">
<blockquote class="acta_mediumitalic size36 pl-px80 pr-px80 line-height140">
{% render_model testimonial "description" %}
</blockquote>
<div class="mt-px30">
<p class="acta_book size20 softblack">{{ testimonial.author }},<span>{{ testimonial.city }}</span>
</p>
</div>
</div>
{% endif %}
{% endfor %}
</div>
</div>
When a page is published, a copy of a plugin is created - which does include plugin's fields but not any relations. There is a provision in the CMS to provide copy method for exactly this purpose, see example from documentation:
class ArticlePluginModel(CMSPlugin):
title = models.CharField(max_length=50)
sections = models.ManyToManyField(Section)
def copy_relations(self, oldinstance):
self.sections = oldinstance.sections.all()
The important bit is the copy_relations, which ensures that the new object has the same relational links.
In your case, something along these lines should work:
class TestimonialsPlugin(CMSPlugin):
n_testimonials = models.PositiveIntegerField(
verbose_name=_('Number of Testimonials'), default=5)
speed_autoplay = models.PositiveIntegerField(
verbose_name=_('Speed of slider (milliseconds)'), default=3000)
picked_testimonials = models.ManyToManyField(Testimonials,
verbose_name=_('picked_testimonials'),
blank=True, null=True)
def copy_relations(self, oldinstance):
self.picked_testimonials = oldinstance.picked_testimonials.all()

Categories