简体   繁体   English

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

[英]Django save() is not saving form to database

Hello I have problem with saving forms to database. 您好,我在将表单保存到数据库时遇到问题。 When I try to save the AdHistoryForm in ads_history_add view the forim is rendered correctly but after submitting nothing happens aside of redirecting me to ads_history_list view. 当我尝试在ads_history_add视图中保存AdHistoryForm时格式正确呈现,但是提交后,除了将我重定向到ads_history_list视图外,什么都没有发生。

In addition when I try to submit this form with empty field it doesnt show any errors (I included them in template), so maybe it is validation thing. 另外,当我尝试使用空白字段提交此表单时,它没有显示任何错误(我将它们包括在模板中),因此也许是验证性的事情。

When I try to add Ad in ads_add view everything is ok. 当我尝试在ads_add视图中添加广告时 ,一切正常。

Can you help me? 你能帮助我吗?

models.py 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 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 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"),
)

both form templates inherits from this template: 这两个表单模板都从该模板继承:

<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>

The POST request never reaches your ads_history_add view because your ads_history_add URL pattern does not have a trailing slash. POST请求永远不会到达您的ads_history_add视图,因为您的ads_history_add网址格式没有斜杠。 Without the trailing slash, action="." 如果没有斜杠,请使用action="." in the ads_form_add.html template results in a POST to (?P<ad_id>\\d+)/history/ ads_form_add.html模板中的结果导致对(?P<ad_id>\\d+)/history/

Add the trailing slash and everything should work as expected. 添加尾部斜杠,所有内容均应按预期工作。 Alternatively, you could omit the action attribute to tell the browser to POST to the current URL. 另外,您可以省略action属性,以告诉浏览器将POST张贴到当前URL。

Also note that, although not relevant here, it is probably a good habit to display {{ form.non_field_errors }} . 另请注意,尽管此处不相关,但显示{{ form.non_field_errors }}可能是一个好习惯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM