【发布时间】:2017-08-08 18:15:10
【问题描述】:
我有一个登录系统,您需要登录才能提交新帖子。我的“新帖子”页面/表单工作正常,用户提交的内容已正确发布在数据库中,如何在主页上显示该内容时只显示标题和副标题(它们是字符字段)而不是帖子的正文(这是一个文本字段)。
inde.html
{% extends "blog/base.html" %}
{% block body_block %}
<div class="left">
{% if userposts %}
{% for posts in userposts %}
<div class="front-post">
<h2 class="post-title">{{ posts.post_title }}</h2>
<h3 class="post-sub-title">{{ posts.post_sub_title }}</h3>
<p class="post-author">{{ post.post_author }}</p>
<p class="post-date">{{ post.post_date }}</p>
<p class="post-body">{{ post.post_body }}</p>
</div>
{% endfor %}
{% endif %}
</div>
<div class="right">
<p>SIDE BAR</p>
</div>
{% endblock %}
views.py
from django.shortcuts import render
from blog.forms import UserForm,UserProfileInfoForm,AddPost
from blog.models import UserPosts
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect,HttpResponse
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
# Create your views here.
def index(request):
post_list = UserPosts.objects.order_by('post_date')
post_dict = {'userposts':post_list}
return render(request, 'blog/index.html',context=post_dict)
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserProfileInfo(models.Model):
user = models.OneToOneField(User)
portfolio_site = models.URLField(blank=True)
profile_pic = models.ImageField(upload_to='profile_pics',blank='True')
def __str__(self):
return self.user.username
class UserPosts(models.Model):
post_title = models.CharField(max_length=100,unique=True)
post_sub_title = models.CharField(max_length=250,unique=False)
post_author = ''
post_date = models.DateField(auto_now=True)
post_body = models.TextField(max_length=1000,unique=False)
def __str__(self):
return str(self.post_title)
forms.py
from django import forms
from django.contrib.auth.models import User
from blog.models import UserProfileInfo,UserPosts
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta():
model = User
fields = ('username','email','password')
class UserProfileInfoForm(forms.ModelForm):
class Meta():
model = UserProfileInfo
fields = ('portfolio_site','profile_pic')
class AddPost(forms.ModelForm):
class Meta():
model = UserPosts
fields = '__all__'
【问题讨论】:
-
只是一个错字吗?
posts.post_sub_title与post.post_body -
可能是因为您在
for循环中输入了post而不是posts?