Blog Post doesn't show images, bold text, or other attributes only the raw code... Django/Ckeditor - django

I've followed a tutorial on implementing a ckeditor RichTextUploadingField() to my blog so I can have more functionality and better looking post/blogs.
Everything seems to be working but when I go to see the actual post after adding the picture and some words. I get a raw output with all my text...
Here is my output on my blog
<p><span style="color:#1a1a1a"><span style="background-color:#ffffff">First of all, I have assumed that you have seen countless rubbish articles, and still can't understand classes and objects, but at least know that there are two things like classes and objects.</span></span></p>
<p><span style="color:#1a1a1a"><span style="background-color:#ffffff">Since you don't have programming experience, you can't understand Python's 'classes and objects' by analogy from the programming language you've learned. Let's use the example of life to build a house.</span></span></p>
<p> </p>
<p><span style="color:#1a1a1a"><span style="background-color:#ffffff"><img alt="" src="/media/upload/2019/11/08/01.png" style="height:268px; width:400px" /></span></span></p>
Not sure why it doesn't look like the output I get before I post the article while I'm editing and creating it.
MODELS.PY
from ckeditor_uploader.fields import RichTextUploadingField
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
from django.utils import timezone
class Post(models.Model):
title = models.CharField(max_length=100)
# content = models.TextField()
content = RichTextUploadingField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return f'{self.title} --> {self.author}'
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
POST_DETAIL.HTML
{% extends "portfolio_app/base.html" %}
{% block content %}
<div class="py-5 bg-light">
<div class="container">
<div class="row">
<div class="col-md-12">
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'user-posts' object.author.username %}">{{ object.author }}</a>
<small class="text-muted">{{ object.date_posted|date:'F d, Y' }}</small>
{% if object.author == user %}
<div>
<a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'post-update' object.id %}">Update Post</a>
<a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete Post</a>
</div>
{% endif %}
</div>
<h2 class="article-title">{{ object.title }}</h2>
<p class="article-content">{{ object.content }}</p>
</div>
</article>
</div>
</div>
</div>
</div>
{% endblock content %}
POST_FORM.HTML
{% extends "portfolio_app/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container col-md-6">
<div class="content-section">
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom md-4">Blog Post</legend>
{{ form.media }}
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Post!</button>
</div>
</form>
</div>
</div>
</div>
{% endblock content %}
Am I missing something..? Thank you again for your help.

use |safe filter.
<h2 class="article-title">{{ object.title|safe }}</h2>
<p class="article-content">{{ object.content|safe }}</p>

Related

Problems with a backend part of search line in Django

who can explain me why my SearchView doesn't work. I have some code like this.It doesn't show me any mistakes, but it doesn't work. The page is clear. Seems like it doesn't see the input.
search.html
<div class="justify-content-center mb-3">
<div class="row">
<div class="col-md-8 offset-2">
<form action="{% url 'search' %}" method="get">
<div class="input-group">
<input type="text" name="q" class="form-control" placeholder="Search..." />
<div class="input-group-append">
<button class="btn btn-dark" type="submit" id="button-addon2">Search</button>
</div>
</div>
</form>
</div>
</div>
</div>
search/urls.py
path('search/', SearchView.as_view(), name='search')
search/views.py
class SearchView(ListView):
model = Question
template_name = 'forum/question_list.html'
def get_queryset(self):
query = self.request.GET.get("q")
object_list = Question.objects.filter(
Q(title__icontains=query) | Q(detail__icontains=query)
)
return object_list
forum/question_list.html
{% extends 'main/base.html' %}
{% block content %}
{% for question in object_list %}
<div class="card mb-3">
<div class="card-body">
<h4 class="card-title">{{ question.title }}</h4>
<p class="card-text">{{ question.detail }}</p>
<p>
{{ question.user.username }}
5 answers
10 comments
</p>
</div>
</div>
{% endfor %}
{% endblock %}

How to filter out Friends of user in search users function Django

I'm trying to filter out the friends of a user and also the current logged in user from a "search_users" function, I've tried using exclude() but keep getting an error I'm not sure whats wrong. I also wanted to add a "add friend" button next to the users, which I think I've done correctly on 'search_users.html.
Error
views.py
#login_required
def search_users(request):
query = request.GET.get('q')
object_list = User.objects.filter(username__icontains=query).exclude(friends=request.user.profile.friends.all())
context ={
'users': object_list
}
return render(request, "users/search_users.html", context)
search_users.html
{% extends "feed/layout.html" %} {% load static %}
{% block searchform %}
<form
class="form-inline my-2 my-lg-0 ml-5"
action="{% url 'search_users' %}"
method="get"
>
<input name="q" type="text" placeholder="Search users.." />
<button class="btn btn-success my-2 my-sm-0 ml-10" type="submit">
Search
</button>
</form>
{% endblock searchform %} {% block content %}
<div class="container">
<div class="row">
<div class="col-md-8">
{% if not users %}
<br /><br />
<h2><i>No such users found!</i></h2>
{% else %}
<div class="card card-signin my-5">
<div class="card-body">
{% for user_p in users %}
<a href="{{ user_p.profile.get_absolute_url }}"
><img
src="{{ user_p.profile.image.url }}"
class="rounded mr-2"
width="40"
height="40"
alt=""
/></a>
<a class="text-dark" href="{{ user_p.profile.get_absolute_url }}"
><b>{{ user_p }}</b></a
>
<small class="float-right">
<a
class="btn btn-primary mr-2"
href="/users/friend-request/send/{{ user_p.username }}"
>Add Friend</a>
</small>
<br/><br />
{% endfor %}
</div>
</div>
{% endif %}
</div>
<div class="col-md-4">
<div class="card card-signin my-5">
<a href="{{ request.user.profile.get_absolute_url }}"
><img
class="card-img-top"
src="{{ request.user.profile.image.url }}"
alt=""
/></a>
<div class="card-body">
<h5 class="card-title text-center">{{ request.user }}</h5>
<h6 class="text-center">
{{ request.user.profile.friends.count }}
<p class="text-muted">Friends</p>
</h6>
<p class="card-text text-center">{{ request.user.profile.bio }}</p>
</div>
</div>
</div>
</div>
{% endblock content %}
</div>
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.png', upload_to='profile_pics')
slug = AutoSlugField(populate_from='user')
bio = models.CharField(max_length=255, blank=True)
friends = models.ManyToManyField('Profile', blank=True)
I would have done like this :
object_list = User.objects\
.filter(username__icontains=query)\
.exclude(profile__friends__in=request.user.profile.friends.all())\
.exclude(id=request.user.id)
It should be
User.profile.objects.filter(username__icontains=query).exclude(friends=request.user.profile.friends.all())
You were getting an error earlier because you referred to the user object earlier and not the profile itself. User.profile gives the one to one related model profile instead.
You can read more about one to one relationships here. https://docs.djangoproject.com/en/3.1/topics/db/examples/one_to_one/

Image ids apparently not being created

I have created a template for displaying a photo gallery and giving users the ability to add photos to that gallery:
{% extends 'nowandthen/base.html' %}
{% block body_block %}
<br>
<br>
{% if pictures %}
<ul>
{% for p in pictures %}
<div class="container">
<div class="row">
<div class="col-md-8 card mb-4 mt-3 ">
<!-- Card -->
<!-- Card content -->
<div class="card-body d-flex flex-row">
<!-- Content -->
<div>
<!-- Title -->
<h4 class="card-title font-weight-bold mb-2">{{ p.title }}</h4>
<!-- Subtitle -->
<p class="card-text"><i class="far fa-clock pr-2"></i>{{ p.when_added }}</p>
</div>
</div>
<!-- Card image -->
<div class="view overlay">
<img class="card-img-top rounded-0" src="{{ p.image.url }}" alt="Card image cap">
<a href="#!">
<div class="mask rgba-white-slight"></div>
</a>
</div>
<!-- Card content -->
<div class="card-body">
<div class="collapse-content">
<!-- Text -->
<p class="card-text collapse" id="collapseContent">{{ p.description }}</p>
<!-- Button -->
<a class="btn btn-flat red-text p-1 my-1 mr-0 mml-1 collapsed" data-toggle="collapse" href="#collapseContent" aria-expanded="false" aria-controls="collapseContent">Click for description</a>
<i class="fas fa-share-alt text-muted float-right p-1 my-1" data-toggle="tooltip" data-placement="top" title="Share this post"></i>
<i class="fas fa-heart text-muted float-right p-1 my-1 mr-3" data-toggle="tooltip" data-placement="top" title="I like it"></i>
</div>
</div>
<div class="card-body">
<!-- comments -->
<h2>comments</h2>
{% if not p.comments %}
No comments
{% endif %}
{% for x in p.comment %}
<div class="comments" style="padding: 10px;">
<p class="font-weight-bold">
<h4>Comment by</h4> {{ x.user }}
<span class=" text-muted font-weight-normal">
{{ x.created_on }}
</span>
</p>
{{ x.body | linebreaks }}
</div>
{% endfor %}
</div>
<div class="card-body">
{% if new_comment %}
<h2>Your comment has been posted.</h2>
{% else %}
<h3>Leave a comment</h3>
<form action="{% url 'nowandthen:add_comment' p.image_id %}" method="POST">
{{ comment_form.as_p }}
{% csrf_token %}
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
{% endif %}
</div>
</div>
</div>
</div>
<!-- Card -->
{% endfor %}
</ul>
{% else %}
<li><strong>There are no photographs present.</strong></li>
{% endif %}
{% endblock %}
The idea is that there is an image associated with each comment - there is a for loop of {% for p in pictures %} at the start of the page, and I use variations of p. (e.g. p.image_id) to associate particular pictures with particular comments.
In addition, the urls.py contains the following:
path('add_comment/<int:p.image_id>', views.add_comment, name='add_comment')
However, when I run the code, I get an error message that suggests that image ids aren't being created (even though image is a field in he Pictures model I created):
Reverse for 'add_comment' with arguments '('',)' not found. 1 pattern(s) tried: ['add_comment/$']
What do you suggest, please?
EDIT: This is my view:
#login_required
def add_comment(request, image_id):
new_comment = None
template_name = 'add_comment.html'
image = get_object_or_404(Picture, id=image_id)
comment = image.comments.filter(active=True)
new_comment = None
# Comment posted
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create Comment object and don't save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()
context = {'image': image,'comment': comment, 'new_comment': new_comment,'comment_form': comment_form}
return render(request, template_name, context)
And this is my add_comment.html template:
{% extends 'nowandthen/base.html' %}
{% load staticfiles %}
{% block title_block %}
Add self
{% endblock %}
{% block body_block %}
<h1>Add a Comment</h1>
<div>
<form id="comment_form" method="post" action="{% url 'nowandthen:add_comment' comment_id%}" enctype="multipart/form-data" >
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="submit" value="Add Comment" />
</form>
</div>
{% endblock %}
Since you pictures variable is a Queryset, when you loop through it in your template, to access its ID, you just need to do it that way. instance.id
Based on your case, you will have:
{% url 'nowandthen:add_comment' p.id %}
And you will be able to access the id in your view with image_id

Django page navigation- home list not visible

I am super new to Dango; pardon me for a rookie question :)
I am learning Django by creating a "Note taking app". This is how the application home page looks.
When I click on any of the notes from the note list, it opens the details on the right-side page. But the problem is it wipes-out the left-hand side note list. To reload the list I need to click on the Home link again. The expected behavior is, it should retain the note-list on the left side as well as show the details on the right frame.
urls.py
from django.urls import path
from .views import NoteListView, NoteDetailView, NoteCreateView, NoteUpdateView, NoteDeleteView
from . import views
urlpatterns = [
path('', NoteListView.as_view(), name='lekha-home'),
path('note/<int:pk>/', NoteDetailView.as_view(), name='note-detail'),
path('note/new/', NoteCreateView.as_view(), name='note-create'),
path('note/<int:pk>/update', NoteUpdateView.as_view(), name='note-update'),
path('note/<int:pk>/delete', NoteDeleteView.as_view(), name='note-delete'),
path('about/', views.about, name='lekha-about'),
]
enter code here
views.py
class NoteListView(ListView):
model = Note
template_name = 'lekha/home.html'
context_object_name = 'notes'
ordering = ['-date_created']
class NoteDetailView(DetailView):
model = Note
# success_url = 'lekha/note_detail.html'
class NoteCreateView(LoginRequiredMixin, CreateView):
model = Note
fields = ['title', 'content']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
home.html
{% extends "lekha/base.html" %}
{% block content %}
{% for note in notes %}
<div class="list-group">
{{ note.title }}
</div>
{% endfor %}
{% endblock content %}
note_detail.html
{% extends "lekha/base.html" %}
{% block content2 %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<a class="mr-8" href="#">{{ object.author }}</a>
<small class="text-muted">{{ object.date_created|date:"F d, Y" }}</small>
{% if object.author == user %}
<a class="btn float-right btn-secondary ml-1 btn-sm" href="{% url 'note-update' object.id %} ">Update</a>
<a class="btn float-right btn-danger ml-1 btn-sm" href="{% url 'note-delete' object.id %} ">Delete</a>
{% endif %}
</div>
<h4 class="article-title">{{ object.title }}</h4>
<hr>
<p class="article-content">{{ object.content }}</p>
</div>
</article>
{% endblock content2 %}
And this is how I am calling it in base.html
<main role="main" class="container-fluid px-2">
<div class="row">
<div class="col-md-3">
<div class="content-section">
<h4>Notes</h4>
{% block content %}{% endblock %}
</div>
</div>
<div class="col-md-8">
{% block content2 %}{% endblock %}
</div>
</div>
</main>
Sorry for the detailed post. I would appreciate any pointers. Thanks!
Welcome to Django!
Your template note_detail.html extends base.html, which doesn't contain the HTML for the list of notes, and note_detail.html doesn't add the list, so that's why it's not showing up - you haven't added it!
To do this, you need the same {% block content %} from home.html in note_detail.html, and you also need to manually pass a notes context variable to the template. You get that for free with the ListView class.
First, the change to the template:
note_detail.html
{% extends "lekha/base.html" %}
{% block content %}
{% for note in notes %}
<div class="list-group">
{{ note.title }}
</div>
{% endfor %}
{% endblock content %}
{% block content2 %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<a class="mr-8" href="#">{{ object.author }}</a>
<small class="text-muted">{{ object.date_created|date:"F d, Y" }}</small>
{% if object.author == user %}
<a class="btn float-right btn-secondary ml-1 btn-sm" href="{% url 'note-update' object.id %} ">Update</a>
<a class="btn float-right btn-danger ml-1 btn-sm" href="{% url 'note-delete' object.id %} ">Delete</a>
{% endif %}
</div>
<h4 class="article-title">{{ object.title }}</h4>
<hr>
<p class="article-content">{{ object.content }}</p>
</div>
</article>
{% endblock content2 %}
And the change to the view:
views.py
class NoteListView(ListView):
model = Note
template_name = 'lekha/home.html'
context_object_name = 'notes'
ordering = ['-date_created']
class NoteDetailView(DetailView):
model = Note
def get_context_data(self):
data = super().get_context_data
data['notes'] = Note.objects.all().order_by('-date_created')
One last tip: to keep your HTML templates "DRY," you should really extract the list of notes into a separate html template (often called a partial) that you can plug into multiple other templates. Your template setup would look like this:
partials/all_notes.html
{% for note in notes %}
<div class="list-group">
{{ note.title }}
</div>
{% endfor %}
home.html
{% extends "lekha/base.html" %}
{% block content %}
{% include 'lekha/partials/all_notes.html' %}
{% endblock content %}
note_detail.html
{% extends "lekha/base.html" %}
{% block content %}
{% include 'lekha/partials/all_notes.html' %}
{% endblock content %}
{% block content2 %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<a class="mr-8" href="#">{{ object.author }}</a>
<small class="text-muted">{{ object.date_created|date:"F d, Y" }}</small>
{% if object.author == user %}
<a class="btn float-right btn-secondary ml-1 btn-sm" href="{% url 'note-update' object.id %} ">Update</a>
<a class="btn float-right btn-danger ml-1 btn-sm" href="{% url 'note-delete' object.id %} ">Delete</a>
{% endif %}
</div>
<h4 class="article-title">{{ object.title }}</h4>
<hr>
<p class="article-content">{{ object.content }}</p>
</div>
</article>
{% endblock content2 %}
base.html
<main role="main" class="container-fluid px-2">
<div class="row">
<div class="col-md-3">
<div class="content-section">
<h4>Notes</h4>
{% block content %}{% endblock %}
</div>
</div>
<div class="col-md-8">
{% block content2 %}{% endblock %}
</div>
</div>
</main>

django class page view not rendering template code

I wanted to use class based views and went through the django documentation and I get noerror messages but wind up with an empty template. I had it working with the non-classed based views. How do I reformat the code so that it renders the template? The template consists of a title, some headings, a navigational menu, flags for selecting instructions in different languages,
followed by a form which shows a flag, policy name char field, and a check box control. I think the initial = {'key': 'value'} in the view forms incorrect but I don't know what to replace it with. Thanks in advance.
forms.py
from django import forms
from policytracker.models import Flag, Label_Links
class PolicyStartForm( forms.Form ):
flags = Flag.objects.all()
policy = Label_Links.objects.all().filter(iso_language='en')[0]
frm_policy1_name=[]
for flag in flags:
frm_policy1_name.append(forms.CharField(max_length=40))
policy_dict = { 'new_policy_link' :policy.nav_section_new_policy_link,
'new_policy_label' :policy.nav_section_new_policy_label,
'graphs_link':policy.nav_section_graphs_link,
'graphs_label' :policy.nav_section_graphs_label,
'account_link' :policy.nav_section_account_link,
'account_label' :policy.nav_section_account_label,
'policy_list_link':policy.nav_section_list_policies_link,
'policy_list_label':policy.nav_section_list_policies_label,
'login_link' :policy.nav_section_login_link,
'login_label' :policy.nav_section_login_label,
'new_policy1_heading' :policy.new_policy1_heading,
'new_policy1_title_label':policy.new_policy1_title_label,
'policy_needs_translation_label':policy.new_policy1_needs_trans_label,
'policy1_submit_label': policy.new_policy1_submit_button_label,
'policy1_tip_msg' :policy.new_policy1_tip_msg,
't_logged_in' :True,
'frm_policy_name' :frm_policy1_name,
't_flags' :flags }
</code>
<code>
views.py
# coding=utf-8
from django.shortcuts import render
from django.http import HttpResponseRedirect
from policytracker.forms import LoginForm, PolicyStartForm
from policytracker.models import Flag, Label_Links
from django.views import View
class PolicyStartView(View):
template_name = 'policystart.html'
initial = {'key': 'value'}
form_class = PolicyStartForm
def get(self, request, *args, **kwargs):
form = self.form_class(initial=self.initial)
return render(request, self.template_name, {'form': form})
</code>
<code>
policystart.html
{% extends "policy-base.html" %}
{% block navsection %}
<div class="container top">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<h1 class="text-center">{{ new_policy1_heading }}</h1>
</div>
</div>
{% if t_policy_details %}
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<h4 class="text-nowrap text-left" id="week_start">2017-02-11</h4></div>
<div class="col-md-4 col-xs-4">
<h4 class="text-center" id="week_number">Week 1</h4></div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<h4 class="text-nowrap text-right" id="week_end">2016-09-18</h4></div>
</div>
{% endif %}
<div class="row">
<div class="col-md-12">
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header"><a class="navbar-brand hidden navbar-link" href="#"> Policies</a>
<button class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navcol-1"><span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button>
</div>
<div class="collapse navbar-collapse" id="navcol-1">
<ul class="nav navbar-nav navbar-right">
<li class="hidden" role="presentation">{{ new_policy_label }}</li>
<li {% if not t_logged_in %} class="hidden" {% endif %} role="presentation">{{ graphs_label }}</li>
<li {% if not t_logged_in %} class="hidden" {% endif %} role="presentation">{{ account_label }}</li>
<li role="presentation">{{ policy_list_label }}</li>
{% if not t_logged_in %} <li role="presentation">{{ login_label }}</li> {% endif %}
</ul>
</div>
</div>
</nav>
</div>
</div>
{% include "pol-new1-lang.html" %}
</div>
<div class="container middle-container">
<div class="row">
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-3">
<p> </p>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-8">
<h4>{{ new_policy1_title_label }}</h4>
</div>
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1">
<h4 class="text-center">{{ policy_needs_translation_label }}</h4>
</div>
</div>
<form method="POST">
{% csrf_token %}
{% load static %}
{% for f in t_flags %}
<div class="row flag">
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-2"><img src="{% static f.flag_image_filename %}"></div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-9">
<input class="form-control" type="text" name="policytitle">
</div>
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1">
<input class="form-control" type="checkbox" name="needstranslation">
</div>
</div>
{% endfor %}
<div class="row enter">
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-3">
<p> </p>
</div>
<div class="col-lg-9 col-md-9 col-sm-9 col-xs-8">
<button class="btn btn-default" type="submit">{{ policy1_submit_label }}</button>
</div>
</div>
</form>
<div class="row enter">
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-3">
<p> </p>
</div>
<div class="col-lg-9 col-md-9 col-sm-9 col-xs-8">
<p>{{ policy1_tip_msg }}</p>
</div>
</div>
</div>
{% endblock %}
</code>
You're using a load of variables in your template, but you aren't actually sending any of them to the context; the only thing your view passes is form. If you want to use things like new_policy1_heading, policy_needs_translation_label and t_flags you need to define them in your view and send them to the template from there.
Actually, it looks like you've completely misunderstood the jobs of forms and views. All the code you've currently put inside your form actually belongs in the view, and you should use policy_dict as the template context. It doesn't look like you need a form class at all.
Even there, though, you're doing much more work than you need to. There's no need to send all the specific fields of the policy object individually; just send policy and then in the template you can do {{ policy.policy_needs_translation_label }} etc.