Django ModelForm不保存数据 [英] Django ModelForm not saving data
问题描述
我尝试了以下帖子中的解决方案:
I've tried solutions from the following posts:
我正在尝试将ModelForm中的数据保存到模型中。
I'm trying to save data from a ModelForm into the model.
models.py:
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面板。知道为什么吗?
However, on redirect, it doesn't save the form into the model which I'm checking from both PHPMyAdmin (using a MySQLdb) and the Django Admin panel. Any idea why?
推荐答案
您要发布到 / testimonials / thanks /
更改为您的 add_testimonial
路由,以使您的视图处理POST。因此,解决方案是更改模板的表单标签中的 action
值。
You are POSTing to /testimonials/thanks/
which should be changed to your add_testimonial
route to have your view handle the POST. So, the solution is to change the action
value in your template's form tag.
如果您可以发布相关的您可以从urls.py中获取代码。对于action属性的值,我可以提供更具体的答案。
If you can post the relevant code from your urls.py I can provide a more specific answer as to what the value of the action attribute should be.
更新
发布有效表单后,重定向将在您的视图中发生。将模板的操作属性值更改为:
The redirect will happen in your view when a valid form is POSTed. Change your template's action attribute value to:
<form id="testimonial_form" method="POST" action="{% url 'add_testimonial' %}">
您认为:
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('testimonial_thanks'))
并确保在视图中包括以下导入:
And make sure you include the following import in your view:
from django.core.urlresolvers import reverse
更新2
在模板中显示表单错误:
Display your form errors in your template:
<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。因此,将 verified
表单字段更改为:
Now that you can see your form errors, you will need to provide your default value to the hidden field, and there's no need to make it a ChoiceField if the user has no choice (it's hidden!). So change the verified
form field to:
verified = forms.CharField(widget=forms.HiddenInput(), initial='no')
另外,这将是一个在字段中验证该值的一个好主意,因为即使该字段被隐藏,一个进取的,邪恶的用户仍然可以发布其他值。
Also, it would be a good idea to verify the value in your view since even though the field is hidden, an enterprising, evil user can still POST other values.
这篇关于Django ModelForm不保存数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!