Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django / Jquery / Javascript - How to prepopulate form with url parameters (autofill the form)

I would like to send some people link lets say:

http://www.example.com/form/[email protected]

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 "[email protected]".

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>                
like image 264
Radek Avatar asked May 28 '13 16:05

Radek


People also ask

How do I autofill fields in URL?

In your browser, navigate to the page your form is on and copy the URL. Add a question mark (?) to the end of the page URL. Add the internal name of the property, followed by an equal sign and the value to auto-populate in the field.

How do I get form data from a form in Django?

GET and POST are the only HTTP methods to use when dealing with forms. Django’s login form is returned using the POST method, in which the browser bundles up the form data, encodes it for transmission, sends it to the server, and then receives back its response.

How do I create a URL with multiple parameters in Django?

This is an example URL with multiple parameters. In your view template, use Django's URL syntax to add a link to the form that contains the parameters. Make sure you have your URLs configured in urls.py.

How do I add parameters to a form?

Please remember to put a question mark ( ? ) after the form URL to declare that we are submitting parameters, then comes the name followed by an equal sign ( = ), then the value. If you wish to add more parameters, these are to be separated by an ampersand ( & ) sign.

How to include the field names in the URL parameter?

The field names can be found under the name attribute, e.g. name=”q5_fullName [first]”. In order to use it on the URL parameter, you only have to copy the name after the underscore ( _ ) symbol. Now, we’re able to get the names of each field, so it is time to include them in the URL.


2 Answers

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))
like image 113
karthikr Avatar answered Oct 20 '22 08:10

karthikr


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

like image 35
Benjamin Gruenbaum Avatar answered Oct 20 '22 09:10

Benjamin Gruenbaum