ModelForm数据不保存django [英] ModelForm data not saving django
本文介绍了ModelForm数据不保存django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经阅读了关于表单数据不保存的其他帖子,但似乎无法确定自己的问题。有一种感觉,它的东西真的很基本,我失踪了。真的感谢帮助谢谢。
I've read the other posts on here about form data not saving, but can't seem to pinpoint my own problem. Have a feeling its something really basic I'm missing. Really appreciate the help thanks.
#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>
推荐答案
尝试这样做:
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))
这篇关于ModelForm数据不保存django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文