Django ModelForm字段无法呈现

时间:2015-12-27 00:34:39

标签: python django modelform

我正在尝试创建一个允许用户发表评论的模型表单,在feeds.html模板中不显示forms.py字段列表中指定的表单字段。我已经检查了Django关于模型表格的文档,但看起来我没有做错任何事情。

Models.py

from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from time import time

    class Feed(models.Model):
    author = models.ForeignKey(User)
    caption = models.CharField(max_length=300)
    audio_file = models.FileField(upload_to=get_upload_file_name)
    pub_time = models.DateTimeField(default=timezone.now)
    likes = models.IntegerField(default=0)

    def __unicode__(self):
        return unicode(self.caption)

class Comment(models.Model):
    username = models.CharField(max_length=100)
    body = models.TextField()
    pub_time = models.DateTimeField(default=timezone.now)
    feed = models.ForeignKey(Feed)

    def __unicode__(self):

forms.py

from django.forms import ModelForm, Textarea
from feed.models import Feed, Comment

class CommentForm(ModelForm):
    class Meta:
        model = Comment
        fields = ['body']
        widgets = {
            'body': Textarea(attrs={'cols':80, 'rows': 20}),
        }

Views.py

from django.shortcuts import render, render_to_response
from models import Feed, Comment
from django.http import HttpResponse, HttpResponseRedirect
from django.core.context_processors import csrf
from django.utils import timezone
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from feed.forms import CreateFeedForm

def add_comment(request, feed_id):
    p = Feed.objects.get(id=feed_id)

    if request.method == "POST":
        f = CommentForm(request.POST)
        if f.is_valid():
            c = f.save(commit=False)
            c.username = User.objects.get(username = request.user.username)
            c.pub_time = timezone.now()
            c.feed = p
            c.save()

            return HttpResponseRedirect('/feeds/')
    else:
        f = CommentForm()

    args = {}
    args.update(csrf(request))
    args['CForm'] = f

    return HttpResponseRedirect('/feeds/')

Urls.py

from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^accounts/', include('registration.backends.default.urls')),

    url(r'^feeds/', 'feed.views.feeds', name='feeds'),
    url(r'^feed/(?P<feed_id>\d+)/$', 'feed.views.feed', name='feed'),
    url(r'^upload/', 'feed.views.upload', name='upload'),
    url(r'^like_feed/(?P<feed_id>\d+)/$', 'feed.views.like_feed', name='like_Feed'),
    url(r'^add_comment/(?P<feed_id>\d+)/$', 'feed.views.add_comment'),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Feeds.html

{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block head_title %}Welcome | {% endblock %}

{% block sidebar %}
{% if request.user.is_authenticated %}
    <!-- side bar menu  -->
    <div class="col-md-3">
        <div class="list-group">
            <a class="list-group-item" href="{% url 'feeds' %}"><i class="fa fa-home fa-fw"></i>&nbsp; Home</a>
            <a class="list-group-item" href="#uploadmodal" data-toggle="modal" data-target="#uploadmodal"><i class="fa fa-upload fa-fw"></i>&nbsp; upload</a>
            <a class="list-group-item" href="#"><i class="fa fa-microphone fa-fw"></i>&nbsp; Record</a>
        </div>
    </div>


{% block feeds %}
<div class="row">
    <div class="col-md-4 col-md-offset-1">
        {% if request.user.is_authenticated %}
            {% if feeds.count > 0 %}
                {% for feed in feeds %}
                    <div>
                        <h4>{{ feed.author }}</h4s>
                        <p><a href="/feed/{{ feed.id }}">{{ feed.caption }}</a></p>
                        <p>
                            <audio controls>
                                 <source src="{{feed.audio_file.url }}" type="audio/mp3">
                    Your browser does not support the audio element.
                            </audio>
                        </p>
                        <p><a href="/like_feed/{{ feed.id }}">Like(s)</a> {{ feed.likes }} &nbsp;&nbsp;&nbsp;&nbsp;</p>

                        <form action="/add_comment/{{ feed.id }}/" method="POST">{% csrf_token %}
                            {{ cForm|crispy }}
                            <input class="btn btn-primary" type="submit" value="Comment" name="submit" />
                        </form>
                    </div>
                {% endfor %}
            {% endif %}
        {% endif %}
    </div>
</div>
{% endblock %}

1 个答案:

答案 0 :(得分:1)

请在问题中添加feeds视图。

这样的事情应该适用于添加评论:

def add_comment(request, feed_id, ):
    try:
        feed_instance = Feed.objects.get(id=feed_id)
    except Feed.DoesNotExist:
        raise Http404

    form = CommentForm(request.POST or None)

    if form.is_valid():
        comment = form.save(commit=False)
        comment.username = request.user
        comment.pub_time = timezone.now()
        comment.feed = feed_instance
        comment.save()

    return HttpResponseRedirect('/feeds/')

以及feeds视图:

def feeds(request):
    context = {
        'form': CommentForm(),
        'feeds': Feed.objects.all(),
    }

    return render(request, 'feeds.html', context)