我有一个名为 outage_name 的 ModelChoiceField 。我还有一个简单的表单,允许您从列表中选择项目。 ModelChoiceField是从MySQL DB中提取的。此查询集位于forms.py
中outage_name = forms.ModelChoiceField(queryset = Outage.objects.filter(published = True)
models.py如下所示。
from django.db import models
from django.contrib.auth.models import User
class Outage(models.Model):
outage_name = models.CharField(max_length=60, unique=True)
published = models.BooleanField()
def __unicode__(self):
return self.outage_name
class Detail(models.Model):
detail = models.CharField(max_length=60, unique=True)
user = models.ForeignKey(User)
outage = models.ForeignKey(Outage)
def __unicode__(self):
return self.outage
当我从列表中选择并提交表单时,我似乎无法弄清楚如何匹配列表中选择的 outage = models.ForeignKey(Outage)。到正确的 outage_name 。在我的views.py中,我可以对id进行硬编码,然后提交到数据库,一切正常。
def turnover_form(request):
if request.user.is_authenticated():
if request.method == 'POST':
form = TurnoverForm(request.POST)
if form.is_valid():
details = Detail.objects.get_or_create(
detail = form.cleaned_data['detail'],
user = request.user,
outage = Outage.objects.get(pk=1))
return HttpResponseRedirect('/turnover/user/')
else:
form = TurnoverForm()
variables = RequestContext(request, {'form': form})
return render_to_response('turnover_form.html', variables)
else:
return HttpResponseRedirect('/authorization/')
有关如何将id与所选项目进行匹配的任何建议将不胜感激。我确信我的代码不是非常pythonic,因为我还在学习。
答案 0 :(得分:1)
outage = form.cleaned_data['outage'] # cleaned_data['outage'] is a model instance