Commits

Anonymous committed f4178e1

Merged revisions 4186 to 4454 from trunk.

  • Participants
  • Parent commits 841dc62
  • Branches sqlalchemy

Comments (0)

Files changed (120)

     Clint Ecker
     Enrico <rico.bl@gmail.com>
     favo@exoweb.net
+    Eric Floehr <eric@intellovations.com>
     gandalf@owca.info
     Baishampayan Ghose
     martin.glueck@gmail.com
     Manuzhai
     Petar Marić
     mark@junklight.com
+    Yasushi Masuda <whosaysni@gmail.com>
     mattycakes@gmail.com
     Jason McBrayer <http://www.carcosa.net/jason/>
     mccutchen@gmail.com
     michael.mcewan@gmail.com
+    mitakummaa@gmail.com
     mmarshall
     Eric Moritz <http://eric.themoritzfamily.com/>
     Robin Munn <http://www.geekforgod.com/>
+    Robert Myers <myer0052@gmail.com>
     Nebojša Dorđević
     Fraser Nevett <mail@nevett.org>
     Sam Newman <http://www.magpiebrain.com/>
     serbaut@gmail.com
     Pete Shinners <pete@shinners.org>
     SmileyChris <smileychris@gmail.com>
+    smurf@smurf.noris.de
     sopel
     Thomas Steinacher <tom@eggdrop.ch>
     nowell strite
     Tom Insam
     Joe Topjian <http://joe.terrarum.net/geek/code/python/django/>
     Karen Tracey <graybark@bellsouth.net>
+    Makoto Tsuyuki <mtsuyuki@gmail.com>
     Amit Upadhyay
     Geert Vanderkelen
     Milton Waddams

File django/bin/daily_cleanup.py

+#!/usr/bin/env python
+
 """
 Daily cleanup job.
 

File django/conf/global_settings.py

 INTERNAL_IPS = ()
 
 # Local time zone for this installation. All choices can be found here:
-# http://www.postgresql.org/docs/current/static/datetime-keywords.html#DATETIME-TIMEZONE-SET-TABLE
+# http://www.postgresql.org/docs/8.1/static/datetime-keywords.html#DATETIME-TIMEZONE-SET-TABLE
 TIME_ZONE = 'America/Chicago'
 
 # Language code for this installation. All choices can be found here:

File django/conf/project_template/settings.py

 DATABASE_PORT = ''             # Set to empty string for default. Not used with sqlite3.
 
 # Local time zone for this installation. All choices can be found here:
-# http://www.postgresql.org/docs/current/static/datetime-keywords.html#DATETIME-TIMEZONE-SET-TABLE
+# http://www.postgresql.org/docs/8.1/static/datetime-keywords.html#DATETIME-TIMEZONE-SET-TABLE
 TIME_ZONE = 'America/Chicago'
 
 # Language code for this installation. All choices can be found here:

File django/contrib/admin/templates/admin/auth/user/change_password.html

+{% extends "admin/base_site.html" %}
+{% load i18n admin_modify adminmedia %}
+{% block extrahead %}{{ block.super }}
+<script type="text/javascript" src="../../../../jsi18n/"></script>
+{% for js in javascript_imports %}{% include_admin_script js %}{% endfor %}
+{% endblock %}
+{% block stylesheet %}{% admin_media_prefix %}css/forms.css{% endblock %}
+{% block bodyclass %}{{ opts.app_label }}-{{ opts.object_name.lower }} change-form{% endblock %}
+{% block userlinks %}<a href="../../../../doc/">{% trans 'Documentation' %}</a> / <a href="../../../password_change/">{% trans 'Change password' %}</a> / <a href="../../../logout/">{% trans 'Log out' %}</a>{% endblock %}
+{% block breadcrumbs %}{% if not is_popup %}
+<div class="breadcrumbs">
+     <a href="../../../../">{% trans "Home" %}</a> &rsaquo;
+     <a href="../../">{{ opts.verbose_name_plural|capfirst|escape }}</a> &rsaquo;
+     <a href="../">{{ original|truncatewords:"18"|escape }}</a> &rsaquo;
+     {% trans 'Change password' %}
+</div>
+{% endif %}{% endblock %}
+{% block content %}<div id="content-main">
+<form action="{{ form_url }}" method="post" id="{{ opts.module_name }}_form">{% block form_top %}{% endblock %}
+<div>
+{% if is_popup %}<input type="hidden" name="_popup" value="1" />{% endif %}
+{% if form.error_dict %}
+    <p class="errornote">
+    {% blocktrans count form.error_dict.items|length as counter %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktrans %}
+    </p>
+{% endif %}
+
+<p>{% blocktrans with original.username|escape as username %}Enter a new password for the user <strong>{{ username }}</strong>.{% endblocktrans %}</p>
+
+<fieldset class="module aligned">
+
+<div class="form-row">
+  {{ form.password1.html_error_list }}
+  <label for="id_password1" class="required">{% trans 'Password' %}:</label> {{ form.password1 }}
+</div>
+
+<div class="form-row">
+  {{ form.password2.html_error_list }}
+  <label for="id_password2" class="required">{% trans 'Password (again)' %}:</label> {{ form.password2 }}
+  <p class="help">{% trans 'Enter the same password as above, for verification.' %}</p>
+</div>
+
+</fieldset>
+
+<div class="submit-row">
+<input type="submit" value="{% trans 'Change password' %}" class="default" />
+</div>
+
+<script type="text/javascript">document.getElementById("{{ first_form_field_id }}").focus();</script>
+</div>
+</form></div>
+{% endblock %}

File django/contrib/admin/templates/admin/base.html

     <div id="content" class="{% block coltype %}colM{% endblock %}">
         {% block pretitle %}{% endblock %}
         {% block content_title %}{% if title %}<h1>{{ title|escape }}</h1>{% endif %}{% endblock %}
-        {% block content %}{{ content }}{% endblock %}
+        {% block content %}
+        {% block object-tools %}{% endblock %}
+        {{ content }}
+        {% endblock %}
         {% block sidebar %}{% endblock %}
         <br class="clear" />
     </div>

File django/contrib/admin/templates/admin/change_form.html

 </div>
 {% endif %}{% endblock %}
 {% block content %}<div id="content-main">
+{% block object-tools %}
 {% if change %}{% if not is_popup %}
   <ul class="object-tools"><li><a href="history/" class="historylink">{% trans "History" %}</a></li>
   {% if has_absolute_url %}<li><a href="../../../r/{{ content_type_id }}/{{ object_id }}/" class="viewsitelink">{% trans "View on site" %}</a></li>{% endif%}
   </ul>
 {% endif %}{% endif %}
+{% endblock %}
 <form {% if has_file_field %}enctype="multipart/form-data" {% endif %}action="{{ form_url }}" method="post" id="{{ opts.module_name }}_form">{% block form_top %}{% endblock %}
 <div>
 {% if is_popup %}<input type="hidden" name="_popup" value="1" />{% endif %}

File django/contrib/admin/templates/admin/change_list.html

 {% block coltype %}flex{% endblock %}
 {% block content %}
 <div id="content-main">
+{% block object-tools %}
 {% if has_add_permission %}
 <ul class="object-tools"><li><a href="add/{% if is_popup %}?_popup=1{% endif %}" class="addlink">{% blocktrans with cl.opts.verbose_name|escape as name %}Add {{ name }}{% endblocktrans %}</a></li></ul>
 {% endif %}
+{% endblock %}
 <div class="module{% if cl.has_filters %} filtered{% endif %}" id="changelist">
 {% block search %}{% search_form cl %}{% endblock %}
 {% block date_hierarchy %}{% date_hierarchy cl %}{% endblock %}

File django/contrib/admin/templatetags/admin_list.py

                        "url": cl.get_query_string({ORDER_VAR: i, ORDER_TYPE_VAR: new_order_type}),
                        "class_attrib": (th_classes and ' class="%s"' % ' '.join(th_classes) or '')}
 
+def _boolean_icon(field_val):
+    BOOLEAN_MAPPING = {True: 'yes', False: 'no', None: 'unknown'}
+    return '<img src="%simg/admin/icon-%s.gif" alt="%s" />' % (settings.ADMIN_MEDIA_PREFIX, BOOLEAN_MAPPING[field_val], field_val)
+
 def items_for_result(cl, result):
     first = True
     pk = cl.lookup_opts.pk.attname
             try:
                 attr = getattr(result, field_name)
                 allow_tags = getattr(attr, 'allow_tags', False)
+                boolean = getattr(attr, 'boolean', False)
                 if callable(attr):
                     attr = attr()
-                result_repr = str(attr)
+                if boolean:
+                    allow_tags = True
+                    result_repr = _boolean_icon(attr)
+                else:
+                    result_repr = str(attr)
             except (AttributeError, ObjectDoesNotExist):
                 result_repr = EMPTY_CHANGELIST_VALUE
             else:
                 row_class = ' class="nowrap"'
             # Booleans are special: We use images.
             elif isinstance(f, models.BooleanField) or isinstance(f, models.NullBooleanField):
-                BOOLEAN_MAPPING = {True: 'yes', False: 'no', None: 'unknown'}
-                result_repr = '<img src="%simg/admin/icon-%s.gif" alt="%s" />' % (settings.ADMIN_MEDIA_PREFIX, BOOLEAN_MAPPING[field_val], field_val)
+                result_repr = _boolean_icon(field_val)
             # FloatFields are special: Zero-pad the decimals.
             elif isinstance(f, models.FloatField):
                 if field_val is not None:

File django/contrib/admin/urls.py

 
     # "Add user" -- a special-case view
     ('^auth/user/add/$', 'django.contrib.admin.views.auth.user_add_stage'),
+    # "Change user password" -- another special-case view
+    ('^auth/user/(\d+)/password/$', 'django.contrib.admin.views.auth.user_change_password'),
 
     # Add/change/delete/history
     ('^([^/]+)/([^/]+)/$', 'django.contrib.admin.views.main.change_list'),

File django/contrib/admin/views/auth.py

 from django.contrib.admin.views.decorators import staff_member_required
-from django.contrib.auth.forms import UserCreationForm
+from django.contrib.auth.forms import UserCreationForm, AdminPasswordChangeForm
 from django.contrib.auth.models import User
 from django.core.exceptions import PermissionDenied
-from django import forms, template
-from django.shortcuts import render_to_response
+from django import oldforms, template
+from django.shortcuts import render_to_response, get_object_or_404
 from django.http import HttpResponseRedirect
+from django.utils.html import escape
 
 def user_add_stage(request):
     if not request.user.has_perm('auth.change_user'):
                 return HttpResponseRedirect('../%s/' % new_user.id)
     else:
         errors = new_data = {}
-    form = forms.FormWrapper(manipulator, new_data, errors)
+    form = oldforms.FormWrapper(manipulator, new_data, errors)
     return render_to_response('admin/auth/user/add_form.html', {
         'title': _('Add user'),
         'form': form,
         'username_help_text': User._meta.get_field('username').help_text,
     }, context_instance=template.RequestContext(request))
 user_add_stage = staff_member_required(user_add_stage)
+
+def user_change_password(request, id):
+    if not request.user.has_perm('auth.change_user'):
+        raise PermissionDenied
+    user = get_object_or_404(User, pk=id)
+    manipulator = AdminPasswordChangeForm(user)
+    if request.method == 'POST':
+        new_data = request.POST.copy()
+        errors = manipulator.get_validation_errors(new_data)
+        if not errors:
+            new_user = manipulator.save(new_data)
+            msg = _('Password changed successfully.')
+            request.user.message_set.create(message=msg)
+            return HttpResponseRedirect('..')
+    else:
+        errors = new_data = {}
+    form = oldforms.FormWrapper(manipulator, new_data, errors)
+    return render_to_response('admin/auth/user/change_password.html', {
+        'title': _('Change password: %s') % escape(user.username),
+        'form': form,
+        'is_popup': request.REQUEST.has_key('_popup'),
+        'add': True,
+        'change': False,
+        'has_delete_permission': False,
+        'has_change_permission': True,
+        'has_absolute_url': False,
+        'first_form_field_id': 'id_password1',
+        'opts': User._meta,
+        'original': user,
+        'show_save': True,
+    }, context_instance=template.RequestContext(request))
+user_change_password = staff_member_required(user_change_password)

File django/contrib/admin/views/main.py

-from django import forms, template
+from django import oldforms, template
 from django.conf import settings
 from django.contrib.admin.filterspecs import FilterSpec
 from django.contrib.admin.views.decorators import staff_member_required
     """
     Ensure that primary key values do not confuse the admin URLs by escaping
     any '/', '_' and ':' characters. Similar to urllib.quote, except that the
-    quoting is slightly different so that it doesn't get autoamtically
-    unquoted by the web browser.
+    quoting is slightly different so that it doesn't get automatically
+    unquoted by the Web browser.
     """
     if type(s) != type(''):
         return s
         errors = {}
 
     # Populate the FormWrapper.
-    form = forms.FormWrapper(manipulator, new_data, errors)
+    form = oldforms.FormWrapper(manipulator, new_data, errors)
 
     c = template.RequestContext(request, {
         'title': _('Add %s') % opts.verbose_name,
         errors = {}
 
     # Populate the FormWrapper.
-    form = forms.FormWrapper(manipulator, new_data, errors)
+    form = oldforms.FormWrapper(manipulator, new_data, errors)
     form.original = manipulator.original_object
     form.order_objects = []
 

File django/contrib/admin/views/template.py

 from django.contrib.admin.views.decorators import staff_member_required
 from django.core import validators
-from django import template, forms
+from django import template, oldforms
 from django.template import loader
 from django.shortcuts import render_to_response
 from django.contrib.sites.models import Site
             request.user.message_set.create(message='The template is valid.')
     return render_to_response('admin/template_validator.html', {
         'title': 'Template validator',
-        'form': forms.FormWrapper(manipulator, new_data, errors),
+        'form': oldforms.FormWrapper(manipulator, new_data, errors),
     }, context_instance=template.RequestContext(request))
 template_validator = staff_member_required(template_validator)
 
-class TemplateValidator(forms.Manipulator):
+class TemplateValidator(oldforms.Manipulator):
     def __init__(self, settings_modules):
         self.settings_modules = settings_modules
         site_list = Site.objects.in_bulk(settings_modules.keys()).values()
         self.fields = (
-            forms.SelectField('site', is_required=True, choices=[(s.id, s.name) for s in site_list]),
-            forms.LargeTextField('template', is_required=True, rows=25, validator_list=[self.isValidTemplate]),
+            oldforms.SelectField('site', is_required=True, choices=[(s.id, s.name) for s in site_list]),
+            oldforms.LargeTextField('template', is_required=True, rows=25, validator_list=[self.isValidTemplate]),
         )
 
     def isValidTemplate(self, field_data, all_data):

File django/contrib/auth/forms.py

 from django.contrib.sites.models import Site
 from django.template import Context, loader
 from django.core import validators
-from django import forms
+from django import oldforms
 
-class UserCreationForm(forms.Manipulator):
+class UserCreationForm(oldforms.Manipulator):
     "A form that creates a user, with no privileges, from the given username and password."
     def __init__(self):
         self.fields = (
-            forms.TextField(field_name='username', length=30, maxlength=30, is_required=True,
+            oldforms.TextField(field_name='username', length=30, maxlength=30, is_required=True,
                 validator_list=[validators.isAlphaNumeric, self.isValidUsername]),
-            forms.PasswordField(field_name='password1', length=30, maxlength=60, is_required=True),
-            forms.PasswordField(field_name='password2', length=30, maxlength=60, is_required=True,
+            oldforms.PasswordField(field_name='password1', length=30, maxlength=60, is_required=True),
+            oldforms.PasswordField(field_name='password2', length=30, maxlength=60, is_required=True,
                 validator_list=[validators.AlwaysMatchesOtherField('password1', _("The two password fields didn't match."))]),
         )
 
         "Creates the user."
         return User.objects.create_user(new_data['username'], '', new_data['password1'])
 
-class AuthenticationForm(forms.Manipulator):
+class AuthenticationForm(oldforms.Manipulator):
     """
     Base class for authenticating users. Extend this to get a form that accepts
     username/password logins.
         """
         self.request = request
         self.fields = [
-            forms.TextField(field_name="username", length=15, maxlength=30, is_required=True,
+            oldforms.TextField(field_name="username", length=15, maxlength=30, is_required=True,
                 validator_list=[self.isValidUser, self.hasCookiesEnabled]),
-            forms.PasswordField(field_name="password", length=15, maxlength=30, is_required=True),
+            oldforms.PasswordField(field_name="password", length=15, maxlength=30, is_required=True),
         ]
         self.user_cache = None
 
     def get_user(self):
         return self.user_cache
 
-class PasswordResetForm(forms.Manipulator):
+class PasswordResetForm(oldforms.Manipulator):
     "A form that lets a user request a password reset"
     def __init__(self):
         self.fields = (
-            forms.EmailField(field_name="email", length=40, is_required=True,
+            oldforms.EmailField(field_name="email", length=40, is_required=True,
                 validator_list=[self.isValidUserEmail]),
         )
 
         }
         send_mail('Password reset on %s' % site_name, t.render(Context(c)), None, [self.user_cache.email])
 
-class PasswordChangeForm(forms.Manipulator):
+class PasswordChangeForm(oldforms.Manipulator):
     "A form that lets a user change his password."
     def __init__(self, user):
         self.user = user
         self.fields = (
-            forms.PasswordField(field_name="old_password", length=30, maxlength=30, is_required=True,
+            oldforms.PasswordField(field_name="old_password", length=30, maxlength=30, is_required=True,
                 validator_list=[self.isValidOldPassword]),
-            forms.PasswordField(field_name="new_password1", length=30, maxlength=30, is_required=True,
+            oldforms.PasswordField(field_name="new_password1", length=30, maxlength=30, is_required=True,
                 validator_list=[validators.AlwaysMatchesOtherField('new_password2', _("The two 'new password' fields didn't match."))]),
-            forms.PasswordField(field_name="new_password2", length=30, maxlength=30, is_required=True),
+            oldforms.PasswordField(field_name="new_password2", length=30, maxlength=30, is_required=True),
         )
 
     def isValidOldPassword(self, new_data, all_data):
         "Saves the new password."
         self.user.set_password(new_data['new_password1'])
         self.user.save()
+
+class AdminPasswordChangeForm(oldforms.Manipulator):
+    "A form used to change the password of a user in the admin interface."
+    def __init__(self, user):
+        self.user = user
+        self.fields = (
+            oldforms.PasswordField(field_name='password1', length=30, maxlength=60, is_required=True),
+            oldforms.PasswordField(field_name='password2', length=30, maxlength=60, is_required=True,
+                validator_list=[validators.AlwaysMatchesOtherField('password1', _("The two password fields didn't match."))]),
+        )
+
+    def save(self, new_data):
+        "Saves the new password."
+        self.user.set_password(new_data['password1'])
+        self.user.save()

File django/contrib/auth/models.py

     first_name = models.CharField(_('first name'), maxlength=30, blank=True)
     last_name = models.CharField(_('last name'), maxlength=30, blank=True)
     email = models.EmailField(_('e-mail address'), blank=True)
-    password = models.CharField(_('password'), maxlength=128, help_text=_("Use '[algo]$[salt]$[hexdigest]'"))
+    password = models.CharField(_('password'), maxlength=128, help_text=_("Use '[algo]$[salt]$[hexdigest]' or use the <a href=\"password/\">change password form</a>."))
     is_staff = models.BooleanField(_('staff status'), default=False, help_text=_("Designates whether the user can log into this admin site."))
     is_active = models.BooleanField(_('active'), default=True, help_text=_("Designates whether this user can log into the Django admin. Unselect this instead of deleting accounts."))
     is_superuser = models.BooleanField(_('superuser status'), default=False, help_text=_("Designates that this user has all permissions without explicitly assigning them."))

File django/contrib/auth/views.py

 from django.contrib.auth.forms import AuthenticationForm
 from django.contrib.auth.forms import PasswordResetForm, PasswordChangeForm
-from django import forms
+from django import oldforms
 from django.shortcuts import render_to_response
 from django.template import RequestContext
 from django.contrib.sites.models import Site
         errors = {}
     request.session.set_test_cookie()
     return render_to_response(template_name, {
-        'form': forms.FormWrapper(manipulator, request.POST, errors),
+        'form': oldforms.FormWrapper(manipulator, request.POST, errors),
         REDIRECT_FIELD_NAME: redirect_to,
         'site_name': Site.objects.get_current().name,
     }, context_instance=RequestContext(request))
             else:
                 form.save(email_template_name=email_template_name)
             return HttpResponseRedirect('%sdone/' % request.path)
-    return render_to_response(template_name, {'form': forms.FormWrapper(form, new_data, errors)},
+    return render_to_response(template_name, {'form': oldforms.FormWrapper(form, new_data, errors)},
         context_instance=RequestContext(request))
 
 def password_reset_done(request, template_name='registration/password_reset_done.html'):
         if not errors:
             form.save(new_data)
             return HttpResponseRedirect('%sdone/' % request.path)
-    return render_to_response(template_name, {'form': forms.FormWrapper(form, new_data, errors)},
+    return render_to_response(template_name, {'form': oldforms.FormWrapper(form, new_data, errors)},
         context_instance=RequestContext(request))
 password_change = login_required(password_change)
 

File django/contrib/comments/views/comments.py

 from django.core import validators
-from django import forms
+from django import oldforms
 from django.core.mail import mail_admins, mail_managers
 from django.http import Http404
 from django.core.exceptions import ObjectDoesNotExist
             else:
                 return []
         self.fields.extend([
-            forms.LargeTextField(field_name="comment", maxlength=3000, is_required=True,
+            oldforms.LargeTextField(field_name="comment", maxlength=3000, is_required=True,
                 validator_list=[self.hasNoProfanities]),
-            forms.RadioSelectField(field_name="rating1", choices=choices,
+            oldforms.RadioSelectField(field_name="rating1", choices=choices,
                 is_required=ratings_required and num_rating_choices > 0,
                 validator_list=get_validator_list(1),
             ),
-            forms.RadioSelectField(field_name="rating2", choices=choices,
+            oldforms.RadioSelectField(field_name="rating2", choices=choices,
                 is_required=ratings_required and num_rating_choices > 1,
                 validator_list=get_validator_list(2),
             ),
-            forms.RadioSelectField(field_name="rating3", choices=choices,
+            oldforms.RadioSelectField(field_name="rating3", choices=choices,
                 is_required=ratings_required and num_rating_choices > 2,
                 validator_list=get_validator_list(3),
             ),
-            forms.RadioSelectField(field_name="rating4", choices=choices,
+            oldforms.RadioSelectField(field_name="rating4", choices=choices,
                 is_required=ratings_required and num_rating_choices > 3,
                 validator_list=get_validator_list(4),
             ),
-            forms.RadioSelectField(field_name="rating5", choices=choices,
+            oldforms.RadioSelectField(field_name="rating5", choices=choices,
                 is_required=ratings_required and num_rating_choices > 4,
                 validator_list=get_validator_list(5),
             ),
-            forms.RadioSelectField(field_name="rating6", choices=choices,
+            oldforms.RadioSelectField(field_name="rating6", choices=choices,
                 is_required=ratings_required and num_rating_choices > 5,
                 validator_list=get_validator_list(6),
             ),
-            forms.RadioSelectField(field_name="rating7", choices=choices,
+            oldforms.RadioSelectField(field_name="rating7", choices=choices,
                 is_required=ratings_required and num_rating_choices > 6,
                 validator_list=get_validator_list(7),
             ),
-            forms.RadioSelectField(field_name="rating8", choices=choices,
+            oldforms.RadioSelectField(field_name="rating8", choices=choices,
                 is_required=ratings_required and num_rating_choices > 7,
                 validator_list=get_validator_list(8),
             ),
             mail_managers("Comment posted by sketchy user (%s)" % self.user_cache.username, c.get_as_text())
         return c
 
-class PublicFreeCommentManipulator(forms.Manipulator):
+class PublicFreeCommentManipulator(oldforms.Manipulator):
     "Manipulator that handles public free (unregistered) comments"
     def __init__(self):
         self.fields = (
-            forms.TextField(field_name="person_name", maxlength=50, is_required=True,
+            oldforms.TextField(field_name="person_name", maxlength=50, is_required=True,
                 validator_list=[self.hasNoProfanities]),
-            forms.LargeTextField(field_name="comment", maxlength=3000, is_required=True,
+            oldforms.LargeTextField(field_name="comment", maxlength=3000, is_required=True,
                 validator_list=[self.hasNoProfanities]),
         )
 
         from django.contrib.auth import login
         login(request, manipulator.get_user())
     if errors or request.POST.has_key('preview'):
-        class CommentFormWrapper(forms.FormWrapper):
+        class CommentFormWrapper(oldforms.FormWrapper):
             def __init__(self, manipulator, new_data, errors, rating_choices):
-                forms.FormWrapper.__init__(self, manipulator, new_data, errors)
+                oldforms.FormWrapper.__init__(self, manipulator, new_data, errors)
                 self.rating_choices = rating_choices
             def ratings(self):
                 field_list = [self['rating%d' % (i+1)] for i in range(len(rating_choices))]
         comment = errors and '' or manipulator.get_comment(new_data)
         return render_to_response('comments/free_preview.html', {
             'comment': comment,
-            'comment_form': forms.FormWrapper(manipulator, new_data, errors),
+            'comment_form': oldforms.FormWrapper(manipulator, new_data, errors),
             'options': options,
             'target': target,
             'hash': security_hash,

File django/contrib/contenttypes/models.py

 from django.db import models
 from django.utils.translation import gettext_lazy as _
 
+CONTENT_TYPE_CACHE = {}
 class ContentTypeManager(models.Manager):
     def get_for_model(self, model):
         """
         ContentType if necessary.
         """
         opts = model._meta
-        # The str() is needed around opts.verbose_name because it's a
-        # django.utils.functional.__proxy__ object.
-        ct, created = self.model._default_manager.get_or_create(app_label=opts.app_label,
-            model=opts.object_name.lower(), defaults={'name': str(opts.verbose_name)})
+        key = (opts.app_label, opts.object_name.lower())
+        try:
+            ct = CONTENT_TYPE_CACHE[key]
+        except KeyError:
+            # The str() is needed around opts.verbose_name because it's a
+            # django.utils.functional.__proxy__ object.
+            ct, created = self.model._default_manager.get_or_create(app_label=key[0],
+                model=key[1], defaults={'name': str(opts.verbose_name)})
+            CONTENT_TYPE_CACHE[key] = ct
         return ct
 
 class ContentType(models.Model):

File django/contrib/csrf/middleware.py

 import re
 import itertools
 
-_ERROR_MSG = "<h1>403 Forbidden</h1><p>Cross Site Request Forgery detected.  Request aborted.</p>"
+_ERROR_MSG = '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><body><h1>403 Forbidden</h1><p>Cross Site Request Forgery detected. Request aborted.</p></body></html>'
 
 _POST_FORM_RE = \
     re.compile(r'(<form\W[^>]*\bmethod=(\'|"|)POST(\'|"|)\b[^>]*>)', re.IGNORECASE)

File django/contrib/formtools/preview.py

 from django.core.exceptions import ImproperlyConfigured
 from django.http import Http404
 from django.shortcuts import render_to_response
+from django.template.context import RequestContext
 import cPickle as pickle
 import md5
 
     def preview_get(self, request):
         "Displays the form"
         f = self.form(auto_id=AUTO_ID)
-        return render_to_response(self.form_template, {'form': f, 'stage_field': self.unused_name('stage'), 'state': self.state})
+        return render_to_response(self.form_template,
+            {'form': f, 'stage_field': self.unused_name('stage'), 'state': self.state},
+            context_instance=RequestContext(request))
 
     def preview_post(self, request):
         "Validates the POST data. If valid, displays the preview page. Else, redisplays form."
         if f.is_valid():
             context['hash_field'] = self.unused_name('hash')
             context['hash_value'] = self.security_hash(request, f)
-            return render_to_response(self.preview_template, context)
+            return render_to_response(self.preview_template, context, context_instance=RequestContext(request))
         else:
-            return render_to_response(self.form_template, context)
+            return render_to_response(self.form_template, context, context_instance=RequestContext(request))
 
     def post_post(self, request):
         "Validates the POST data. If valid, calls done(). Else, redisplays form."
                 return self.failed_hash(request) # Security hash failed.
             return self.done(request, f.clean_data)
         else:
-            return render_to_response(self.form_template, {'form': f, 'stage_field': self.unused_name('stage'), 'state': self.state})
+            return render_to_response(self.form_template,
+                {'form': f, 'stage_field': self.unused_name('stage'), 'state': self.state},
+                context_instance=RequestContext(request))
 
     # METHODS SUBCLASSES MIGHT OVERRIDE IF APPROPRIATE ########################
 

File django/contrib/sessions/middleware.py

 from django.conf import settings
 from django.contrib.sessions.models import Session
+from django.core.exceptions import SuspiciousOperation
 from django.utils.cache import patch_vary_headers
 import datetime
 
                     s = Session.objects.get(session_key=self.session_key,
                         expire_date__gt=datetime.datetime.now())
                     self._session_cache = s.get_decoded()
-                except Session.DoesNotExist:
+                except (Session.DoesNotExist, SuspiciousOperation):
                     self._session_cache = {}
                     # Set the session_key to None to force creation of a new
                     # key, for extra security.

File django/core/cache/backends/dummy.py

     def __init__(self, *args, **kwargs):
         pass
 
-    def get(self, *args, **kwargs):
-        pass
+    def get(self, key, default=None):
+        return default
 
     def set(self, *args, **kwargs):
         pass
         pass
 
     def get_many(self, *args, **kwargs):
-        pass
+        return {}
 
     def has_key(self, *args, **kwargs):
         return False

File django/core/handlers/base.py

             if response:
                 return response
 
-        resolver = urlresolvers.RegexURLResolver(r'^/', settings.ROOT_URLCONF)
+        # Get urlconf from request object, if available.  Otherwise use default.
+        urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
+
+        resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
         try:
             callback, callback_args, callback_kwargs = resolver.resolve(request.path)
 

File django/core/management.py

 # which has been installed.
 PROJECT_TEMPLATE_DIR = os.path.join(django.__path__[0], 'conf', '%s_template')
 
-INVALID_PROJECT_NAMES = ('django', 'test')
+INVALID_PROJECT_NAMES = ('django', 'site', 'test')
 
 # Set up the terminal color scheme.
 class dummy: pass
     "Creates a Django project for the given project_name in the given directory."
     from random import choice
     if project_name in INVALID_PROJECT_NAMES:
-        sys.stderr.write(style.ERROR("Error: %r isn't a valid project name. Please try another.\n" % project_name))
+        sys.stderr.write(style.ERROR("Error: '%r' conflicts with the name of an existing Python module and cannot be used as a project name. Please try another name.\n" % project_name))
         sys.exit(1)
     _start_helper('project', project_name, directory)
     # Create a random SECRET_KEY hash, and put it in the main settings.

File django/core/serializers/python.py

     for d in object_list:
         # Look up the model and starting build a dict of data for it.
         Model = _get_model(d["model"])
-        data = {Model._meta.pk.name : d["pk"]}
+        data = {Model._meta.pk.attname : d["pk"]}
         m2m_data = {}
         
         # Handle each field

File django/db/backends/ado_mssql/creation.py

     'SmallIntegerField': 'smallint',
     'TextField':         'text',
     'TimeField':         'time',
-    'URLField':          'varchar(200)',
     'USStateField':      'varchar(2)',
 }

File django/db/backends/mysql/base.py

                 kwargs['port'] = int(settings.DATABASE_PORT)
             kwargs.update(self.options)
             self.connection = Database.connect(**kwargs)
-        cursor = self.connection.cursor()
-        if self.connection.get_server_info() >= '4.1':
-            cursor.execute("SET NAMES 'utf8'")
+            cursor = self.connection.cursor()
+            if self.connection.get_server_info() >= '4.1':
+                cursor.execute("SET NAMES 'utf8'")
+        else:
+            cursor = self.connection.cursor()
         if settings.DEBUG:
             return util.CursorDebugWrapper(MysqlDebugWrapper(cursor), self)
         return cursor

File django/db/backends/mysql/creation.py

     'SmallIntegerField': 'smallint',
     'TextField':         'longtext',
     'TimeField':         'time',
-    'URLField':          'varchar(200)',
     'USStateField':      'varchar(2)',
 }

File django/db/backends/oracle/creation.py

     'SmallIntegerField': 'smallint',
     'TextField':         'long',
     'TimeField':         'timestamp',
-    'URLField':          'varchar(200)',
     'USStateField':      'varchar(2)',
 }

File django/db/backends/postgresql/base.py

     # Import copy of _thread_local.py from Python 2.4
     from django.utils._threading_local import local
 
+def smart_basestring(s, charset):
+    if isinstance(s, unicode):
+        return s.encode(charset)
+    return s
+
+class UnicodeCursorWrapper(object):
+    """
+    A thin wrapper around psycopg cursors that allows them to accept Unicode
+    strings as params.
+
+    This is necessary because psycopg doesn't apply any DB quoting to
+    parameters that are Unicode strings. If a param is Unicode, this will
+    convert it to a bytestring using DEFAULT_CHARSET before passing it to
+    psycopg.
+    """
+    def __init__(self, cursor, charset):
+        self.cursor = cursor
+        self.charset = charset
+
+    def execute(self, sql, params=()):
+        return self.cursor.execute(sql, [smart_basestring(p, self.charset) for p in params])
+
+    def executemany(self, sql, param_list):
+        new_param_list = [tuple([smart_basestring(p, self.charset) for p in params]) for params in param_list]
+        return self.cursor.executemany(sql, new_param_list)
+
+    def __getattr__(self, attr):
+        if self.__dict__.has_key(attr):
+            return self.__dict__[attr]
+        else:
+            return getattr(self.cursor, attr)
+
 class DatabaseWrapper(local):
     def __init__(self, **kwargs):
         self.connection = None
             self.connection.set_isolation_level(1) # make transactions transparent to all cursors
         cursor = self.connection.cursor()
         cursor.execute("SET TIME ZONE %s", [settings.TIME_ZONE])
+        cursor = UnicodeCursorWrapper(cursor, settings.DEFAULT_CHARSET)
         if settings.DEBUG:
             return util.CursorDebugWrapper(cursor, self)
         return cursor
 try:
     Database.register_type(Database.new_type((1082,), "DATE", util.typecast_date))
 except AttributeError:
-    raise Exception, "You appear to be using psycopg version 2, which isn't supported yet, because it's still in beta. Use psycopg version 1 instead: http://initd.org/projects/psycopg1"
+    raise Exception, "You appear to be using psycopg version 2. Set your DATABASE_ENGINE to 'postgresql_psycopg2' instead of 'postgresql'."
 Database.register_type(Database.new_type((1083,1266), "TIME", util.typecast_time))
 Database.register_type(Database.new_type((1114,1184), "TIMESTAMP", util.typecast_timestamp))
 Database.register_type(Database.new_type((16,), "BOOLEAN", util.typecast_boolean))

File django/db/backends/postgresql/creation.py

     'SmallIntegerField': 'smallint',
     'TextField':         'text',
     'TimeField':         'time',
-    'URLField':          'varchar(200)',
     'USStateField':      'varchar(2)',
 }

File django/db/backends/sqlite3/creation.py

     'SmallIntegerField':            'smallint',
     'TextField':                    'text',
     'TimeField':                    'time',
-    'URLField':                     'varchar(200)',
     'USStateField':                 'varchar(2)',
 }

File django/db/models/fields/__init__.py

 from django.dispatch import dispatcher
 from django.conf import settings
 from django.core import validators
-from django import forms
+from django import oldforms
+from django import newforms as forms
 from django.core.exceptions import ObjectDoesNotExist
 from django.utils.functional import curry
 from django.utils.itercompat import tee
 
         if self.choices:
             if self.radio_admin:
-                field_objs = [forms.RadioSelectField]
+                field_objs = [oldforms.RadioSelectField]
                 params['ul_class'] = get_ul_class(self.radio_admin)
             else:
-                field_objs = [forms.SelectField]
+                field_objs = [oldforms.SelectField]
 
             params['choices'] = self.get_choices_default()
         else:
 
     def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False, follow=True):
         """
-        Returns a list of forms.FormField instances for this field. It
+        Returns a list of oldforms.FormField instances for this field. It
         calculates the choices at runtime, not at compile time.
 
         name_prefix is a prefix to prepend to the "field_name" argument.
             return self._choices
     choices = property(_get_choices)
 
+    def formfield(self, **kwargs):
+        "Returns a django.newforms.Field instance for this database Field."
+        defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text}
+        defaults.update(kwargs)
+        return forms.CharField(**defaults)
+
+    def value_from_object(self, obj):
+        "Returns the value of this field in the given model instance."
+        return getattr(obj, self.attname)
+
 class AutoField(Field):
     empty_strings_allowed = False
     def __init__(self, *args, **kwargs):
         return Field.get_manipulator_fields(self, opts, manipulator, change, name_prefix, rel, follow)
 
     def get_manipulator_field_objs(self):
-        return [forms.HiddenField]
+        return [oldforms.HiddenField]
 
     def get_manipulator_new_data(self, new_data, rel=False):
         # Never going to be called
         super(AutoField, self).contribute_to_class(cls, name)
         cls._meta.has_auto_field = True
 
+    def formfield(self, **kwargs):
+        return None
+
 class BooleanField(Field):
     def __init__(self, *args, **kwargs):
         kwargs['blank'] = True
         raise validators.ValidationError, gettext("This value must be either True or False.")
 
     def get_manipulator_field_objs(self):
-        return [forms.CheckboxField]
+        return [oldforms.CheckboxField]
+
+    def formfield(self, **kwargs):
+        defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text}
+        defaults.update(kwargs)
+        return forms.BooleanField(**defaults)
 
 class CharField(Field):
     def get_manipulator_field_objs(self):
-        return [forms.TextField]
+        return [oldforms.TextField]
 
     def to_python(self, value):
         if isinstance(value, basestring):
                 raise validators.ValidationError, gettext_lazy("This field cannot be null.")
         return str(value)
 
+    def formfield(self, **kwargs):
+        defaults = {'max_length': self.maxlength, 'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text}
+        defaults.update(kwargs)
+        return forms.CharField(**defaults)
+
 # TODO: Maybe move this into contrib, because it's specialized.
 class CommaSeparatedIntegerField(CharField):
     def get_manipulator_field_objs(self):
-        return [forms.CommaSeparatedIntegerField]
+        return [oldforms.CommaSeparatedIntegerField]
 
 class DateField(Field):
     empty_strings_allowed = False
         return Field.get_db_prep_save(self, value)
 
     def get_manipulator_field_objs(self):
-        return [forms.DateField]
+        return [oldforms.DateField]
 
-    def flatten_data(self, follow, obj = None):
+    def flatten_data(self, follow, obj=None):
         val = self._get_val_from_obj(obj)
         return {self.attname: (val is not None and val.strftime("%Y-%m-%d") or '')}
 
+    def formfield(self, **kwargs):
+        defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text}
+        defaults.update(kwargs)
+        return forms.DateField(**defaults)
+
 class DateTimeField(DateField):
     def to_python(self, value):
         if isinstance(value, datetime.datetime):
         return Field.get_db_prep_lookup(self, lookup_type, value)
 
     def get_manipulator_field_objs(self):
-        return [forms.DateField, forms.TimeField]
+        return [oldforms.DateField, oldforms.TimeField]
 
     def get_manipulator_field_names(self, name_prefix):
         return [name_prefix + self.name + '_date', name_prefix + self.name + '_time']
         return {date_field: (val is not None and val.strftime("%Y-%m-%d") or ''),
                 time_field: (val is not None and val.strftime("%H:%M:%S") or '')}
 
+    def formfield(self, **kwargs):
+        defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text}
+        defaults.update(kwargs)
+        return forms.DateTimeField(**defaults)
+
 class EmailField(CharField):
     def __init__(self, *args, **kwargs):
         kwargs['maxlength'] = 75
         return "CharField"
 
     def get_manipulator_field_objs(self):
-        return [forms.EmailField]
+        return [oldforms.EmailField]
 
     def validate(self, field_data, all_data):
         validators.isValidEmail(field_data, all_data)
 
+    def formfield(self, **kwargs):
+        defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text}
+        defaults.update(kwargs)
+        return forms.EmailField(**defaults)
+
 class FileField(Field):
     def __init__(self, verbose_name=None, name=None, upload_to='', **kwargs):
         self.upload_to = upload_to
                 os.remove(file_name)
 
     def get_manipulator_field_objs(self):
-        return [forms.FileUploadField, forms.HiddenField]
+        return [oldforms.FileUploadField, oldforms.HiddenField]
 
     def get_manipulator_field_names(self, name_prefix):
         return [name_prefix + self.name + '_file', name_prefix + self.name]
         Field.__init__(self, verbose_name, name, **kwargs)
 
     def get_manipulator_field_objs(self):
-        return [curry(forms.FilePathField, path=self.path, match=self.match, recursive=self.recursive)]
+        return [curry(oldforms.FilePathField, path=self.path, match=self.match, recursive=self.recursive)]
 
 class FloatField(Field):
     empty_strings_allowed = False
         Field.__init__(self, verbose_name, name, **kwargs)
 
     def get_manipulator_field_objs(self):
-        return [curry(forms.FloatField, max_digits=self.max_digits, decimal_places=self.decimal_places)]
+        return [curry(oldforms.FloatField, max_digits=self.max_digits, decimal_places=self.decimal_places)]
 
 class ImageField(FileField):
     def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, **kwargs):
         FileField.__init__(self, verbose_name, name, **kwargs)
 
     def get_manipulator_field_objs(self):
-        return [forms.ImageUploadField, forms.HiddenField]
+        return [oldforms.ImageUploadField, oldforms.HiddenField]
 
     def contribute_to_class(self, cls, name):
         super(ImageField, self).contribute_to_class(cls, name)
 class IntegerField(Field):
     empty_strings_allowed = False
     def get_manipulator_field_objs(self):
-        return [forms.IntegerField]
+        return [oldforms.IntegerField]
+
+    def formfield(self, **kwargs):
+        defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text}
+        defaults.update(kwargs)
+        return forms.IntegerField(**defaults)
 
 class IPAddressField(Field):
     def __init__(self, *args, **kwargs):
         Field.__init__(self, *args, **kwargs)
 
     def get_manipulator_field_objs(self):
-        return [forms.IPAddressField]
+        return [oldforms.IPAddressField]
 
     def validate(self, field_data, all_data):
         validators.isValidIPAddress4(field_data, None)
         Field.__init__(self, *args, **kwargs)
 
     def get_manipulator_field_objs(self):
-        return [forms.NullBooleanField]
+        return [oldforms.NullBooleanField]
 
 class PhoneNumberField(IntegerField):
     def get_manipulator_field_objs(self):
-        return [forms.PhoneNumberField]
+        return [oldforms.PhoneNumberField]
 
     def validate(self, field_data, all_data):
         validators.isValidPhone(field_data, all_data)
 
 class PositiveIntegerField(IntegerField):
     def get_manipulator_field_objs(self):
-        return [forms.PositiveIntegerField]
+        return [oldforms.PositiveIntegerField]
 
 class PositiveSmallIntegerField(IntegerField):
     def get_manipulator_field_objs(self):
-        return [forms.PositiveSmallIntegerField]
+        return [oldforms.PositiveSmallIntegerField]
 
 class SlugField(Field):
     def __init__(self, *args, **kwargs):
         Field.__init__(self, *args, **kwargs)
 
     def get_manipulator_field_objs(self):
-        return [forms.TextField]
+        return [oldforms.TextField]
 
 class SmallIntegerField(IntegerField):
     def get_manipulator_field_objs(self):
-        return [forms.SmallIntegerField]
+        return [oldforms.SmallIntegerField]
 
 class TextField(Field):
     def get_manipulator_field_objs(self):
-        return [forms.LargeTextField]
+        return [oldforms.LargeTextField]
+
+    def formfield(self, **kwargs):
+        defaults = {'required': not self.blank, 'widget': forms.Textarea, 'label': capfirst(self.verbose_name), 'help_text': self.help_text}
+        defaults.update(kwargs)
+        return forms.CharField(**defaults)
 
 class TimeField(Field):
     empty_strings_allowed = False
         return Field.get_db_prep_save(self, value)
 
     def get_manipulator_field_objs(self):
-        return [forms.TimeField]
+        return [oldforms.TimeField]
 
     def flatten_data(self,follow, obj = None):
         val = self._get_val_from_obj(obj)
         return {self.attname: (val is not None and val.strftime("%H:%M:%S") or '')}
 
-class URLField(Field):
+    def formfield(self, **kwargs):
+        defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text}
+        defaults.update(kwargs)
+        return forms.TimeField(**defaults)
+
+class URLField(CharField):
     def __init__(self, verbose_name=None, name=None, verify_exists=True, **kwargs):
+        kwargs['maxlength'] = kwargs.get('maxlength', 200)
         if verify_exists:
             kwargs.setdefault('validator_list', []).append(validators.isExistingURL)
-        Field.__init__(self, verbose_name, name, **kwargs)
+        self.verify_exists = verify_exists
+        CharField.__init__(self, verbose_name, name, **kwargs)
 
     def get_manipulator_field_objs(self):
-        return [forms.URLField]
+        return [oldforms.URLField]
+
+    def get_internal_type(self):
+        return "CharField"
+
+    def formfield(self, **kwargs):
+        defaults = {'required': not self.blank, 'verify_exists': self.verify_exists, 'label': capfirst(self.verbose_name), 'help_text': self.help_text}
+        defaults.update(kwargs)
+        return forms.URLField(**defaults)
 
 class USStateField(Field):
     def get_manipulator_field_objs(self):
-        return [forms.USStateField]
+        return [oldforms.USStateField]
 
 class XMLField(TextField):
     def __init__(self, verbose_name=None, name=None, schema_path=None, **kwargs):
         return "TextField"
 
     def get_manipulator_field_objs(self):
-        return [curry(forms.XMLLargeTextField, schema_path=self.schema_path)]
+        return [curry(oldforms.XMLLargeTextField, schema_path=self.schema_path)]
 
 class OrderingField(IntegerField):
     empty_strings_allowed=False
         return "IntegerField"
 
     def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False, follow=True):
-        return [forms.HiddenField(name_prefix + self.name)]
+        return [oldforms.HiddenField(name_prefix + self.name)]

File django/db/models/fields/generic.py

 Classes allowing "generic" relations through ContentType and object-id fields.
 """
 
-from django import forms
+from django import oldforms
 from django.core.exceptions import ObjectDoesNotExist
 from django.db import backend
 from django.db.models import signals
 
     def get_manipulator_field_objs(self):
         choices = self.get_choices_default()
-        return [curry(forms.SelectMultipleField, size=min(max(len(choices), 5), 15), choices=choices)]
+        return [curry(oldforms.SelectMultipleField, size=min(max(len(choices), 5), 15), choices=choices)]
 
     def get_choices_default(self):
         return Field.get_choices(self, include_blank=False)

File django/db/models/fields/related.py

 from django.db.models import signals, get_model
 from django.db.models.fields import AutoField, Field, IntegerField, get_ul_class
 from django.db.models.related import RelatedObject
+from django.utils.text import capfirst
 from django.utils.translation import gettext_lazy, string_concat, ngettext
 from django.utils.functional import curry
 from django.core import validators
-from django import forms
+from django import oldforms
+from django import newforms as forms
 from django.dispatch import dispatcher
 
 # For Python 2.3
         # Otherwise, just move the named objects into the set.
         if self.related.field.null:
             manager.clear()
-        for obj in value:
-            manager.add(obj)
+        manager.add(*value)
 
 def create_many_related_manager(superclass):
     """Creates a manager that subclasses 'superclass' (which is a Manager)
             # join_table: name of the m2m link table
             # source_col_name: the PK colname in join_table for the source object
             # target_col_name: the PK colname in join_table for the target object
-            # *objs - objects to add
+            # *objs - objects to add. Either object instances, or primary keys of object instances.
             from django.db import connection
 
-            # Add the newly created or already existing objects to the join table.
-            # First find out which items are already added, to avoid adding them twice
-            new_ids = set([obj._get_pk_val() for obj in objs])
-            cursor = connection.cursor()
-            cursor.execute("SELECT %s FROM %s WHERE %s = %%s AND %s IN (%s)" % \
-                (target_col_name, self.join_table, source_col_name,
-                target_col_name, ",".join(['%s'] * len(new_ids))),
-                [self._pk_val] + list(new_ids))
-            if cursor.rowcount is not None and cursor.rowcount != 0:
-                existing_ids = set([row[0] for row in cursor.fetchmany(cursor.rowcount)])
-            else:
-                existing_ids = set()
+            # If there aren't any objects, there is nothing to do.
+            if objs:
+                # Check that all the objects are of the right type
+                new_ids = set()
+                for obj in objs:
+                    if isinstance(obj, self.model):
+                        new_ids.add(obj._get_pk_val())
+                    else:
+                        new_ids.add(obj)
+                # Add the newly created or already existing objects to the join table.
+                # First find out which items are already added, to avoid adding them twice
+                cursor = connection.cursor()
+                cursor.execute("SELECT %s FROM %s WHERE %s = %%s AND %s IN (%s)" % \
+                    (target_col_name, self.join_table, source_col_name,
+                    target_col_name, ",".join(['%s'] * len(new_ids))),
+                    [self._pk_val] + list(new_ids))
+                if cursor.rowcount is not None and cursor.rowcount != 0:
+                    existing_ids = set([row[0] for row in cursor.fetchmany(cursor.rowcount)])
+                else:
+                    existing_ids = set()
 
-            # Add the ones that aren't there already
-            for obj_id in (new_ids - existing_ids):
-                cursor.execute("INSERT INTO %s (%s, %s) VALUES (%%s, %%s)" % \
-                    (self.join_table, source_col_name, target_col_name),
-                    [self._pk_val, obj_id])
-            transaction.commit_unless_managed()
+                # Add the ones that aren't there already
+                for obj_id in (new_ids - existing_ids):
+                    cursor.execute("INSERT INTO %s (%s, %s) VALUES (%%s, %%s)" % \
+                        (self.join_table, source_col_name, target_col_name),
+                        [self._pk_val, obj_id])
+                transaction.commit_unless_managed()
 
         def _remove_items(self, source_col_name, target_col_name, *objs):
             # source_col_name: the PK colname in join_table for the source object
             # *objs - objects to remove
             from django.db import connection
 
-            for obj in objs:
-                if not isinstance(obj, self.model):
-                    raise ValueError, "objects to remove() must be %s instances" % self.model._meta.object_name
-            # Remove the specified objects from the join table
-            cursor = connection.cursor()
-            for obj in objs:
-                cursor.execute("DELETE FROM %s WHERE %s = %%s AND %s = %%s" % \
-                    (self.join_table, source_col_name, target_col_name),
-                    [self._pk_val, obj._get_pk_val()])
-            transaction.commit_unless_managed()
+            # If there aren't any objects, there is nothing to do.
+            if objs:
+                # Check that all the objects are of the right type
+                old_ids = set()
+                for obj in objs:
+                    if isinstance(obj, self.model):
+                        old_ids.add(obj._get_pk_val())
+                    else:
+                        old_ids.add(obj)
+                # Remove the specified objects from the join table
+                cursor = connection.cursor()
+                cursor.execute("DELETE FROM %s WHERE %s = %%s AND %s IN (%s)" % \
+                    (self.join_table, source_col_name,
+                    target_col_name, ",".join(['%s'] * len(old_ids))),
+                    [self._pk_val] + list(old_ids))
+                transaction.commit_unless_managed()
 
         def _clear_items(self, source_col_name):
             # source_col_name: the PK colname in join_table for the source object
 
         manager = self.__get__(instance)
         manager.clear()
-        for obj in value:
-            manager.add(obj)
+        manager.add(*value)
 
 class ReverseManyRelatedObjectsDescriptor(object):
     # This class provides the functionality that makes the related-object
 
         manager = self.__get__(instance)
         manager.clear()
-        for obj in value:
-            manager.add(obj)
+        manager.add(*value)
 
 class ForeignKey(RelatedField, Field):
     empty_strings_allowed = False
             params['validator_list'].append(curry(manipulator_valid_rel_key, self, manipulator))
         else:
             if self.radio_admin:
-                field_objs = [forms.RadioSelectField]
+                field_objs = [oldforms.RadioSelectField]
                 params['ul_class'] = get_ul_class(self.radio_admin)
             else:
                 if self.null:
-                    field_objs = [forms.NullSelectField]
+                    field_objs = [oldforms.NullSelectField]
                 else:
-                    field_objs = [forms.SelectField]
+                    field_objs = [oldforms.SelectField]
             params['choices'] = self.get_choices_default()
         return field_objs, params
 
         if self.rel.raw_id_admin and not isinstance(rel_field, AutoField):
             return rel_field.get_manipulator_field_objs()
         else:
-            return [forms.IntegerField]
+            return [oldforms.IntegerField]
 
     def get_db_prep_save(self, value):
         if value == '' or value == None:
     def contribute_to_related_class(self, cls, related):
         setattr(cls, related.get_accessor_name(), ForeignRelatedObjectsDescriptor(related))
 
+    def formfield(self, **kwargs):
+        defaults = {'choices': self.get_choices_default(), 'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text}
+        defaults.update(kwargs)
+        return forms.ChoiceField(**defaults)
+
 class OneToOneField(RelatedField, IntegerField):
     def __init__(self, to, to_field=None, **kwargs):
         try:
             params['validator_list'].append(curry(manipulator_valid_rel_key, self, manipulator))
         else:
             if self.radio_admin:
-                field_objs = [forms.RadioSelectField]
+                field_objs = [oldforms.RadioSelectField]
                 params['ul_class'] = get_ul_class(self.radio_admin)
             else:
                 if self.null:
-                    field_objs = [forms.NullSelectField]
+                    field_objs = [oldforms.NullSelectField]
                 else:
-                    field_objs = [forms.SelectField]
+                    field_objs = [oldforms.SelectField]
             params['choices'] = self.get_choices_default()
         return field_objs, params
 
         if not cls._meta.one_to_one_field:
             cls._meta.one_to_one_field = self
 
+    def formfield(self, **kwargs):
+        defaults = {'choices': self.get_choices_default(), 'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text}
+        defaults.update(kwargs)
+        return forms.ChoiceField(**kwargs)
+
 class ManyToManyField(RelatedField, Field):
     def __init__(self, to, **kwargs):
         kwargs['verbose_name'] = kwargs.get('verbose_name', None)
             limit_choices_to=kwargs.pop('limit_choices_to', None),
             raw_id_admin=kwargs.pop('raw_id_admin', False),
             symmetrical=kwargs.pop('symmetrical', True))
+        self.db_table = kwargs.pop('db_table', None)
         if kwargs["rel"].raw_id_admin:
             kwargs.setdefault("validator_list", []).append(self.isValidIDList)
         Field.__init__(self, **kwargs)
 
     def get_manipulator_field_objs(self):
         if self.rel.raw_id_admin:
-            return [forms.RawIdAdminField]
+            return [oldforms.RawIdAdminField]
         else:
             choices = self.get_choices_default()
-            return [curry(forms.SelectMultipleField, size=min(max(len(choices), 5), 15), choices=choices)]
+            return [curry(oldforms.SelectMultipleField, size=min(max(len(choices), 5), 15), choices=choices)]
 
     def get_choices_default(self):
         return Field.get_choices(self, include_blank=False)
 
     def _get_m2m_db_table(self, opts):
         "Function that can be curried to provide the m2m table name for this relation"
-        return '%s_%s' % (opts.db_table, self.name)
+        if self.db_table:
+            return self.db_table
+        else:
+            return '%s_%s' % (opts.db_table, self.name)
 
     def _get_m2m_column_name(self, related):
         "Function that can be curried to provide the source column name for the m2m table"
     def set_attributes_from_rel(self):
         pass
 
+    def value_from_object(self, obj):
+        "Returns the value of this field in the given model instance."
+        return getattr(obj, self.attname).all()
+
+    def formfield(self, **kwargs):
+        # If initial is passed in, it's a list of related objects, but the
+        # MultipleChoiceField takes a list of IDs.
+        if kwargs.get('initial') is not None:
+            kwargs['initial'] = [i._get_pk_val() for i in kwargs['initial']]
+        defaults = {'choices': self.get_choices_default(), 'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text}
+        defaults.update(kwargs)
+        return forms.MultipleChoiceField(**defaults)
+
 class ManyToOneRel(object):
     def __init__(self, to, field_name, num_in_admin=3, min_num_in_admin=None,
         max_num_in_admin=None, num_extra_on_change=1, edit_inline=False,

File django/db/models/manager.py

-from django.db.models.query import QuerySet
+from django.db.models.query import QuerySet, EmptyQuerySet
 from django.dispatch import dispatcher
 from django.db.models import signals
 from django.db.models.fields import FieldDoesNotExist
     #######################
     # PROXIES TO QUERYSET #
     #######################
+    
+    def get_empty_query_set(self):
+        return EmptyQuerySet(self.model)
 
     def get_query_set(self):
         """Returns a new QuerySet object.  Subclasses can override this method
         to easily customise the behaviour of the Manager.
         """
         return QuerySet(self.model)
+    
+    def none(self):
+        return self.get_empty_query_set()
 
     def all(self):
         return self.get_query_set()

File django/db/models/manipulators.py

 from django.core.exceptions import ObjectDoesNotExist
-from django import forms
+from django import oldforms
 from django.core import validators
 from django.db.models.fields import FileField, AutoField
 from django.dispatch import dispatcher
                 self.man._prepare(model)
             return self.man
 
-class AutomaticManipulator(forms.Manipulator):
+class AutomaticManipulator(oldforms.Manipulator):
     def _prepare(cls, model):
         cls.model = model
         cls.manager = model._default_manager
 
         # Add field for ordering.
         if self.change and self.opts.get_ordered_objects():
-            self.fields.append(forms.CommaSeparatedIntegerField(field_name="order_"))
+            self.fields.append(oldforms.CommaSeparatedIntegerField(field_name="order_"))
 
     def save(self, new_data):
         # TODO: big cleanup when core fields go -> use recursive manipulators.
 def manipulator_validator_unique_for_date(from_field, date_field, opts, lookup_type, self, field_data, all_data):
     from django.db.models.fields.related import ManyToOneRel
     date_str = all_data.get(date_field.get_manipulator_field_names('')[0], None)
-    date_val = forms.DateField.html2python(date_str)
+    date_val = oldforms.DateField.html2python(date_str)
     if date_val is None:
         return # Date was invalid. This will be caught by another validator.
     lookup_kwargs = {'%s__year' % date_field.name: date_val.year}

File django/db/models/query.py

 from django.db import backend, connection, transaction
 from django.db.models.fields import DateField, FieldDoesNotExist
+from django.db.models.fields.generic import GenericRelation
 from django.db.models import signals
 from django.dispatch import dispatcher
 from django.utils.datastructures import SortedDict
 # Larger values are slightly faster at the expense of more storage space.
 GET_ITERATOR_CHUNK_SIZE = 100
 
+class EmptyResultSet(Exception):
+    pass
+
 ####################
 # HELPER FUNCTIONS #
 ####################
         extra_select = self._select.items()
 
         cursor = connection.cursor()
-        select, sql, params = self._get_sql_clause()
+        
+        try:
+            select, sql, params = self._get_sql_clause()
+        except EmptyResultSet:
+            raise StopIteration
+            
         cursor.execute("SELECT " + (self._distinct and "DISTINCT " or "") + ",".join(select) + sql, params)
         fill_cache = self._select_related
         index_end = len(self.model._meta.fields)
         counter._offset = None
         counter._limit = None
         counter._select_related = False
-        select, sql, params = counter._get_sql_clause()
+        
+        try:
+            select, sql, params = counter._get_sql_clause()
+        except EmptyResultSet:
+            return 0
+            
         cursor = connection.cursor()
         if self._distinct:
             id_col = "%s.%s" % (backend.quote_name(self.model._meta.db_table),
             field_names = [f.attname for f in self.model._meta.fields]
 
         cursor = connection.cursor()
-        select, sql, params = self._get_sql_clause()
+        
+        try:
+            select, sql, params = self._get_sql_clause()
+        except EmptyResultSet:
+            raise StopIteration
+        
         select = ['%s.%s' % (backend.quote_name(self.model._meta.db_table), backend.quote_name(c)) for c in columns]
         cursor.execute("SELECT " + (self._distinct and "DISTINCT " or "") + ",".join(select) + sql, params)
         while 1:
         if self._field.null:
             self._where.append('%s.%s IS NOT NULL' % \
                 (backend.quote_name(self.model._meta.db_table), backend.quote_name(self._field.column)))
-        select, sql, params = self._get_sql_clause()
+                
+        try:
+            select, sql, params = self._get_sql_clause()
+        except EmptyResultSet:
+            raise StopIteration
+        
         sql = 'SELECT %s %s GROUP BY 1 ORDER BY 1 %s' % \
             (backend.get_date_trunc_sql(self._kind, '%s.%s' % (backend.quote_name(self.model._meta.db_table),
             backend.quote_name(self._field.column))), sql, self._order)
         c._kind = self._kind
         c._order = self._order
         return c
+    
+class EmptyQuerySet(QuerySet):
+    def __init__(self, model=None):
+        super(EmptyQuerySet, self).__init__(model)
+        self._result_cache = []
+        
+    def iterator(self):
+        raise StopIteration
+        
+    def count(self):
+        return 0
+        
+    def delete(self):
+        pass
+
+    def _clone(self, klass=None, **kwargs):
+        c = super(EmptyQuerySet, self)._clone(klass, **kwargs)
+        c._result_cache = []
+        return c
 
 class QOperator(object):
     "Base class for QAnd and QOr"
     def get_sql(self, opts):
         joins, where, params = SortedDict(), [], []
         for val in self.args:
-            joins2, where2, params2 = val.get_sql(opts)
-            joins.update(joins2)
-            where.extend(where2)
-            params.extend(params2)
+            try:
+                joins2, where2, params2 = val.get_sql(opts)
+                joins.update(joins2)
+                where.extend(where2)
+                params.extend(params2)
+            except EmptyResultSet:
+                if not isinstance(self, QOr):
+                    raise EmptyResultSet
         if where:
             return joins, ['(%s)' % self.operator.join(where)], params
         return joins, [], params
         self.q = q
 
     def get_sql(self, opts):
-        joins, where, params = self.q.get_sql(opts)
-        where2 = ['(NOT (%s))' % " AND ".join(where)]
+        try:
+            joins, where, params = self.q.get_sql(opts)
+            where2 = ['(NOT (%s))' % " AND ".join(where)]
+        except EmptyResultSet:
+            return SortedDict(), [], []
         return joins, where2, params
 
 def get_where_clause(lookup_type, table_prefix, field_name, value):
     except KeyError:
         pass
     if lookup_type == 'in':
-        return '%s%s IN (%s)' % (table_prefix, field_name, ','.join(['%s' for v in value]))
+        in_string = ','.join(['%s' for id in value])
+        if in_string:
+            return '%s%s IN (%s)' % (table_prefix, field_name, in_string)
+        else:
+            raise EmptyResultSet
     elif lookup_type == 'range':
         return '%s%s BETWEEN %%s AND %%s' % (table_prefix, field_name)
     elif lookup_type in ('year', 'month', 'day'):
 
         pk_list = [pk for pk,instance in seen_objs[cls]]
         for related in cls._meta.get_all_related_many_to_many_objects():
+            if not isinstance(related.field, GenericRelation):
+                for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):
+                    cursor.execute("DELETE FROM %s WHERE %s IN (%s)" % \
+                        (qn(related.field.m2m_db_table()),
+                            qn(related.field.m2m_reverse_name()),
+                            ','.join(['%s' for pk in pk_list[offset:offset+GET_ITERATOR_CHUNK_SIZE]])),
+                        pk_list[offset:offset+GET_ITERATOR_CHUNK_SIZE])
+        for f in cls._meta.many_to_many:
+            if isinstance(f, GenericRelation):
+                from django.contrib.contenttypes.models import ContentType 
+                query_extra = 'AND %s=%%s' % f.rel.to._meta.get_field(f.content_type_field_name).column
+                args_extra = [ContentType.objects.get_for_model(cls).id]
+            else:
+                query_extra = ''
+                args_extra = []
             for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):
-                cursor.execute("DELETE FROM %s WHERE %s IN (%s)" % \
-                    (qn(related.field.m2m_db_table()),
-                        qn(related.field.m2m_reverse_name()),
-                        ','.join(['%s' for pk in pk_list[offset:offset+GET_ITERATOR_CHUNK_SIZE]])),
-                    pk_list[offset:offset+GET_ITERATOR_CHUNK_SIZE])
-        for f in cls._meta.many_to_many:
-            for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):
-                cursor.execute("DELETE FROM %s WHERE %s IN (%s)" % \
+                cursor.execute(("DELETE FROM %s WHERE %s IN (%s)" % \
                     (qn(f.m2m_db_table()), qn(f.m2m_column_name()),
-                    ','.join(['%s' for pk in pk_list[offset:offset+GET_ITERATOR_CHUNK_SIZE]])),
-                    pk_list[offset:offset+GET_ITERATOR_CHUNK_SIZE])
+                    ','.join(['%s' for pk in pk_list[offset:offset+GET_ITERATOR_CHUNK_SIZE]]))) + query_extra,
+                    pk_list[offset:offset+GET_ITERATOR_CHUNK_SIZE] + args_extra)
         for field in cls._meta.fields:
             if field.rel and field.null and field.rel.to in seen_objs:
                 for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):

File django/forms/__init__.py

-from django.core import validators
-from django.core.exceptions import PermissionDenied
-from django.utils.html import escape
-from django.conf import settings
-from django.utils.translation import gettext, ngettext
-
-FORM_FIELD_ID_PREFIX = 'id_'
-
-class EmptyValue(Exception):
-    "This is raised when empty data is provided"
-    pass
-
-class Manipulator(object):
-    # List of permission strings. User must have at least one to manipulate.
-    # None means everybody has permission.
-    required_permission = ''
-
-    def __init__(self):
-        # List of FormField objects
-        self.fields = []
-
-    def __getitem__(self, field_name):
-        "Looks up field by field name; raises KeyError on failure"
-        for field in self.fields:
-            if field.field_name == field_name:
-                return field
-        raise KeyError, "Field %s not found\n%s" % (field_name, repr(self.fields))
-
-    def __delitem__(self, field_name):
-        "Deletes the field with the given field name; raises KeyError on failure"
-        for i, field in enumerate(self.fields):
-            if field.field_name == field_name:
-                del self.fields[i]
-                return
-        raise KeyError, "Field %s not found" % field_name
-
-    def check_permissions(self, user):
-        """Confirms user has required permissions to use this manipulator; raises
-        PermissionDenied on failure."""
-        if self.required_permission is None:
-            return