如何在一个页面上创建模型及其泛型关系

时间:2011-03-30 10:38:25

标签: django django-models django-forms

我有这个设置:

class Observation(models.Model):
    start_time = models.DateTimeField()
    measurements = generic.GenericRelation(Measurement)

class Measurement(models.Model):
    variable = models.ForeignKey(Variable)
    value = models.CharField(max_length=300, blank=True)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

这些都是简化模型。测量需要是通用的,因为它也在其他地方使用。

我想制作一个页面,我可以在其中创建一个观察相关的测量。用户应该能够添加观察中尚未出现的测量值。我有一个工作的ModelForm for Measurement。

我继续遇到不存在的关系,我认为我犯了一个涉及generic_inlinemodelform的愚蠢错误。我搜索过但找不到这样的例子。任何人都可以通过提供示例或链接来帮助我吗?

1 个答案:

答案 0 :(得分:0)

您应该可以在视图中使用commit = False保存它们。

<强> forms.py:

class MeasurementForm(forms.ModelForm):
    class Meta:
        model = Measurement
        fields = ('variable', 'value')

class ObservationForm(forms.ModelForm):
    class Meta:
        model = Observation

<强>模板:

<form method='POST>
    <legend>Observation</legend>
    {{ observation_form.as_p }}
    <legend>Measurement</legend>
    {{ measurement_form.as_p }}
    <input type='submit' value='submit' />
</form>

<强> views.py:

def new_observation(request):
    if request.method=='POST':
        observation_form = ObservationForm(request.POST)
        measurement_form = MeasurementForm(request.POST)
        if observation_form.is_valid() and measurement_form.is_valid():
            observation_instance = observation_form.save()
            measurement_instance = measurement_form.save(commit=False)
            measurement_instance.content_object = observation_instance
            measurement_instance.save()
            return HttpResponseRedirect(observation_instance.get_absolute_url())
    else:
        observation_form = ObservationForm()
        measurement_form = MeasurementForm()

    context = { 'observation_form':observation_form,
                'measurement_form':measurement_form,}

    return render_to_response('add-observation.html', context,
            context_instance=RequestContext(request))