Django form redirect using HttpResponseRedirect

django, forms, redirect

Solution

Your view with the form should look something like this:

def add(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            # do stuff & add to database
            my_file = FileField.objects.create()
             # use my_file.pk or whatever attribute of FileField your id is based on
            return HttpResponseRedirect('/files/%i/' % my_file.pk)
    else:
        form = UploadFileForm()

    return render_to_response('upload_file.html', {
        'form': form,
    })

Problem

So this can't be too hard but I can't figure it out... I want my form in django (located at /file_upload/) to upload a file, add it to the database, and then redirect to a new page where the parameter is the id of the field that I've added in the database (located at /file/163/, say). I've set up urls.py so that /file/163/ works just fine if you navigate there directly, but I don't know how to get there from /file/upload/. My code is like this: ``` def add(request): if request.method == 'POST': # If the form has been submitted... form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): # do stuff & add to database my_file = FileField.objects.create() return HttpResponseRedirect(reverse('/file/', args=[my_file.id])) ``` I can't use this solution because I don't know what the field id is going to be until I've handled the form in views.py, so the redirect has to happen in views.py. I think. Any thoughts?

Original source