我正在尝试保存ModelForm,但是我收到了一个错误:
InternalError at /submeter/anuncio/
current transaction is aborted, commands ignored until end of transaction block
我会尝试解释我在做什么。
好的,我有5个模型需要一次保存在一个表单中。我正在测试保存两个模型,但正如我所说,我在保存方法上遇到错误。作为初学者,我在实现任务的最佳方式上有点迷失。
我做了什么:
模板:
<form method="post" action="/submeter/anuncio/">{% csrf_token %}
{{form_main}}
{{form_bicyclead}}
<input type="hidden" name="section" value="5" />
<input type="submit">
</form>
Views.py:
def submit_data_entry_view(request):
if request.method == 'GET': #first time rendering the form
form_main = MainForm()
form_bicyclead = BicycleAdForm()
return render_to_response('app_t/submit_data_entry.html', {'form_main': form_main, 'form_bicyclead': form_bicyclead}, context_instance=RequestContext(request))
def submit_ad_view(request):
if request.method == 'POST':
post_values = request.POST.copy()
post_values['user'] = request.user.username
post_values['bicycleadtype'] = 2
post_values['bicycleaditemkind'] = 4
post_values['bicycleadcondition'] = 2
post_values['city'] = 4803854
form_main = MainForm(post_values)
form_bicyclead = BicycleAdForm(post_values)
if form_main.is_valid() and form_bicyclead.is_valid():
form_main.save()
#form_bicyclead.save()
resultado = 'valid'
else:
resultado = 'n_valid'
pdb.set_trace()
return render_to_response('app_t/submit_ad.html', {'resultado': resultado}, context_instance=RequestContext(request))
Forms.py:
class MainForm(forms.ModelForm):
class Meta:
model = Main
exclude = ('user', 'section')
class BicycleAdForm(forms.ModelForm):
class Meta:
model = BicycleAd
exclude = ('main', 'bicycleadtype', 'bicycleaditemkind', 'bicycleadcondition', 'city')
Models.py:
class Main(models.Model):
section = models.ForeignKey(Section)
user = models.ForeignKey(User)
title = models.CharField(max_length=250)
date_inserted = models.DateTimeField(auto_now_add=True)
date_last_update = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.title
class Meta:
ordering = ['date_inserted']
class BicycleAd(models.Model):
main = models.ForeignKey(Main)
bicycleadtype = models.ForeignKey(BicycleAdType)
bicycleaditemkind = models.ForeignKey(BicycleAdItemKind) # MPTT Model
bicycleadcondition = models.ForeignKey(BicycleAdCondition)
country = models.ForeignKey(GeonamesCountry)
city = models.ForeignKey(GeonamesLocal)
date_inserted = models.DateTimeField(auto_now_add=True)
date_last_update = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['date_inserted']
我的问题是:如何“覆盖”views.py中的form_main.save()并告诉他们模型“section,user和title”中的所有字段?我认为错误是由于字段“section”和“user”没有传递给save方法。我怎样才能传递这个值?
另一个问题:我是以正确的方式做到这一点,还是有更容易,更简单的方法来实现我想要实现的目标?
最好的问候
答案 0 :(得分:2)
将模型表单修改为:
class MainForm(forms.ModelForm):
def __init__(self, *args, **kw):
self.user = kw.pop('user')
self.section = kw.pop('section')
super(MainForm).__init__(*args, **kw)
class Meta:
model = Main
exclude = ('user', 'section')
def save(self, *args, **kw):
instance = super(MainForm).save(commit=False)
instance.user = self.user
instance.section = self.section
instance.save()
return instance
现在,您需要在视图中创建表单的intance时传递user
和section
:
form_main = MainForm(request.POST or None, user=request.user, section=section)
答案 1 :(得分:2)
我的方法是替换此代码:
def submit_ad_view(request):
if request.method == 'POST':
post_values = request.POST.copy()
post_values['user'] = request.user.username
post_values['bicycleadtype'] = 2
post_values['bicycleaditemkind'] = 4
post_values['bicycleadcondition'] = 2
post_values['city'] = 4803854
form_main = MainForm(post_values)
由:
def submit_ad_view(request):
if request.method == 'POST':
model = Main() #if model exists get it!
#Notice, Main is the name of your model.
model.user = request.user.username
...
model.bicycleaditemkind = 4
...
form_main = MainForm(request.POST, instance = model )
您可以在Creating forms from models django doc。
上了解详情