Django2 实验添加entry条目,没有form文本框显示

Moose_Wang 发布于 2018/04/27 11:12
阅读 793
收藏 0

最近根据《python编程从入门到实践》编写python web程序,但是出现了一些问题:

我对代码经过多次核对,也参考了django1.7和2的差异,并对相应的代码做了调整,经过几天的分析和问题查找,感觉add_entry中的{{ form.as_p }}根本没有生效,至今依旧没能解决,望各位技术大牛能做些许提点,不胜感激,问题描述如下:

“学习笔记”编程练习,有两大模块,一个topic,一个entry,一个topic可包含多个entry条目。功能包括:显示topics,新增topic,显示entries,新增entry(异常),编辑entry

就是add_entry功能的输入文本框无法显示出来(意味着无法添加条目),以下是我的各代码块:

models.py

from django.db import models
from django.contrib.auth.models import User

# Create your models here.
class Topic(models.Model):
    """用户学习的主题"""
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey(User,on_delete=models.CASCADE)
    """
    class Meta:
        verbose_name_plural = 'topicss'
    """
    def __str__(self):
        """返回模型的字符串表示"""
        return self.text
    
class Entry(models.Model):
    """学到的有关某个主题的具体知识"""
    topic = models.ForeignKey(Topic,on_delete=models.CASCADE)
    text = models.TextField()
    #text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)
    
    #meta存储用于管理模型的额外信息,这里相当于设置一个别名
    class Meta:
        verbose_name_plural = 'entries'  
    def __str__(self):
        """返回模型的字符串表示"""
        if len(self.text)>50:
            return self.text[:50] + "..."
        else:
            return self.text

forms.py

from django import forms
from .models import Topic,Entry

class TopicForm(forms.ModelForm):
    class Meta:
        model = Topic
        fields = ['text']
        labels = {'text':''}
        
class EntryForm(forms.ModelForm):
    class Meta:
        model = Entry
        fields = ['text']
        labels = {'text':''}
        widgets = {'text':forms.Textarea(attrs={'cols':80})}

views.py

from django.shortcuts import render
from .models import Topic,Entry
from django.http import HttpResponseRedirect,Http404
from django.urls import reverse
from .forms import TopicForm,EntryForm
from django.contrib.auth.decorators import login_required


# Create your views here.

def index(request):
    """学习笔记的主页"""
    return render(request,'new_learninglogs/index.html')

@login_required
def topics(request):
    """主题页面"""
    #topics = Topic.objects.order_by('date_added')
    """只显示所属用户的所有主题"""
    topics = Topic.objects.filter(owner=request.user).order_by('date_added')
    context ={'topics':topics}
    return render(request,'new_learninglogs/topics.html',context)

def topic(request,topic_id):
    """显示单个主题及其所有的条目"""
    topic = Topic.objects.get(id=topic_id)
    #确认请求的主题属于当前用户
    if topic.owner != request.user:
        raise Http404
    entries = topic.entry_set.order_by('-date_added')
    context = {'topic':topic,'entries':entries}
    return render(request,'new_learninglogs/topic.html',context)

def new_topic(request):
    """添加新主题"""
    if request.method != 'POST':
        #未提交数据:创建一个新表单
        form = TopicForm()
    else:
        form = TopicForm(request.POST)
        if form.is_valid():
            new_topic = form.save(commit=False)
            new_topic.owner = request.user
            new_topic.save()
            #form.save()
            return HttpResponseRedirect(reverse('new_learninglogs:topics'))
        
    context = {'form':form}
    return render(request,'new_learninglogs/new_topic.html',context)

def new_entry(request,topic_id):
    """特定的主题中添加条目"""
    topic = Topic.objects.get(id=topic_id)
    
    if request.method == 'GET':
        form = EntryForm()
    elif request.method == 'POST':
        form = EntryForm(request.POST)
        if form.is_valid():
            new_entry = form.save(commit=False)
            new_entry.topic = topic
            new_entry.save()
            return HttpResponseRedirect(reverse('new_learninglogs:topic',args=[topic_id]))

    
    context = {'topic':topic,'from':form}
    return render(request,'new_learninglogs/new_entry.html' ,context)

def edit_entry(request,entry_id):
    """编辑既有条目"""
    entry = Entry.objects.get(id=entry_id)
    topic = entry.topic
    #限制用户编辑
    if topic.owner != request.user:
        raise Http404
    
    if request.method != 'POST':
        #初次请求,使用当前条目填充表单
        form = EntryForm(instance=entry)
    else:
        #post提交的数据,对数据进行处理
        form = EntryForm(instance=entry,data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('new_learninglogs:topic',args=[topic.id]))
    context ={'entry':entry,'topic':topic,'form':form}
    return render(request,'new_learninglogs/edit_entry.html',context)

new_entry.html

{% extends "new_learninglogs/base.html" %}
{% load bootstrap3 %}

{% block header %}
  <h2>Add an new Entry<h2>
{% endblock header %}

{% block content %}
  <h3><a href="{% url 'new_learninglogs:topic' topic.id %}">{{ topic }}</a></h3>
  <form action="{% url 'new_learninglogs:new_entry' topic.id %}" method='post' class="form">
   {% csrf_token %}
   {{ form.as_p }}
   
   {% buttons %}
   <button name='submit' class="btn btn-primary">add entry</button>
   {% endbuttons %}
  </form>
{% endblock content %}

new_topic.html

{% extends "new_learninglogs/base.html" %}
{% load bootstrap3 %}

{% block header%}
  <h2>Add a new topic</h2>
{% endblock header %}

{% block content %}
 
 <form action="{% url 'new_learninglogs:new_topic' %}" method='post' class="form">
   {% csrf_token %}
   {% bootstrap_form form %}
   <!-- {{ form.as_p }} -->
   {% buttons %}
   <button name="submit" class="btn btn-primary">add topic</button>
   {% endbuttons %}
 </form>
{% endblock content %} 

add_topic显示结果:

add_entry显示结果:

结果没有文本框,麻烦有知道的大牛帮忙提点指教,非常感谢

加载中
0
l
littlefatpat

您好!我也遇到同样的问题,请问解决没?可以分享一下吗?

0
拾光TM
拾光TM

你尝试把new_entry.html里面的   {{ form.as_p }}给注释掉看看,对比两者除了部分代码不同,其他应该一样的

l
littlefatpat
赞!感谢您的回答,我根据你的思路,一开始还是没发现,我找了别人的代码逐行复制,终于发现还是{{ form.as_p }}搞事情,我写成了{{ forms.as_p }},还是菜鸟的老问题,我这段时间每天花十分钟去检查这个问题都没发现,今天终于解决了,感谢您!
0
l
littlefatpat

然后我想我应该发现题主的问题出在哪里了,经过对比,views.py文件中标红的 if request.method == 'GET':  应该是有问题,应该是if request.method !='POST': ,请题主确认,谢谢!

返回顶部
顶部