Added the ability to add comments, made it so that only authorized users can add comments, but for some reason this does not work, please fix it.
I also added tag strong, but for some reason it does not work either
post_detail.html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<link href="{% static 'css/post_detail.css' %}" rel="stylesheet">
<div class="post-entry">
<h2>{{ post.title }}</h2>
<p>{{ post.body|urlize }}</p>
</div>
<p>+ Edit Blog Post</p>
<p>+ Delete Blog Post</p>
{% if post.header_image %}
<p><img src="{{post.header_image.url}}"></p>
{% else %}
<p></p>
{% endif %}
{% for comm in post.commentpost_set.all%}
{{ comm.user }} <br>
{{ comm.text }} <br><br>
{% endfor %}
<br>
<hr>
<h2>Comments...</h2>
{% if not post.comments.all %}
No Comments Yet...<a href="{% url 'post_comment' post.pk %}">
Add Comment</a>
{% else %}
<form method="post">
{% csrf_token %}
{{ comment_form.as_p }}
{% if request.user.is_authenticated %}
Add Comment<br><br>
{% else %}
Add Comment<br><br disabled>
{% endif %}
</form>
{% for comment in post.comments.all %}
<strong>
{{ comment.name }} -
{{ comment.date_added }}
</strong>
<br>
{{ comment.body }}
<br><br>
{% endfor %}
{% endif %}
{% endblock content %}
views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy, reverse
from .models import Post, Comment
from .forms import CommentForm
from django.http import HttpResponseRedirect
class BlogListView(ListView):
model = Post
template_name = 'home.html'
context_object_name = 'posts'
paginate_by = 2
queryset = Post.objects.all()
class BlogDetailView(DetailView):
model = Post
template_name = 'post_detail.html'
class BlogCreateView(CreateView):
model = Post
template_name = 'post_new.html'
fields = ['title', 'author', 'body', 'header_image']
class BlogCommentView(CreateView):
model = Comment
form_class = CommentForm
template_name = 'post_comment.html'
def form_valid(self, form):
form.instance.post_id = self.kwargs['pk']
return super().form_valid(form)
success_url = reverse_lazy('home')
#fields = '__all__'
class BlogUpdateView(UpdateView):
model = Post
template_name = 'post_edit.html'
fields = ['title', 'body', 'header_image']
class BlogDeleteView(DeleteView):
model = Post
template_name = 'post_delete.html'
success_url = reverse_lazy('home')
#property
def image_url(self):
if self.image:
return getattr(self.photo, 'url', None)
return None
Write what files still need to be shown, I will show
Thanks everyone!
<form method="post">
{% csrf_token %}
{{ comment_form.as_p }}
{% if request.user.is_authenticated %}
Add Comment<br><br>
{% else %}
Add Comment<br><br>
{% endif %}
</form>
Related
Based on this tutorial https://www.youtube.com/watch?v=An4hW4TjKhE&ab_channel=AbhishekVerma
I'm trying to add the ability to add comments under posts, add a comment in the admin panel, everything is ok, but the site does not display anything under the post
here is models.py
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
class Post(models.Model):
published = None
title = models.CharField(max_length=200)
author = models.ForeignKey(
'auth.User',
on_delete=models.CASCADE,
)
body = models.TextField()
header_image = models.ImageField(blank=True, null=True, upload_to="images/", default='fox.jpeg')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post_detail', args=[str(self.id)])
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post_post')
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_user')
content = models.TextField(max_length=160)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '{}-{}'.format(self.post.title, str(self.user.username))
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from .models import Post, Comment
from django import forms
from .forms import *
class BlogListView(ListView):
model = Post
template_name = 'home.html'
context_object_name = 'posts'
paginate_by = 2
queryset = Post.objects.all()
class BlogDetailView(DetailView):
model = Post
template_name = 'post_detail.html'
class BlogCreateView(CreateView):
model = Post
template_name = 'post_new.html'
fields = ['title', 'author', 'body', 'header_image']
class BlogUpdateView(UpdateView):
model = Post
template_name = 'post_edit.html'
fields = ['title', 'body', 'header_image']
class BlogDeleteView(DeleteView):
model = Post
template_name = 'post_delete.html'
success_url = reverse_lazy('home')
#property
def image_url(self):
"""
Return self.photo.url if self.photo is not None,
'url' exist and has a value, else, return None.
"""
if self.image:
return getattr(self.photo, 'url', None)
return None
def post_detail(request, id, slug):
post = get_object_or_404(Post, id=id, slug=slug)
comments = Comment.objects.filter(post=post).order_by('-id')
is_liked = False
if post.likes.filter(id=request.user.id).exists():
is_liked = True
if request.method == 'POST':
comment_form = CommentForm(request.POST or None)
if comment_form.is_valid():
content = request.POST.get('content')
comment = Comment.objects.create(post=post, user=request.user, content=content)
comment.save()
return HttpResponseRedirect(post.get_absolute_url())
else:
comment_form = CommentForm()
context = {
'post': post,
'is_liked': is_liked,
'total_likes': post.total_likes(),
'comments': comments,
'comment_form': comment_form,
}
return render(request, 'myblog/post_detail.html', context) #his "blog" = my "myblog"
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('content',)
post_detail.html
{% extends 'base.html' %}
{% block content %}
<div class="post-entry">
<h2>{{ post.title }}</h2>
<p>{{ post.body }}</p>
</div>
<p>+ Edit Blog Post</p>
<p>+ Delete Blog Post</p>
<img src="{{ post.header_image.url|default_if_none:'fox.jpeg' }}">
{{ post.body|urlize }}
{% for comm in post.commentpost_set.all%}
{{ comm.user }} <br>
{{ comm.text }} <br><br>
{% endfor %}
{% endblock content %}
<br><br>
<hr>
<form method="post">
{% csrf_token %}
{{ comment_form.as_p }}
{% if request.user.is_authenticated %}
<input type="submit" value="Submit" class="btn btn-outline-success">
{% else %}
<input type="submit" value="Submit" class="btn btn-outline-success" disabled>
{% endif %}
</form>
<div class="main-comment-section">
{{ comments.count }} Comment{{ comments|pluralize }}
{% for comment in comments %}
<blockquote class="blockquote">
<p class="mb-0">{{ comment.content }}</p>
<footer class="blockquote-footer">by <cite title="Source Title">{{ comment.user|capfirst }}</cite></footer>
</blockquote>
{% endfor %}
</div>
myblog/urls.py
from django.urls import path
from .views import (
BlogListView,
BlogDetailView,
BlogCreateView,
BlogUpdateView,
BlogDeleteView,
)
urlpatterns = [
path('post/new/', BlogCreateView.as_view(), name='post_new'),
path('post/<int:pk>/', BlogDetailView.as_view(), name='post_detail'),
path('post/<int:pk>/edit/',BlogUpdateView.as_view(), name='post_edit'),
path('post/<int:pk>/delete/',BlogDeleteView.as_view(), name='post_delete'),
path('', BlogListView.as_view(), name='home'),
]
base.html
{% load static %}
<html>
<head>
<title>Django blog</title>
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400"
rel="stylesheet">
<link href="{% static 'css/base.css' %}" rel="stylesheet">
</head>
<body>
<div>
<header>
<div class="nav-left">
<h1>Django blog</h1>
<h2>Admin</h2>
</div>
<div class="nav-right">
+ New Blog Post
</div>
</header>
{% if user.is_authenticated %}
<p>Hi {{ user.username }}!</p>
{% else %}
<p>You are not logged in.</p>
Log In<br>
<p>Sign up</p>
{% endif %}
{% block content %}
{% endblock content %}
</div>
</body>
</html>
<ul class="pagination">
{% if page_obj.has_previous %}
{% if page_obj.number|add:'-3' > 1 %}
<li class="pagination__item">
1
</li>
{% endif %}
{% if page_obj.number|add:'-3' >= 3 %}
<li class="pagination__item pagination__item--dots">
<a href="?{{ genre }}{{ year }}page={{ page_obj.previous_page_number|add:'-3' }}">
<span class="pagination__link">• • •</span>
</a>
</li>
{% endif %}
{% endif %}
{% if paginator.page_range|length > 1 %}
{% for i in paginator.page_range %}
{% if page_obj.number == i %}
<li class="pagination__item active">
<a class="pagination__link" href="#">{{ i }}</a>
</li>
{% elif i > page_obj.number|add:'-4' and i < page_obj.number|add:'4' %}
<li class="pagination__item">
<a class="pagination__link" href="?{{ genre }}{{ year }}page={{ i }}">{{ i }}</a>
</li>
{% endif %}
{% endfor %}
{% endif %}
{% if page_obj.has_next %}
{% if page_obj.number|add:'4' < page_obj.paginator.num_pages %}
<li class="pagination__item pagination__item--dots">
<a href="?{{ genre }}{{ year }}page={{ page_obj.next_page_number|add:'3' }}">
<span class="pagination__link">• • •</span>
</a>
</li>
{% endif %}
{% if page_obj.number|add:'3' < page_obj.paginator.num_pages %}
<li class="pagination__item">
<a class="pagination__link" href="?{{ genre }}{{ year }}page={{ page_obj.paginator.num_pages }}">
{{ page_obj.paginator.num_pages }}
</a>
</li>
{% endif %}
{% endif %}
</ul>
Thanks for any help
Your post_detail.html extends base.html, hence any content you wish to render must be inside some block and this block also must be present in the parent template (base.html here). You currently have some content outside any block and hence they aren't rendered. Put the HTML inside the block and it will show up:
{% extends 'base.html' %}
{% block content %}
<div class="post-entry">
<h2>{{ post.title }}</h2>
<p>{{ post.body }}</p>
</div>
<p>+ Edit Blog Post</p>
<p>+ Delete Blog Post</p>
<img src="{{ post.header_image.url|default_if_none:'fox.jpeg' }}">
{{ post.body|urlize }}
{% for comm in post.commentpost_set.all%}
{{ comm.user }} <br>
{{ comm.text }} <br><br>
{% endfor %}
<!-- put them inside the block -->
<br><br>
<hr>
<form method="post">
{% csrf_token %}
{{ comment_form.as_p }}
{% if request.user.is_authenticated %}
<input type="submit" value="Submit" class="btn btn-outline-success">
{% else %}
<input type="submit" value="Submit" class="btn btn-outline-success" disabled>
{% endif %}
</form>
<div class="main-comment-section">
{{ comments.count }} Comment{{ comments|pluralize }}
{% for comment in comments %}
<blockquote class="blockquote">
<p class="mb-0">{{ comment.content }}</p>
<footer class="blockquote-footer">by <cite title="Source Title">{{ comment.user|capfirst }}</cite></footer>
</blockquote>
{% endfor %}
</div>
{% endblock content %}
I want to create app with search and pagination. Pagination didn't work with ListView.
When I click on the link "next" I am moving from start page http://127.0.0.1:8001/ ---> to the http://127.0.0.1:8001/?city=2 but elements of the list did not change.
And next click to the "next" link did not changes the url ( http://127.0.0.1:8001/?city=2 --> http://127.0.0.1:8001/?city=2).
Could you help me to find error?
I think that error in *.html file, but can't find it
My code:
models.py
from django.db import models
class City(models.Model):
name = models.CharField(max_length=255)
state = models.CharField(max_length=255)
class Meta:
verbose_name_plural = "cities"
def __str__(self):
return self.name
urls.py
# cities/urls.py
from django.urls import path
from . import views
from .views import HomePageView, SearchResultsView
urlpatterns = [
path('search/', SearchResultsView.as_view(), name='search_results'),
path('', HomePageView.as_view(), name='home'),
path('city/<int:pk>/', views.city_detail, name='city_detail'),
]
views.py
from django.shortcuts import render
from django.views.generic import TemplateView, ListView
from .models import City
from django.db.models import Q
from django.shortcuts import render, get_object_or_404
class HomePageView(ListView):
model = City
template_name = 'cities/home.html'
paginate_by = 3
def city_detail(request, pk):
city = get_object_or_404(City, pk=pk)
return render(request, 'cities/city_detail.html', {'city': city})
class SearchResultsView(ListView):
model = City
template_name = 'cities/search_results.html'
def get_queryset(self): # new
query = self.request.GET.get('q')
object_list = City.objects.filter(
Q(name__icontains=query) | Q(state__icontains=query)
)
return object_list
home.html
<!-- templates/home.html -->
<h1>HomePage</h1>
<form action="{% url 'search_results' %}" method="get">
<input name="q" type="text" placeholder="Search...">
</form>
<ul>
{% for city in object_list %}
<li>
<h1>{{ city.name }}</h1>
</li>
{% endfor %}
</ul>
{{page_obj}}
<div class="pagination">
<span class="page-links">
{% if page_obj.has_previous %}
previous
{% endif %}
<span class="page-current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
next
{% endif %}
</span>
</div>
The standard name for the page query parameter is 'page' You should either change the name of the queryparameter, or render the template with the ?page= parameter.
Option 1: Changing the page_kwarg
You can change that by altering the page_kwarg attribute [Django-doc]:
class HomePageView(ListView):
model = City
template_name = 'cities/home.html'
paginate_by = 3
page_kwarg = 'city'
Option 2: Changing the template
It might be more sensical however to simply change the template, such that it uses page as parameter:
<div class="pagination">
<span class="page-links">
{% if page_obj.has_previous %}
previous
{% endif %}
<span class="page-current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
next
{% endif %}
</span>
</div>
Please, click the link to see the picture to see the error.
base.html
<ul class= 'nav navbar-nav navbar-right'>
{% if user.is_authenticated %}
<li>
New post
</li>
<li>
Drafts
</li>
<li>
Log out
</li>
<li>
<a >Welcome: {{ user.username }}</a>
</li>
{% else %}
<li>
<a class = 'nav navbar-right' href="{% url 'login' %}">
<span class = 'glyphicon glyphicon-user'></span>
</a>
<a class = 'nav navbar-right' href= "{% url 'signup' %}">
Sign up</a>
post_detail.html
{% extends 'blog/base.html'%}
{% block content %}
<h1 class= 'posttitle loader'>{{ post.title }}</h1>
{% if post.published_date %}
<div class="date postdate">
{{ post.published_date }}
</div>
{% else %}
<a class = 'btn btn-primary' href=" {% url 'post_publish' pk=post.pk
%}">Publish</a>
{% endif %}
<p class = 'postcontent'> {{ post.text|safe|linebreaksbr}}</p>
{% if user.is_authenticated %}
<a class= 'btn btn-primary' href="{% url 'post_edit' pk=post.pk %}">
<span class = 'glyphicon glyphicon-pencil'></span>
</a>
<a class= 'btn btn-primary' href="{% url 'post_remove' pk=post.pk %}">
<span class = 'glyphicon glyphicon-remove'></span>
</a>
{% endif %}
<hr>
{% if user.is_authenticated %}
<a class = 'btn btn-primary btn-comment' href="{% url 'add_comment_to_post'
pk=post.pk %}">Comment</a>
{% else %}
<a class = 'btn btn-primary btn-comment' href="{% url 'comment_redirect'
pk=post.pk %}">Comment</a>
{% endif %}
<div class="container">
{% for comment in post.comments.all %}
<br>
{% if user.is_authenticated or comments.approved_comments %}
{{ comment.created_date }}
{% if not comment.approved_comments %}
<a class= 'btn btn-default' href="{% url 'comment_remove' pk=comment.pk
%}">
<span class = 'glyphicon glyphicon-remove'></span></a>
<a class= 'btn btn-primary' href="{% url 'comment_approve' pk=comment.pk
%}">
<span class = 'glyphicon glyphicon-ok'></span></a>
{% else %}
{% endif %}
<p>{{ comment.text|safe|linebreaks }}</p>
<p>Posted by: {{ comment.author }}</p>
{% endif %}
{% empty %}
<p>No comments</p>
{% endfor %}
</div>
{% endblock %}
post_form.html
% extends 'blog/base.html'%}
{% load bootstrap3 %}
{% block content %}
<h1>New post</h1>
<form class="post-form" method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
<script>
var editor = new MediumEditor('.editable');
</script>
{% endblock %}
urls.py
from django.conf.urls import url
from blog import views
urlpatterns = [
url(r'^about/$', views.AboutView.as_view(), name = 'about'),
url(r'^$', views.PostListView.as_view(),name = 'post_list' ),
url(r'^post/(?P<pk>\d+)$', views.PostDetailView.as_view(), name = 'post_detail'),
url(r'^post/new/$', views.CreatePostView.as_view(), name = 'post_new'),
url(r'^post/(?P<pk>\d+)/edit/$', views.PostUpdateView.as_view(), name = 'post_edit'),
url(r'^post/(?P<pk>\d+)/remove/$', views.PostDeleteView.as_view(), name = 'post_remove'),
url(r'^drafts/$', views.DraftListView.as_view(),name = 'post_draft_list' ),
url(r'^post/(?P<pk>\d+)/Comment/$', views.add_comment_to_post, name = 'add_comment_to_post'),
url(r'^comment/(?P<pk>\d+)/approve/$',views.comment_approve, name = 'comment_approve'),
url(r'^comment/(?P<pk>\d+)/remove/$',views.comment_remove, name = 'comment_remove'),
url(r'^signup/$', views.SignUp.as_view(), name ='signup'),
url(r'^comment/(?P<pk>\d+)/Comment/$', views.comment_red, name = 'comment_redirect'),
url(r'^post/(?P<pk>\d+)/publish/$', views.post_publish,
name='post_publish'),
]
views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from django.views.generic import (TemplateView, ListView, DetailView,
CreateView,UpdateView,DeleteView)
from blog.models import Post,comments, User
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from blog.forms import PostForm, CommentsForm
from django.urls import reverse_lazy
from django.contrib.auth import login, logout
from . import forms
Created views here.
class AboutView(TemplateView):
template_name = 'about.html'
class PostListView(ListView):
model = Post
def get_query(self):
return post.object.filter(published_date__lte=timezone.now()).orderby('-
published_date')
class PostDetailView(DetailView):
model = Post
class CreatePostView(LoginRequiredMixin,CreateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
form_class = PostForm
model = Post
class PostUpdateView(LoginRequiredMixin, UpdateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
form_class = PostForm
model = Post
class PostDeleteView(LoginRequiredMixin, DeleteView):
model = Post
success_url = reverse_lazy('post_list')
class DraftListView(LoginRequiredMixin, ListView):
login_url = '/login/'
redirect_field_name = 'blog/post_draft_list.html'
model = Post
def get_query(self):
return post.object.filter(published_date__isnull =
True).order_by('created_date')
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse_lazy('login')
template_name = 'sign_up.html'
model = User
############COMMENT###################
#login_required
def post_publish(request, pk):
post = get_object_or_404(Post, pk=pk)
post.publish()
redirect('post_detail', pk=pk)
def comment_red(request,pk):
post = get_object_or_404(Post, pk=pk)
return render(request,'blog/comment_redirect.html')
#login_required
def add_comment_to_post(request,pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = CommentsForm(request.POST)
if form.is_valid():
comment = form.save(commit = False)
comment.post = post
comment.save()
return redirect('post_detail', pk=post.pk)
else:
form = CommentsForm()
return render(request, 'blog/comment_form.html',{'form':form})
#login_required
def comment_approve(request, pk):
comment = get_object_or_404(comments, pk=pk)
comment.approve()
return redirect('post_detail', pk=comment.post.pk)
#login_required
def comment_remove(request, pk):
comment = get_object_or_404(comments, pk=pk)
comment.delete()
return redirect('post_detail', pk=comment.post.pk)
Can I anyone please help me where I got wrong or what I need to, I just got stuck on this. Initially, it was working fine when I click New post on nav bar, it would lead me to the form when I can input text and author but now when I click there, I get this NoReverseMatch at /post/new/ Reverse for 'post_publish' with keyword arguments '{'pk': ''}' not found.
Thank you.
My first guess is that post object is null here:
<a class = 'btn btn-primary' href=" {% url 'post_publish' pk=post.pk
%}">Publish</a>
But to be sure we need a full stack strace.
EDIT #1
We are still missing the traceback, i cannot see it in your picture, but my answer is still valid. post.pk is None, you should replace it with object.pk since you're using a Detailview.
https://docs.djangoproject.com/en/2.0/ref/class-based-views/generic-display/#detailview
How can I add "headers" to context so it's accessible in templates. I guess it needs to be pass to get request somehow? What would be the pythonic way to pass this variable to a get method in FormView class?
views.py
class IndexView(FormView):
template_name = 'index.html'
form_class = CheckForm
success_url = reverse_lazy('index')
def form_valid(self, form, **kwargs):
context = self.get_context_data(**kwargs)
context['headers'] = form.result()
return super(IndexView, self).form_valid(form)
index.html
<form action="." method="post" name="url" id="url" novalidate>
{{ form.as_p }}
{% csrf_token %}
<button type="submit">Check</button>
{% if headers %}
{% for k,v in headers %}
{{ k }}: {{ v }}<br>
{% endfor %}
{% else %}
<br>No data
{% endif %}
forms.py
from django import forms
import requests
class CheckForm(forms.Form):
url = forms.URLField(max_length=255, label='')
def result(self):
cd = self.cleaned_data
url = cd['url']
r = requests.get(url)
r.headers
return r
urls.py
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
]
I am pretty sure you want to use messages
from django.contrib import messages
So now you can add some stuff and send it to the next template.
messages.success(request, u"Success message - text only")
In template :
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>
{% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Important: {% endif %}
{{ message }}
</li>
{% endfor %}
</ul>
{% endif %}
Main problem is the redirect on success. This will throw another get request to same window. In your case this is not desired as you want to capitalize on the data from the form.
views.py
import requests
class IndexView(FormView):
template_name = 'index.html'
form_class = CheckForm
def form_valid(self, form, **kwargs):
context = self.get_context_data()
context['headers'] = form.get_headers()
return self.render_to_response(context)
forms.py
import requests
from django import forms
class CheckForm(forms.Form):
url = forms.URLField(max_length=255, label='')
def get_headers(self):
if self.cleaned_data:
url = self.cleaned_data['url']
return requests.get(url).headers
return {}
index.html
<form action="." method="post" name="url" id="url" novalidate>
{{ form.as_p }}
{% csrf_token %}
<button type="submit">Check</button>
{% if headers %}
{% for k,v in headers.items %}
{{ k }}: {{ v }}<br>
{% endfor %}
{% else %}
<br>No data
{% endif %}
Had a similar requirement and passed the custom context (here a processed file) and the original form instance in form_valid() to a render method instead of the forms default HttpResponseRedirect.
# forms.py
class MyForm(forms.Form):
file = forms.FileField()
# views.py
class MyFormView(FormView):
template_name = 'path/to/template/mytemplate.html'
form_class = MyForm
def get_success_url(self):
return self.request.path
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['processed_data'] = None
return context
def do_some_processing(self, file):
# process file...
return processed_data
def form_valid(self, form):
form = super().form_valid(form)
custom_context = {
"form": self.form_class,
"processed_data": self.do_some_processing(self.request.FILES['file']),
}
context = self.get_context_data(form=form)
context.update(custom_context)
return render(self.request, self.template_name, context)
# mytemplate.html
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
<pre>
{{ processed_data }}
</pre>
I have a lots of apps, but I want to generate all app's data on my homepage. Here's my apps:blog,members
I want to show blogs and my members on my homepage
I know that if I want to generate one app's data,I can do this:
blog/urls.py:
urlpatterns = [
url(r'^$', ListView.as_view(
queryset=Post.objects.all().order_by("-date")[:10],
template_name='blog1.html')),
and in blog1.html:
{% extends "index.html" %}
{% block blog %}
{% for post in blog_post %}
<div id="blog-wrapper" class="bgrid-third s-bgrid-half mob-bgrid-whole group">
<article class="bgrid">
<h5>{{ post.date }} </h5>
<h3><div class = "entry-title">{{ post.title }}</div></h3>
<p>{{ post.user }}</p>
<p><div class = "post_body">{{ post.body|safe|linebreaks }}</div></p>
</article>
</div>
{% endfor %}
{% endblock %}
{% block member %}
Here when I go to the url,I can see all blogs I write,but now I want to see blogs and members(another app) on one page, so how can I do this?
I would suggest you to use ListView's get_context_data method.
Create view in your project's views.py:
from django.views.generic import ListView
# Import your models here.
class HomepageView(ListView):
model = Post
ordering = '-date'
template_name = 'blog1.html'
context_object_name = 'posts'
def get_context_data(self, **kwargs):
context = super(HomepageView, self).get_context_data(**kwargs)
context['members'] = Member.objects.all()
return context
def get_queryset(self):
return super(HomepageView, self).get_queryset()[:10]
Then, change urls.py:
from django.conf.urls import url
# Import ``HomepageView`` here.
urlpatterns = [
url(r'^$', HomepageView.as_view(), name='homepage'),
# Other patterns here.
]
Now you can access posts using posts variable and members using members variable.
from .models import Post
from member.models import UserProfile
def get_data():
return {
"post": Post.objects.all().order_by("-date")[:10],
"user": UserProfile.objects.all()[:10]
}
then in my blog1.html:
{% extends "index.html" %}
{% block blog %}
{% for post in object_list.post %}
<div id="blog-wrapper" class="bgrid-third s-bgrid-half mob-bgrid-whole group">
<article class="bgrid">
<h5>{{ post.date }} </h5>
<h3><div class = "entry-title">{{ post.title }}</div></h3>
<p>{{ post.user }}</p>
<p><div class = "post_body">{{ post.body|safe|linebreaks }}</div></p>
</article>
</div>
{% endfor %}
{% endblock %}
{% block member %}
{% for post in object_list.user %}
<div class="bgrid member">
<div class="member-header">
<div class="member-pic">
<img src="{{ post.portrait }}" alt=""/>
</div>
<div class="member-name">
<h3>{{ post.user }}</h3>
<span>Creative Director</span>
</div>
</div>
<p>{{ post.intro }}</p>
<ul class="member-social">
<li><i class="fa fa-google-plus"></i></li>
<li><i class="fa fa-github"></i></li>
</ul>
</div> <!-- /member -->
{% endfor %}
{% endblock %}