6

I would like to send some people link lets say:

http://www.example.com/form/?q=example@me.com

If they click the link it will go to the page /form/ where is the form with multiple fields.

I would like to pre-populate it with that q string that would fill out that "email" input

field with specified email in the string "example@me.com".

Website is done in Django, would like to ask what is the best approach to accomplish this.

Should I use JS, Jquery, Django? Dont know where to start.

Would like something like this:

http://support.unbounce.com/entries/307658-Can-I-pre-populate-a-form-with-URL-parameters-VIDEO-

but on my site. Can somebody help with simple form and example?

Thanks

models.py

from django.db import models

class Example(models.Model):
    username = models.CharField(max_length=200, blank=True)
    email = models.CharField(max_length=200)
    image = models.ImageField(upload_to='profiles', blank=True)
    text = models.CharField(max_length=200, blank=True)

forms.py

from django import forms

from models import Example

class ExampleForm(forms.ModelForm):
    class Meta:
        model = Example

views.py

from django import forms
from models import Example
from forms import ExampleForm

from django.template import RequestContext, Context
from django.core.context_processors import csrf

from django.shortcuts import render_to_response
from django.shortcuts import render_to_response, get_object_or_404

from django import http

import os
import json
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.conf import settings

def index(request):
    if request.method == "POST":
        form = ExampleForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return http.HttpResponseRedirect('/success/')
    else:
        form = ExampleForm()

    return render_to_response('index.html', {'title': 'Example Form', 'form': form},context_instance=RequestContext(request))

urls.py

from django.conf.urls import patterns, include, url
from django.conf import settings

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^$', 'signup.views.index', name='index'),
    url(r'^admin/', include(admin.site.urls)),
)

index template

<form id='add_cat' method='post' enctype="multipart/form-data">{% csrf_token %}


    <input id="id_username" maxlength="200" name="username" type="text" placeholder="username"> 
    <input id="id_email" maxlength="200" name="email" type="text" >   

    <input id="id_picture" maxlength="200" name="picture" type="text">

    <textarea id="id_text" row="3" name="first_text" placeholder="Type something…"></textarea>

    <input id="add_cat_btn" type='submit' value="save">

 </form>                
Radek
  • 1,149
  • 2
  • 19
  • 40
  • 1
    pass `request.GET` as `initial` data in form if you follow same field names as in form. Otherwise collect `GET` variables and pass them appropriately in form `initial` – Aamir Rind May 28 '13 at 16:25

3 Answers3

4

request.GET.copy() would give you a dictionary, and pass it as an initial dictionary.

initial = request.GET.copy()
form = MyForm(initial=initial)

It would populate the fields which are present in the form.

If you would have GET and POST interchangably,

def index(request):

    initial = {}
    if request.GET:
        initial = request.GET.copy()

    form = ExampleForm(initial=initial)

    if request.method == "POST":
        if request.POST:
            initial = request.POST.copy()
        form = ExampleForm(request.POST, request.FILES, initial=initial)
        if form.is_valid():
            form.save()
            return http.HttpResponseRedirect('/success/')


    return render_to_response('index.html', {'title': 'Example Form', 'form': form },context_instance=RequestContext(request))
karthikr
  • 97,368
  • 26
  • 197
  • 188
3

You can do it either in Django, or in JavaScript.

Here is a JavaScript solution using getParameterByName from that SO question.

The advantage of doing this in JS is that it will let you cache the server response and not require server calculations on every user request.

Give your email form field an ID, for example emailfield, then you can do something like

var emailField = document.getElementById("emailfield");
emailField.value = getParameterByName("email"); // "q" in your example url

Inside your ready, or onload handler (or simply in a script tag placed as the last thing in the body section)

Here is a fiddle

It doesn't work since it puts the code in the iframe so you can't access the GET paramss, if you check the iframe, you can see it works:

Here is an example http://fiddle.jshell.net/FA9fQ/show/light/?email=hello

Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • Just updated my question with code, you can look at it, going to check your solution thanks – Radek May 28 '13 at 16:43
  • This solution works very nice, I am still also looking for django solution without using the JS, but great example, thanks a lot. – Radek May 28 '13 at 16:55
1

karthikr's answer is correct. For anyone looking for a way to do this with Django's Class-based views this can be done using the get_initial method. Below is a re-usable example:

class RequestInitialFormViewMixin(object):
    """Pass Request.GET as initial values to Form"""
    def get_initial(self):
        initial = super(RequestInitialFormViewMixin, self).get_initial()
        if self.request.GET:
            for key, value in self.request.GET.items():  # QueryDict, each value is a list
                if len(value) == 1:
                    initial[key] = value[0]
                else:
                    initial[key] = value
        return initial

class MyFormView(RequestInitialFormViewMixin, FormView):
    # ...

Note that request.GET returns a QueryDict which has a list for every value.

Dário
  • 2,002
  • 1
  • 18
  • 28