我试图修改django教程中的帖子应用程序 - https://github.com/codingforentrepreneurs/Advancing-the-Blog/tree/master/src/posts
我正在创建一个新字段' userc'在forms.py中:
userc = forms.ModelChoiceField(queryset=User.objects.filter(is_staff=True))
我尝试了各种方法,但我无法在模板中显示所选用户。
我应该在views.py中添加什么?
修改 我已尝试{{obj.userc}},{{instance.userc}}在模板中显示所选用户。
views.py
from django.contrib import messages
from django.contrib.contenttypes.models import ContentType
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from comments.forms import CommentForm
from comments.models import Comment
from .forms import PostForm
from .models import Post
from django.contrib.auth.models import User
def post_create(request):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
form = PostForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
# message success
messages.success(request, "Successfully Created")
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"form": form,
}
return render(request, "post_form.html", context)
def abc(request):
if request.method == "POST":
#Get the posted form
form = PostForm(request.POST)
if form.is_valid():
userc = form.cleaned_data['userc']
return render(request, 'post_detail.html', {"selected_user" : userc})
def post_detail(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
if instance.publish > timezone.now().date() or instance.draft:
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
share_string = quote_plus(instance.content)
initial_data = {
"content_type": instance.get_content_type,
"object_id": instance.id
}
form = CommentForm(request.POST or None, initial=initial_data)
if form.is_valid() and request.user.is_authenticated():
c_type = form.cleaned_data.get("content_type")
content_type = ContentType.objects.get(model=c_type)
obj_id = form.cleaned_data.get('object_id')
content_data = form.cleaned_data.get("content")
parent_obj = None
try:
parent_id = int(request.POST.get("parent_id"))
except:
parent_id = None
if parent_id:
parent_qs = Comment.objects.filter(id=parent_id)
if parent_qs.exists() and parent_qs.count() == 1:
parent_obj = parent_qs.first()
new_comment, created = Comment.objects.get_or_create(
user = request.user,
content_type= content_type,
object_id = obj_id,
content = content_data,
parent = parent_obj,
)
return HttpResponseRedirect(new_comment.content_object.get_absolute_url())
comments = instance.comments
context = {
"title": instance.title,
"instance": instance,
"share_string": share_string,
"comments": comments,
"comment_form":form,
}
return render(request, "post_detail.html", context)
def post_list(request):
today = timezone.now().date()
queryset_list = Post.objects.active() #.order_by("-timestamp")
if request.user.is_staff or request.user.is_superuser:
queryset_list = Post.objects.all()
query = request.GET.get("q")
if query:
queryset_list = queryset_list.filter(
Q(title__icontains=query)|
Q(content__icontains=query)|
Q(user__first_name__icontains=query) |
Q(user__last_name__icontains=query)
).distinct()
paginator = Paginator(queryset_list, 8) # Show 25 contacts per page
page_request_var = "page"
page = request.GET.get(page_request_var)
try:
queryset = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
queryset = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
queryset = paginator.page(paginator.num_pages)
context = {
"object_list": queryset,
"title": "List",
"page_request_var": page_request_var,
"today": today,
}
return render(request, "post_list.html", context)
def post_update(request, slug=None):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
instance = get_object_or_404(Post, slug=slug)
form = PostForm(request.POST or None, request.FILES or None, instance=instance)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
messages.success(request, "<a href='#'>Item</a> Saved", extra_tags='html_safe')
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"title": instance.title,
"instance": instance,
"form":form,
}
return render(request, "post_form.html", context)
def post_delete(request, slug=None):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
instance = get_object_or_404(Post, slug=slug)
instance.delete()
messages.success(request, "Successfully deleted")
return redirect("posts:list")
答案 0 :(得分:4)
到目前为止forms.py
和views.py
中的代码很好。但是,要在userc
和post_detail.html
模板中显示post_list.html
,您需要在提交表单时将字段保存到数据库中。
执行此操作的一种方法是向userc
模型添加Post
字段:
userc = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='userc', default=1)
添加到Post
posts/models.py
班级
python manage.py makemigrations posts
然后python manage.py migrate
(确保您首先在src
目录中)现在,在post_detail.html
模板中,您可以添加{{ instance.userc }}
以显示所选用户。
注意:related_name='userc'
是必需的,因为Post
已拥有用户模型的外键。
答案 1 :(得分:0)
将实例作为上下文变量传递。
context = {
"form": form,
"instance": instance
}
如果instance = None
不是POST,请先设置request.method
使其正常工作。模板只能访问在视图中作为上下文传递的变量。因此,在上下文中传递实例将允许您使用{{instance.userc}}
。
CodingforEntrepenuers是一个很好的教程,但我建议您更密切地关注并正确理解您的基础知识。