Django save()没有将表单保存到数据库

时间:2015-03-17 07:36:05

标签: python django model-view-controller

您好我将表单保存到数据库时遇到问题。当我尝试在 ads_history_add 视图中保存 AdHistoryForm 时,forim会正确呈现,但在提交之后,除了将我重定向到 ads_history_list 视图之外,没有任何结果。< / p>

此外,当我尝试使用空字段提交此表单时,它不显示任何错误(我将它们包含在模板中),所以也许它是验证的东西。

当我尝试在 ads_add 视图中添加广告时,一切正常。

你能帮助我吗?

models.py

from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User


class Ad(models.Model):
    title = models.CharField(max_length=128, verbose_name=_("name"), help_text=_("required"), unique=True)
    content = models.TextField(verbose_name=_("content"), blank=True)
    url = models.URLField(verbose_name=_("website"), blank=True)
    date_create = models.DateTimeField(auto_now_add=True)
    date_modify = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return self.title


class AdHistory(models.Model):
    ad = models.ForeignKey(Ad)
    user = models.ForeignKey(User)
    comment = models.TextField(verbose_name=_("comment"), help_text=_("required"))
    date_create = models.DateTimeField(auto_now_add=True)
    date_modify = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return self.comment

forms.py

from django import forms

from .models import Ad, AdHistory


class AdForm(forms.ModelForm):
    class Meta:
        model = Ad
        fields = ['title', 'content', 'url']


class AdHistoryForm(forms.ModelForm): 
    class Meta:
        model = AdHistory
        fields = ['comment']

views.py

from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required, user_passes_test
from django.utils.translation import ugettext as _

from .models import Ad, AdHistory
from .forms import AdForm, AdHistoryForm   



@login_required
@user_passes_test(lambda u: u.is_superuser)
def ads_list(request):
    ads_list = Ad.objects.all().order_by('-date_modify')
    context = {'list': ads_list}
    return render(request, 'ads_list.html', context)

@login_required
@user_passes_test(lambda u: u.is_superuser)
def ads_add(request):
    form = AdForm(request.POST or None)
    if form.is_valid():
        form.save()
        return redirect('ads_list')
    context = {'form': form}
    return render(request, 'ads_form_add.html', context)

@login_required
@user_passes_test(lambda u: u.is_superuser)
def ads_history_list(request, ad_id):
    ad = get_object_or_404(Ad, pk=ad_id)
    history_list = AdHistory.objects.select_related().filter(ad=ad).order_by('-id')
    context = {'list': history_list, 'object': ad}
    return render(request, 'ads_history_list.html', context)

@login_required
@user_passes_test(lambda u: u.is_superuser)
def ads_history_add(request, ad_id):
    ad = get_object_or_404(Ad, pk=ad_id)
    f = AdHistoryForm(request.POST or None)
    if f.is_valid():
        new_entry = f.save(commit=False)
        new_entry.ad = ad
        new_entry.user = request.user
        new_entry.save()
        return redirect('ads_history_list', ad_id)
    context = {'form': f, 'object': ad}
    return render(request, 'ads_history_add.html', context)

urls.py

rom django.conf.urls import patterns, url
from django.contrib.auth.decorators import login_required

from ads import views

urlpatterns = patterns(
    '',
    url(r'^$', views.ads_list, name="ads_list"),
    url(r'^add/', views.ads_add, name="ads_add"),
    url(r'^(?P<ad_id>\d+)/history/$', views.ads_history_list, name="ads_history_list"),
    url(r'^(?P<ad_id>\d+)/history/add$', views.ads_history_add, name="ads_history_add"),
)

两个表单模板都继承自此模板:

<form role="form" method="post" action=".">

    {% csrf_token %} 

    <table class="table table-bordered crm-form">

        {% for field in form.visible_fields %} 

        <tr>
            <th>
                {{ field.label }}
            </th>
            <td>
                {{ field }}

                <small>{{ field.help_text }}</small>

                {% if field.errors %}
                <div class="alert alert-danger" role="alert">{{ field.errors }}</div>
                {% endif %}

            </td>

        </tr>

        {% endfor %}
    </table>

     <button type="submit" name="submit" class="btn btn-success crm-float-right">
        {% trans 'Save' %}
    </button>

</form>

1 个答案:

答案 0 :(得分:2)

POST请求永远不会到达ads_history_add视图,因为您的ads_history_add网址格式没有尾部斜杠。如果没有尾部斜杠,action="."模板中的ads_form_add.html会导致POST (?P<ad_id>\d+)/history/

添加尾部斜杠,一切都应按预期工作。或者,您可以省略action属性以告知浏览器POST到当前URL。

另请注意,尽管此处不相关,但显示{{ form.non_field_errors }}可能是个好习惯。