Django ModelForm没有保存数据

时间:2014-05-15 21:44:06

标签: python django

我尝试过以下帖子的解决方案:

Saving data from ModelForm:没有用

ModelForm data not saving django:没有用。

我正在尝试将ModelForm中的数据保存到模型中。

models.py:

class Testimonials(models.Model):
    name = models.CharField(max_length=128)
    credentials = models.CharField(max_length=128)
    test = models.CharField(max_length=2000)
    id = models.AutoField(primary_key=True)
    NO = 'NO'
    YES = 'YES'
    APPROVAL = ((NO, 'no'), (YES, 'yes'))
    verified = models.CharField(choices=APPROVAL, default=NO, max_length=3) #Field for making sure only verified testimonials are displayed

    def __unicode__(self):
        return self.id

forms.py:

class TestimonialForm(forms.ModelForm):
    name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control input-area', 'placeholder': 'Enter your name'}), required=True)
    credentials = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control input-area', 'placeholder': 'Enter your designation'}), required=True)
    test = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control test-form-area', 'placeholder': 'Testimonial', 'rows': '5'}), required=True)
    verified = forms.ChoiceField(widget=forms.HiddenInput())

    class Meta:
        model = Testimonials  

views.py

def add_testimonial(request):
    context = RequestContext(request)
    if request.method == 'POST':
        form = TestimonialForm(request.POST)

        if form.is_valid():
            form.save(commit=True)
            return HttpResponseRedirect('/testimonials/thanks/')
        else:
            print form.errors

    else:
        form = TestimonialForm()

    return render_to_response('templates/add_testimonial.html', {'form': form}, context)

模板:

<form id="testimonial_form" method="POST" action="/testimonials/thanks/">
    {% csrf_token %}
    {% for hidden in form.hidden_fields %}
        {{ hidden }}
    {% endfor %}
    {% for field in form.visible_fields %}
        {{ field.help_text}}
        {{ field }}
    {% endfor %}
    <input type="submit" name="submit" value="Add testimonial" class="btn btn-info test-button"/>
</form>

编辑:

urls.py

url(r'^testimonials/all/', views.testimonials, name='testimonial'),
url(r'^testimonials/thanks/', views.testimonials_thanks, name='testimonial_thanks'),
url(r'^add_testimonial', views.add_testimonial, name='add_testimonial'),

但是,在重定向时,它不会将表单保存到我正在从PHPMyAdmin(使用MySQLdb)和Django Admin面板检查的模型中。知道为什么吗?

1 个答案:

答案 0 :(得分:3)

您要发布到/testimonials/thanks/,应将其更改为add_testimonial路由,以使您的视图处理POST。因此,解决方案是更改模板的表单标记中的action值。

如果您可以发布urls.py中的相关代码,我可以提供一个更具体的答案,说明action属性的值应该是什么。

<强>更新

当有效表单张贴时,重定向将在您的视图中发生。将模板的操作属性值更改为:

<form id="testimonial_form" method="POST" action="{% url 'add_testimonial' %}">

在您看来:

if form.is_valid():
    form.save()
    return HttpResponseRedirect(reverse('testimonial_thanks'))

并确保在视图中包含以下导入:

from django.core.urlresolvers import reverse

更新2

在模板中显示表单错误:

<form id="testimonial_form" method="POST" action="{% url 'add_testimonial' %}">
    {% csrf_token %}
    {% if form.non_field_errors %}
        <div class="form-group text-error">
            {{ form.non_field_errors }}
        </div>
    {% endif %}

    {% for hidden in form.hidden_fields %}
        {{ hidden }}
    {% endfor %}
    {% for field in form.visible_fields %}
        {{ field.help_text}}
        {{ field }}
        {% if field.errors %}
            <span>{{ field.errors|striptags }}</span>
        {% endif %}
    {% endfor %}
    <input type="submit" name="submit" value="Add testimonial" class="btn btn-info test-button"/>
</form>

更新3

既然你可以看到你的表单错误,你需要在隐藏字段中提供你的默认值,如果用户别无选择,就不需要把它变成一个ChoiceField(它是's&#39; s隐!)。因此,请将verified表单字段更改为:

verified = forms.CharField(widget=forms.HiddenInput(), initial='no')

此外,验证视图中的值是个好主意,因为即使该字段被隐藏,一个有进取心的,邪恶的用户仍然可以POST其他值。