我正在尝试保存 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>
视图.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))
表格.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')
模型.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() 并告诉他们我在模型“部分、用户和标题”中拥有的所有字段?我认为错误是因为“部分”和“用户”字段没有传递给保存方法。我怎样才能传递这个值?
另一个问题:我这样做是正确的,还是有更简单的方法来实现我想要实现的目标?
最好的祝福