6

I'm new to Django and Python, and have spent a couple days trying to solve this problem. I've tried several approaches in other threads here, but I think I'm missing some basic concept because none of them have worked for me. Here's what I'm trying to do:

I'm using ModelForm, and I have created a form for adding records that includes a foreign key. I want this value to be set by default to match the record that was displayed on the page I linked from. [Code shown below edited to show suggested corrections].

Here's the relevant code from views.py:

def add_sighting(request):
unit = request.GET.get('unit')
form = SightingForm(request.POST or None, initial={'unit':unit})
if form.is_valid():
    sighting = form.save(commit=False)
    sighting.save()
    return redirect(index)
return render_to_response('trainapp/add_sighting_form.html',
                          {'unit': unit, 'sighting_form': form},
                          context_instance=RequestContext(request))

Here's the relevant code from add_sighting_form.html:

<form action="/trainapp/add_sighting/" method="post">
{% csrf_token %}
<table>
{{ sighting_form.as_table }}
</table>
<input type="submit" value="Save" />
</form>

Here's the relevant code from the template I linked from:

<p><a href="/trainapp/add_sighting/?unit={{ unit.id }}">Add sighting</a></p>
4

1 回答 1

4

有几种方法可能在这里起作用。

最简单的方法是在创建表单实例时使用初始参数,然后再将其传递到某个视图的上下文中。

假设您正在使用如下视图方法:

def some_view( request ):
    id = request.GET.get( 'record-id' )
    # do check if id is valid...

    # load some record
    record = Record.objects.get( pk=id )

    # create a form instance
    form = RecordForm( initial={ 'some_key_field_name':record.id } )

    # set up context
    context = Context({
         'record' : record,
         'form' : form
    })

    # render the templateview using the above context
    # and return a HttpResponse ...

如果您改用基于类的视图,则可以覆盖 get_context_data 以获得类似的结果。

基于类的视图

根据您的代码,我还想建议您查看 Django 中基于类的视图。可以为您处理获取和发布表格。它甚至会为您创建(默认)表单。

已发布代码的等价物将是这样的:

class CreateSightingView( CreateView ):

    model = Sighting

    def get_context_data( self, **kwargs ):
        # call the super to get the default context
        data = super( CreateSightingView, self ).get_context_data( **kwargs )

        # add the initial value here
        # but first get the id from the request GET data
        id = self.request.GET.get( 'record-id' )
        # again: do some checking of id
        data.get( 'form' ).initial[ 'unit' ] = id

        return data
于 2012-10-10T22:25:04.017 回答