我已经阅读了其他关于表格数据未保存的帖子,但似乎无法查明我自己的问题。感觉它的东西非常基本我不见了。非常感谢帮助谢谢。
#model
class AboutMe(models.Model):
title = models.CharField(max_length=30)
user = models.ForeignKey(User)
post = models.TextField()
created = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.title
#form
class AboutMeForm(forms.ModelForm):
class Meta:
model = AboutMe
fields = ['title', 'post']
#view
def post_line(request):
if request.method == 'POST':
form = AboutMeForm(request.POST)
if form.is_valid():
new_about = form.save(commit=False)
new_about.user = request.user
new_about.save()
return HttpResponseRedirect('index.html')
else:
form = AboutMeForm()
return render_to_response('post_line.html', locals(), context_instance=RequestContext(request))
#template:
<div class="post_line">
<form enctype="multipart/form-data" action='.' method="post">{% csrf_token %}
{{ form.as_table }}
<input type="submit" name="submit" value="post" />
</form>
</div>
答案 0 :(得分:0)
我无法在这里发表评论所以我在这里写作
1)HttpResponseRedirect('index.html')
这里错了,你必须传递一些网址,如
/ login /或/ profile /
2)请打印您的表格,如
打印表单并检查您获得的是所有字段都有效或缺少任何字段
然后告诉表单错误
答案 1 :(得分:0)
尝试这样做:
forms.py
class AboutMeForm(ModelForm):
class Meta:
model=AboutMe
fields = YOUR FIELDS
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(AboutMeForm, self).__init__(*args, **kwargs)
def save(self, commit=True):
instance = super(AboutMeForm, self).save(commit=False)
if self.user:
instance.user = self.user
return instance.save()
在views.py上:
def post_line(request):
if request.method == 'POST':
form = AboutMeForm(request.POST)
if form.is_valid():
new_about = form.save()
return HttpResponseRedirect('index.html')
else:
form = AboutMeForm()
return render_to_response('post_line.html', locals(), context_instance=RequestContext(request))