1

我正在申请食品食谱,并尝试在食谱中执行相同的 html 并在模式窗口中包含评论,问题是当我提交模板失败并且没有将评论保存在数据库中

网址.py

urlpatterns = patterns('recetas.apps.menus.views',
    url(r'^recetas/$','recetas_view',name='vista_recetas'),
    url(r'^reporte/$','reporte_receta',name='receta_reporte'),
    url(r'^receta/(?P<id_receta>\d+)$','detalle_receta', name='vista_detalle'),
)

调用此 url 的 html 代码

<td><a href='/receta/{{ receta.id }}'>{{ receta.titulo }}</a></td>

视图.py

def detalle_receta(request, id_receta):
    dato = get_object_or_404(Receta, pk=id_receta)
    comentarios = Comentario.objects.filter(receta=dato)
    if request.POST:
        if request.POST.get('cancel', id_receta):
            return HttpResponseRedirect('/receta/{0}'.format(id_receta))
        form = ComentarioForm(request.POST)
        if form.is_valid():
           form.save()
           return HttpResponseRedirect('/receta/{0}'.format(id_receta))
    else:
        form = ComentarioForm(initial={'receta': id_receta})

    cxt = {'receta':dato,'comentarios':comentarios,'form':form}
    return render_to_response('menus/receta.html', cxt, context_instance=RequestContext(request))

receta.html

{% extends 'base.html' %}
{% block titulo %}{{ receta.titulo }}{% endblock titulo %}
{% block estatico %}
<link rel='stylesheet' href='{{ STATIC_URL }}css/receta.css' type='text/css'>
<link rel='stylesheet' href='{{ STATIC_URL }}css/modal.css' type='text/css'>
<script type='text/javascript'>

    function despliegaModal(valor) {
        var elem = document.getElementById("bgVentanaModal");
        elem.style.visibility = valor;
        }
</script>
{% endblock estatico %}
{% block contenido %}
<div id="bgVentanaModal">
    <div id="ventanaModal">
        <form action="/receta/{{ receta.id_receta }}" method="POST">
            {% csrf_token %}
            {{ form.as_p }}
            <input type="submit" value="Grabar">
            <input name="cancel" type="submit" value="Cancelar">
        </form>
    </div>
</div>
<div id=receta>
    <div id="nombre_receta">
        <h1>{{receta.titulo|title}}</h1>
        <hr>
    </div>
    <div id='ingredientes'>
        <h2>Ingredientes</h2>
        <p>{{ receta.ingredientes }}</p>
    </div>
    <div id='imagen'>
        <img src='{{MEDIA_URL}}{{receta.imagen}}' width="480" height="300" >
    </div>
    <div id='preparacion'>
        <h2>Preparación</h2>
        <p>{{ receta.preparacion }}</p>
    </div>
    <div id='comentarios'>
        <h2>Comentarios</h2>
        {% for item in comentarios %}
            <p>{{ item.texto}}</p>
        {% empty %}
            <p>Sin Comentarios registrados</p>
        {% endfor %}
        {% if user.is_authenticated %}
            <a href="javascript:despliegaModal('visible');">Agregue su comentario</a>
        {% endif %}
    </div>
    <div id="pie">
        <hr>
        <p>Receta Registrada el {{ receta.tiempo_registro|date:'SHORT_DATETIME_FORMAT' }} por {{ receta.usuario }}</p>
    </div>
</div>
{% endblock contenido %}

一切正常,直到我给出取消键,不验证 POST。

4

2 回答 2

1

我相信问题出在你的view.py. 具体在这部分:

if request.POST.get('cancel', id_receta):
    return HttpResponseRedirect('/receta/{0}'.format(id_receta))

if永远不会产生False价值,因此,您的评论将永远不会被保存。这与dict.get函数的工作方式有关:

获取(键[,默认值])

如果键在字典中,则返回键的值,否则返回默认值。如果未给出默认值,则默认为 None,因此此方法永远不会引发 KeyError。

因此,如果单击,Grabar您将获得默认值 ( id_receta)。请尝试以下操作:

if request.POST.get('cancel'): # Default to None
    return HttpResponseRedirect('/receta/{0}'.format(id_receta))

Cancelar一种解决方法是在您单击模板时使用带有一些 JavaScript 的按钮来重定向:

视图.py

def detalle_receta(request, id_receta):
    dato = get_object_or_404(Receta, pk=id_receta)
    comentarios = Comentario.objects.filter(receta=dato)
    if request.POST:
        # if request.POST.get('cancel', id_receta):
        #    return HttpResponseRedirect('/receta/{0}'.format(id_receta))
        form = ComentarioForm(request.POST)
        if form.is_valid():
           form.save()
           return HttpResponseRedirect('/receta/{0}'.format(id_receta))
    else:
        form = ComentarioForm(initial={'receta': id_receta})

    cxt = {'receta':dato,'comentarios':comentarios,'form':form}
    return render_to_response('menus/receta.html', cxt, context_instance=RequestContext(request))

receta.html

...
...
<form action="/receta/{{ receta.id_receta }}" method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Grabar">
    <input type="button" value="Cancelar" onclick="window.location.href='/receta/{{ dato.id }}'"/>>
</form>
...
...

当然,您应该使用get_absolute_url而不是硬编码 URL。

于 2012-09-05T20:45:25.867 回答
0

感谢Cesar的帮助,您的回答对我有帮助,但我的错误在receta.html中的变量中

{{ receta.id }}和按钮中的相同正确的是

<form action="/receta/{{ receta.id }}" method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Grabar"/>
    <input type="button" value="Cancelar" onclick="window.location.href='/receta/{{ receta.id }}'"/>
</form>

感谢您的帮助和发现错误的朋友

于 2012-09-07T21:02:09.933 回答