开发者

How to create a model and its generic relations on one page

I have this setup:

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

class Measurement(models.Model):
    variable = models.ForeignKey(Variable)
    value = models.CharField(max_开发者_如何学JAVAlength=300, blank=True)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

These are simplified models of course. Measurement needs to be generic because it is also used elsewhere.

I want to make a page on which I can create an Observation and the related Measurements. The user should be able to add Measurements that are not yet present on the observation. I have a working ModelForm for Measurement.

I keep running into relations not existing, and I think I am making a silly mistake involving generic_inlinemodelform. I have searched but cannot find an example for this. Can anyone help me out, either by providing an example or linking to it?


You should be able to save them using commit = False in your views.

forms.py:

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

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

template:

<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))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜