Changeset 6339
- Timestamp:
- 09/15/07 16:46:18 (1 year ago)
- Files:
-
- django/branches/queryset-refactor/AUTHORS (modified) (1 diff)
- django/branches/queryset-refactor/django/contrib/auth/decorators.py (modified) (2 diffs)
- django/branches/queryset-refactor/django/contrib/comments/views/comments.py (modified) (9 diffs)
- django/branches/queryset-refactor/django/contrib/comments/views/karma.py (modified) (3 diffs)
- django/branches/queryset-refactor/django/contrib/comments/views/userflags.py (modified) (4 diffs)
- django/branches/queryset-refactor/django/contrib/formtools/preview.py (modified) (1 diff)
- django/branches/queryset-refactor/django/contrib/webdesign/templatetags/webdesign.py (modified) (1 diff)
- django/branches/queryset-refactor/django/contrib/webdesign/tests.py (modified) (1 diff)
- django/branches/queryset-refactor/django/core/handlers/base.py (modified) (1 diff)
- django/branches/queryset-refactor/django/core/handlers/modpython.py (modified) (1 diff)
- django/branches/queryset-refactor/django/core/handlers/wsgi.py (modified) (1 diff)
- django/branches/queryset-refactor/django/core/management/commands/shell.py (modified) (2 diffs)
- django/branches/queryset-refactor/django/core/management/validation.py (modified) (1 diff)
- django/branches/queryset-refactor/django/db/backends/mysql/base.py (modified) (3 diffs)
- django/branches/queryset-refactor/django/db/backends/oracle/base.py (modified) (4 diffs)
- django/branches/queryset-refactor/django/http/__init__.py (modified) (2 diffs)
- django/branches/queryset-refactor/django/middleware/gzip.py (modified) (1 diff)
- django/branches/queryset-refactor/django/shortcuts/__init__.py (modified) (1 diff)
- django/branches/queryset-refactor/django/template/defaultfilters.py (modified) (2 diffs)
- django/branches/queryset-refactor/django/utils/cache.py (modified) (1 diff)
- django/branches/queryset-refactor/django/utils/feedgenerator.py (modified) (1 diff)
- django/branches/queryset-refactor/docs/add_ons.txt (modified) (1 diff)
- django/branches/queryset-refactor/docs/form_preview.txt (copied) (copied from django/trunk/docs/form_preview.txt)
- django/branches/queryset-refactor/docs/shortcuts.txt (modified) (3 diffs)
- django/branches/queryset-refactor/docs/templates.txt (modified) (1 diff)
- django/branches/queryset-refactor/docs/tutorial01.txt (modified) (1 diff)
- django/branches/queryset-refactor/tests/modeltests/model_forms/models.py (modified) (6 diffs)
- django/branches/queryset-refactor/tests/regressiontests/backends/models.py (modified) (1 diff)
- django/branches/queryset-refactor/tests/regressiontests/fixtures_regress/models.py (modified) (2 diffs)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
django/branches/queryset-refactor/AUTHORS
r6337 r6339 253 253 Brian Rosner <brosner@gmail.com> 254 254 Oliver Rutherfurd <http://rutherfurd.net/> 255 ryankanno 255 256 Ivan Sagalaev (Maniac) <http://www.softwaremaniacs.org/> 256 257 Vinay Sajip <vinay_sajip@yahoo.co.uk> django/branches/queryset-refactor/django/contrib/auth/decorators.py
r6337 r6339 1 1 from django.contrib.auth import REDIRECT_FIELD_NAME 2 2 from django.http import HttpResponseRedirect 3 from urllib importquote3 from django.utils.http import urlquote 4 4 5 5 def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): … … 16 16 if test_func(request.user): 17 17 return view_func(request, *args, **kwargs) 18 return HttpResponseRedirect('%s?%s=%s' % (login_url, redirect_field_name, quote(request.get_full_path())))18 return HttpResponseRedirect('%s?%s=%s' % (login_url, redirect_field_name, urlquote(request.get_full_path()))) 19 19 _checklogin.__doc__ = view_func.__doc__ 20 20 _checklogin.__dict__ = view_func.__dict__ django/branches/queryset-refactor/django/contrib/comments/views/comments.py
r5848 r6339 156 156 return c 157 157 158 def post_comment(request ):158 def post_comment(request, extra_context=None, context_processors=None): 159 159 """ 160 160 Post a comment … … 186 186 choice of ratings 187 187 """ 188 if extra_context is None: extra_context = {} 188 189 if not request.POST: 189 190 raise Http404, _("Only POSTs are allowed") … … 245 246 'rating_range': rating_range, 246 247 'rating_choices': rating_choices, 247 }, context_instance=RequestContext(request ))248 }, context_instance=RequestContext(request, extra_context, context_processors)) 248 249 elif 'post' in request.POST: 249 250 # If the IP is banned, mail the admins, do NOT save the comment, and … … 258 259 raise Http404, _("The comment form didn't provide either 'preview' or 'post'") 259 260 260 def post_free_comment(request ):261 def post_free_comment(request, extra_context=None, context_processors=None): 261 262 """ 262 263 Post a free comment (not requiring a log in) … … 278 279 post a comment). 279 280 """ 281 if extra_context is None: extra_context = {} 280 282 if not request.POST: 281 283 raise Http404, _("Only POSTs are allowed") … … 308 310 'target': target, 309 311 'hash': security_hash, 310 }, context_instance=RequestContext(request ))312 }, context_instance=RequestContext(request, extra_context, context_processors)) 311 313 elif 'post' in request.POST: 312 314 # If the IP is banned, mail the admins, do NOT save the comment, and … … 322 324 raise Http404, _("The comment form didn't provide either 'preview' or 'post'") 323 325 324 def comment_was_posted(request ):326 def comment_was_posted(request, extra_context=None, context_processors=None): 325 327 """ 326 328 Display "comment was posted" success page … … 331 333 The object the comment was posted on 332 334 """ 335 if extra_context is None: extra_context = {} 333 336 obj = None 334 337 if 'c' in request.GET: … … 339 342 except ObjectDoesNotExist: 340 343 pass 341 return render_to_response('comments/posted.html', {'object': obj}, context_instance=RequestContext(request)) 344 return render_to_response('comments/posted.html', {'object': obj}, 345 context_instance=RequestContext(request, extra_context, context_processors)) django/branches/queryset-refactor/django/contrib/comments/views/karma.py
r5609 r6339 5 5 from django.utils.translation import ugettext as _ 6 6 7 def vote(request, comment_id, vote ):7 def vote(request, comment_id, vote, extra_context=None, context_processors=None): 8 8 """ 9 9 Rate a comment (+1 or -1) … … 14 14 `comments.comments` object being rated 15 15 """ 16 if extra_context is None: extra_context = {} 16 17 rating = {'up': 1, 'down': -1}.get(vote, False) 17 18 if not rating: … … 28 29 # Reload comment to ensure we have up to date karma count 29 30 comment = Comment.objects.get(pk=comment_id) 30 return render_to_response('comments/karma_vote_accepted.html', {'comment': comment}, context_instance=RequestContext(request)) 31 return render_to_response('comments/karma_vote_accepted.html', {'comment': comment}, 32 context_instance=RequestContext(request, extra_context, context_processors)) django/branches/queryset-refactor/django/contrib/comments/views/userflags.py
r4265 r6339 7 7 from django.conf import settings 8 8 9 def flag(request, comment_id ):9 def flag(request, comment_id, extra_context=None, context_processors=None): 10 10 """ 11 11 Flags a comment. Confirmation on GET, action on POST. … … 16 16 the flagged `comments.comments` object 17 17 """ 18 if extra_context is None: extra_context = {} 18 19 comment = get_object_or_404(Comment,pk=comment_id, site__id__exact=settings.SITE_ID) 19 20 if request.POST: 20 21 UserFlag.objects.flag(comment, request.user) 21 22 return HttpResponseRedirect('%sdone/' % request.path) 22 return render_to_response('comments/flag_verify.html', {'comment': comment}, context_instance=RequestContext(request)) 23 return render_to_response('comments/flag_verify.html', {'comment': comment}, 24 context_instance=RequestContext(request, extra_context, context_processors)) 23 25 flag = login_required(flag) 24 26 25 def flag_done(request, comment_id): 27 def flag_done(request, comment_id, extra_context=None, context_processors=None): 28 if extra_context is None: extra_context = {} 26 29 comment = get_object_or_404(Comment,pk=comment_id, site__id__exact=settings.SITE_ID) 27 return render_to_response('comments/flag_done.html', {'comment': comment}, context_instance=RequestContext(request)) 30 return render_to_response('comments/flag_done.html', {'comment': comment}, 31 context_instance=RequestContext(request, extra_context, context_processors)) 28 32 29 def delete(request, comment_id ):33 def delete(request, comment_id, extra_context=None, context_processors=None): 30 34 """ 31 35 Deletes a comment. Confirmation on GET, action on POST. … … 36 40 the flagged `comments.comments` object 37 41 """ 42 if extra_context is None: extra_context = {} 38 43 comment = get_object_or_404(Comment,pk=comment_id, site__id__exact=settings.SITE_ID) 39 44 if not Comment.objects.user_is_moderator(request.user): … … 47 52 m.save() 48 53 return HttpResponseRedirect('%sdone/' % request.path) 49 return render_to_response('comments/delete_verify.html', {'comment': comment}, context_instance=RequestContext(request)) 54 return render_to_response('comments/delete_verify.html', {'comment': comment}, 55 context_instance=RequestContext(request, extra_context, context_processors)) 50 56 delete = login_required(delete) 51 57 52 def delete_done(request, comment_id): 58 def delete_done(request, comment_id, extra_context=None, context_processors=None): 59 if extra_context is None: extra_context = {} 53 60 comment = get_object_or_404(Comment,pk=comment_id, site__id__exact=settings.SITE_ID) 54 return render_to_response('comments/delete_done.html', {'comment': comment}, context_instance=RequestContext(request)) 61 return render_to_response('comments/delete_done.html', {'comment': comment}, 62 context_instance=RequestContext(request, extra_context, context_processors)) django/branches/queryset-refactor/django/contrib/formtools/preview.py
r5293 r6339 1 1 """ 2 2 Formtools Preview application. 3 4 This is an abstraction of the following workflow:5 6 "Display an HTML form, force a preview, then do something with the submission."7 8 Given a django.newforms.Form object that you define, this takes care of the9 following:10 11 * Displays the form as HTML on a Web page.12 * Validates the form data once it's submitted via POST.13 * If it's valid, displays a preview page.14 * If it's not valid, redisplays the form with error messages.15 * At the preview page, if the preview confirmation button is pressed, calls16 a hook that you define -- a done() method.17 18 The framework enforces the required preview by passing a shared-secret hash to19 the preview page. If somebody tweaks the form parameters on the preview page,20 the form submission will fail the hash comparison test.21 22 Usage23 =====24 25 Subclass FormPreview and define a done() method:26 27 def done(self, request, cleaned_data):28 # ...29 30 This method takes an HttpRequest object and a dictionary of the form data after31 it has been validated and cleaned. It should return an HttpResponseRedirect.32 33 Then, just instantiate your FormPreview subclass by passing it a Form class,34 and pass that to your URLconf, like so:35 36 (r'^post/$', MyFormPreview(MyForm)),37 38 The FormPreview class has a few other hooks. See the docstrings in the source39 code below.40 41 The framework also uses two templates: 'formtools/preview.html' and42 'formtools/form.html'. You can override these by setting 'preview_template' and43 'form_template' attributes on your FormPreview subclass. See44 django/contrib/formtools/templates for the default templates.45 3 """ 46 4 django/branches/queryset-refactor/django/contrib/webdesign/templatetags/webdesign.py
r5609 r6339 63 63 count = parser.compile_filter(count) 64 64 if len(bits) != 1: 65 raise TemplateSyntaxError("Incorrect format for %r tag" % tagname)65 raise template.TemplateSyntaxError("Incorrect format for %r tag" % tagname) 66 66 return LoremNode(count, method, common) 67 67 lorem = register.tag(lorem) django/branches/queryset-refactor/django/contrib/webdesign/tests.py
r5876 r6339 8 8 ['Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'] 9 9 10 >>> from django.template import loader, Context 11 >>> t = loader.get_template_from_string("{% load webdesign %}{% lorem 3 w %}") 12 >>> t.render(Context({})) 13 u'lorem ipsum dolor' 10 14 """ 11 15 django/branches/queryset-refactor/django/core/handlers/base.py
r6337 r6339 143 143 this function converts them to absolute paths. 144 144 """ 145 if ' location' in response.headersand http.get_host(request):145 if 'Location' in response and http.get_host(request): 146 146 response['Location'] = request.build_absolute_uri(response['Location']) 147 147 return response django/branches/queryset-refactor/django/core/handlers/modpython.py
r5629 r6339 160 160 # Convert our custom HttpResponse object back into the mod_python req. 161 161 req.content_type = response['Content-Type'] 162 for key, value in response. headers.items():163 if key != ' Content-Type':162 for key, value in response.items(): 163 if key != 'content-type': 164 164 req.headers_out[str(key)] = str(value) 165 165 for c in response.cookies.values(): django/branches/queryset-refactor/django/core/handlers/wsgi.py
r5868 r6339 209 209 status_text = 'UNKNOWN STATUS CODE' 210 210 status = '%s %s' % (response.status_code, status_text) 211 response_headers = [(str(k), str(v)) for k, v in response. headers.items()]211 response_headers = [(str(k), str(v)) for k, v in response.items()] 212 212 for c in response.cookies.values(): 213 213 response_headers.append(('Set-Cookie', str(c.output(header='')))) django/branches/queryset-refactor/django/core/management/commands/shell.py
r6075 r6339 1 import os 1 2 from django.core.management.base import NoArgsCommand 2 3 from optparse import make_option … … 44 45 readline.set_completer(rlcompleter.Completer(imported_objects).complete) 45 46 readline.parse_and_bind("tab:complete") 47 48 # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system 49 # conventions and get $PYTHONSTARTUP first then import user. 50 if not use_plain: 51 pythonrc = os.environ.get("PYTHONSTARTUP") 52 if pythonrc and os.path.isfile(pythonrc): 53 try: 54 execfile(pythonrc) 55 except NameError: 56 pass 57 # This will import .pythonrc.py as a side-effect 58 import user 46 59 code.interact(local=imported_objects) django/branches/queryset-refactor/django/core/management/validation.py
r6337 r6339 53 53 e.add(opts, '"%s": prepopulate_from should be a list or tuple.' % f.name) 54 54 if f.choices: 55 if isinstance(f.choices, basestring) or \ 56 not is_iterable(f.choices): 55 if isinstance(f.choices, basestring) or not is_iterable(f.choices): 57 56 e.add(opts, '"%s": "choices" should be iterable (e.g., a tuple or list).' % f.name) 58 57 else: django/branches/queryset-refactor/django/db/backends/mysql/base.py
r5983 r6339 24 24 import types 25 25 import re 26 27 # Raise exceptions for database warnings if DEBUG is on 28 from django.conf import settings 29 if settings.DEBUG: 30 from warnings import filterwarnings 31 filterwarnings("error", category=Database.Warning) 26 32 27 33 DatabaseError = Database.DatabaseError … … 154 160 155 161 def _cursor(self, settings): 156 from warnings import filterwarnings157 162 if not self._valid_connection(): 158 163 kwargs = { … … 176 181 self.connection = Database.connect(**kwargs) 177 182 cursor = self.connection.cursor() 178 if settings.DEBUG:179 filterwarnings("error", category=Database.Warning)180 183 return cursor 181 184 django/branches/queryset-refactor/django/db/backends/oracle/base.py
r6337 r6339 291 291 # empty string. 292 292 if value is None and isinstance(field, Field) and field.empty_strings_allowed: 293 value = ''293 value = u'' 294 294 # Convert 1 or 0 to True or False 295 295 elif value in (1, 0) and isinstance(field, (BooleanField, NullBooleanField)): … … 355 355 table_name = sequence_info['table'] 356 356 seq_name = get_sequence_name(table_name) 357 query = _get_sequence_reset_sql() % {'sequence': seq_name, 'table': self.quote_name(table_name)} 357 column_name = self.quote_name(sequence_info['column'] or 'id') 358 query = _get_sequence_reset_sql() % {'sequence': seq_name, 359 'table': self.quote_name(table_name), 360 'column': column_name} 358 361 sql.append(query) 359 362 return sql … … 369 372 if isinstance(f, models.AutoField): 370 373 sequence_name = get_sequence_name(model._meta.db_table) 371 output.append(query % {'sequence':sequence_name, 372 'table':model._meta.db_table}) 374 column_name = self.quote_name(f.db_column or f.name) 375 output.append(query % {'sequence': sequence_name, 376 'table': model._meta.db_table, 377 'column': column_name}) 373 378 break # Only one AutoField is allowed per model, so don't bother continuing. 374 379 for f in model._meta.many_to_many: 375 380 sequence_name = get_sequence_name(f.m2m_db_table()) 376 output.append(query % {'sequence':sequence_name, 377 'table':f.m2m_db_table()}) 381 output.append(query % {'sequence': sequence_name, 382 'table': f.m2m_db_table(), 383 'column': self.quote_name('id')}) 378 384 return output 379 385 … … 508 514 BEGIN 509 515 LOCK TABLE %(table)s IN SHARE MODE; 510 SELECT NVL(MAX( id), 0) INTO startvalue FROM %(table)s;516 SELECT NVL(MAX(%(column)s), 0) INTO startvalue FROM %(table)s; 511 517 SELECT %(sequence)s.nextval INTO cval FROM dual; 512 518 cval := startvalue - cval; django/branches/queryset-refactor/django/http/__init__.py
r6337 r6339 247 247 self._container = [content] 248 248 self._is_string = True 249 self. headers = {'content-type': content_type}249 self._headers = {'content-type': content_type} 250 250 self.cookies = SimpleCookie() 251 251 if status: … … 255 255 "Full HTTP message, including headers" 256 256 return '\n'.join(['%s: %s' % (key, value) 257 for key, value in self. headers.items()]) \257 for key, value in self._headers.items()]) \ 258 258 + '\n\n' + self.content 259 259 260 260 def __setitem__(self, header, value): 261 self. headers[header.lower()] = value261 self._headers[header.lower()] = value 262 262 263 263 def __delitem__(self, header): 264 264 try: 265 del self. headers[header.lower()]265 del self._headers[header.lower()] 266 266 except KeyError: 267 267 pass 268 268 269 269 def __getitem__(self, header): 270 return self. headers[header.lower()]270 return self._headers[header.lower()] 271 271 272 272 def has_header(self, header): 273 273 "Case-insensitive check for a header" 274 return self.headers.has_key(header.lower()) 274 return self._headers.has_key(header.lower()) 275 276 __contains__ = has_header 277 278 def items(self): 279 return self._headers.items() 280 281 def get(self, header, alternate): 282 return self._headers.get(header, alternate) 275 283 276 284 def set_cookie(self, key, value='', max_age=None, expires=None, path='/', domain=None, secure=None): django/branches/queryset-refactor/django/middleware/gzip.py
r5875 r6339 21 21 # Avoid gzipping if we've already got a content-encoding or if the 22 22 # content-type is Javascript (silly IE...) 23 is_js = "javascript" in response. headers.get('Content-Type', '').lower()23 is_js = "javascript" in response.get('Content-Type', '').lower() 24 24 if response.has_header('Content-Encoding') or is_js: 25 25 return response django/branches/queryset-refactor/django/shortcuts/__init__.py
r6337 r6339 15 15 django.template.loader.render_to_string() with the passed arguments. 16 16 """ 17 httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype' )}17 httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)} 18 18 return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) 19 19 load_and_render = render_to_response # For backwards compatibility. django/branches/queryset-refactor/django/template/defaultfilters.py
r6019 r6339 255 255 256 256 def linebreaks(value): 257 "Converts newlines into <p> and <br />s" 257 """ 258 Replaces line breaks in plain text with appropriate HTML; a single 259 newline becomes an HTML line break (``<br />``) and a new line 260 followed by a blank line becomes a paragraph break (``</p>``). 261 """ 258 262 from django.utils.html import linebreaks 259 263 return linebreaks(value) … … 261 265 262 266 def linebreaksbr(value): 263 "Converts newlines into <br />s" 267 """ 268 Converts all newlines in a piece of plain text to HTML line breaks 269 (``<br />``). 270 """ 264 271 return value.replace('\n', '<br />') 265 272 linebreaksbr = stringfilter(linebreaksbr) django/branches/queryset-refactor/django/utils/cache.py
r5712 r6339 43 43 t = s.split('=',1) 44 44 if len(t) > 1: 45 return (t[0].lower() .replace('-', '_'), t[1])45 return (t[0].lower(), t[1]) 46 46 else: 47 return (t[0].lower() .replace('-', '_'), True)47 return (t[0].lower(), True) 48 48 49 49 def dictvalue(t): django/branches/queryset-refactor/django/utils/feedgenerator.py
r5643 r6339 28 28 29 29 def rfc3339_date(date): 30 return date.strftime('%Y-%m-%dT%H:%M:%SZ') 30 if date.tzinfo: 31 return date.strftime('%Y-%m-%dT%H:%M:%S%z') 32 else: 33 return date.strftime('%Y-%m-%dT%H:%M:%SZ') 31 34 32 35 def get_tag_uri(url, date): django/branches/queryset-refactor/docs/add_ons.txt
r5985 r6339 71 71 "Display an HTML form, force a preview, then do something with the submission." 72 72 73 Full documentation for this feature does not yet exist, but you can read the 74 code and docstrings in ``django/contrib/formtools/preview.py`` for a start. 73 See the `form preview documentation`_. 74 75 .. _form preview documentation: ../form_preview/ 75 76 76 77 humanize django/branches/queryset-refactor/docs/shortcuts.txt
r6337 r6339 7 7 introduce controlled coupling for convenience's sake. 8 8 9 ``render_to_response ``10 ====================== 9 ``render_to_response()`` 10 ======================== 11 11 12 12 ``django.shortcuts.render_to_response`` renders a given template with a given … … 14 14 text. 15 15 16 Example:: 16 Required arguments 17 ------------------ 18 19 ``template`` 20 The full name of a template to use. 21 22 Optional arguments 23 ------------------ 24 25 ``context`` 26 A dictionary of values to add to the template context. By default, this 27 is an empty dictionary. If a value in the dictionary is callable, the 28 view will call it just before rendering the template. 29 30 ``mimetype`` 31 **New in Django development version:** The MIME type to use for the 32 resulting document. Defaults to the value of the ``DEFAULT_CONTENT_TYPE`` 33 setting. 34 35 Example 36 ------- 37 38 The following example renders the template ``myapp/index.html`` with the 39 MIME type ``application/xhtml+xml``:: 17 40 18 41 from django.shortcuts import render_to_response 19 r = render_to_response('myapp/template.html', {'foo': 'bar'}) 42 43 def my_view(request): 44 # View code here... 45 return render_to_response('myapp/index.html', {"foo": "bar"}, 46 mimetype="application/xhtml+xml") 20 47 21 48 This example is equivalent to:: … … 23 50 from django.http import HttpResponse 24 51 from django.template import Context, loader 25 t = loader.get_template('myapp/template.html') 26 c = Context({'foo': 'bar'}) 27 r = HttpResponse(t.render(c)) 52 53 def my_view(request): 54 # View code here... 55 t = loader.get_template('myapp/template.html') 56 c = Context({'foo': 'bar'}) 57 r = HttpResponse(t.render(c), 58 mimetype="application/xhtml+xml") 59 60 .. _an HttpResponse object: ../request_response/#httpresponse-objects 28 61 29 62 ``get_object_or_404`` 30 63 ===================== 31 64 32 ``django.shortcuts.get_object_or_404`` calls ` `get()``on a given model65 ``django.shortcuts.get_object_or_404`` calls `get()`_ on a given model 33 66 manager, but it raises ``django.http.Http404`` instead of the model's 34 67 ``DoesNotExist`` exception. 68 69 Required arguments 70 ------------------ 71 72 ``klass`` 73 A ``Model``, ``Manager`` or ``QuerySet`` instance from which to get the 74 object. 75 76 ``**kwargs`` 77 Lookup parameters, which should be in the format accepted by ``get()`` and 78 ``filter()``. 79 80 Example 81 ------- 82 83 The following example gets the object with the primary key of 1 from 84 ``MyModel``:: 85 86 from django.shortcuts import get_object_or_404 87 88 def my_view(request): 89 my_object = get_object_or_404(MyModel, pk=1) 90 91 This example is equivalent to:: 92 93 from django.http import Http404 94 95 def my_view(request): 96 try: 97 my_object = MyModel.object.get(pk=1) 98 except MyModel.DoesNotExist: 99 raise Http404 100 101 Note: As with ``get()``, an ``AssertionError`` will be raised if more than 102 one object is found. 103 104 .. _get(): ../db-api/#get-kwargs 35 105 36 106 ``get_list_or_404`` 37 107 =================== 38 108 39 ``django.shortcuts.get_list_or_404`` returns the result of ` `filter()``on a109 ``django.shortcuts.get_list_or_404`` returns the result of `filter()`_ on a 40 110 given model manager, raising ``django.http.Http404`` if the resulting list is 41 111 empty. 112 113 Required arguments 114 ------------------ 115 116 ``klass`` 117 A ``Model``, ``Manager`` or ``QuerySet`` instance from which to get the 118 object. 119 120 ``**kwargs`` 121 Lookup parameters, which should be in the format accepted by ``get()`` and 122 ``filter()``. 123 124 Example 125 ------- 126 127 The following example gets all published objects from ``MyModel``:: 128 129 from django.shortcuts import get_list_or_404 130 131 def my_view(request): 132 my_objects = get_list_or_404(MyModel, published=True) 133 134 This example is equivalent to:: 135 136 from django.http import Http404 137 138 def my_view(request): 139 my_objects = MyModels.object.filter(published=True) 140 if not my_objects: 141 raise Http404 142 143 .. _filter(): ../db-api/#filter-kwargs django/branches/queryset-refactor/docs/templates.txt
r6334 r6339 1136 1136 ~~~~~~~~~~ 1137 1137 1138 Converts newlines into ``<p>`` and ``<br />`` tags. 1138 Replaces line breaks in plain text with appropriate HTML; a single 1139 newline becomes an HTML line break (``<br />``) and a new line 1140 followed by a blank line becomes a paragraph break (``</p>``). 1139 1141 1140 1142 linebreaksbr 1141 1143 ~~~~~~~~~~~~ 1142 1144 1143 Converts newlines into ``<br />`` tags. 1145 Converts all newlines in a piece of plain text to HTML line breaks 1146 (``<br />``). 1144 1147 1145 1148 linenumbers django/branches/queryset-refactor/docs/tutorial01.txt
r6040 r6339 41 41 code, then run the command ``django-admin.py startproject mysite``. This 42 42 will create a ``mysite`` directory in your current directory. 43 44 .. admonition:: Max OS X permissions 45 46 If you're using Mac OS X, you may see the message "permission 47 denied" when you try to run ``django-admin.py startproject``. This 48 is because, on Unix-based systems like OS X, a file must be marked 49 as "exceutable" before it can be run as a program. To do this, open 50 Terminal.app and navigate (using the `cd` command) to the directory 51 where ``django-admin.py`` is installed, then run the command 52 ``chmod +x django-admin.py``. 43 53 44 54 .. note:: django/branches/queryset-refactor/tests/modeltests/model_forms/models.py
r6065 r6339 116 116 >>> obj 117 117 <Category: It's a test> 118 >>> Category.objects. all()118 >>> Category.objects.order_by('name') 119 119 [<Category: Entertainment>, <Category: It's a test>] 120 120 … … 130 130 >>> obj 131 131 <Category: Third test> 132 >>> Category.objects. all()132 >>> Category.objects.order_by('name') 133 133 [<Category: Entertainment>, <Category: It's a test>] 134 134 >>> obj.save() 135 >>> Category.objects. all()135 >>> Category.objects.order_by('name') 136 136 [<Category: Entertainment>, <Category: It's a test>, <Category: Third test>] 137 137 … … 307 307 1 308 308 >>> new_art = Article.objects.get(id=1) 309 >>> new_art.categories. all()309 >>> new_art.categories.order_by('name') 310 310 [<Category: Entertainment>, <Category: It's a test>] 311 311 … … 328 328 2 329 329 >>> new_art = Article.objects.get(id=2) 330 >>> new_art.categories. all()330 >>> new_art.categories.order_by('name') 331 331 [<Category: Entertainment>, <Category: It's a test>] 332 332 … … 349 349 >>> new_art = f.save(commit=False) 350 350 351 # Manually save the instance 351 # Manually save the instance 352 352 >>> new_art.save() 353 353 >>> new_art.id … … 361 361 # Save the m2m data on the form 362 362 >>> f.save_m2m() 363 >>> new_art.categories. all()363 >>> new_art.categories.order_by('name') 364 364 [<Category: Entertainment>, <Category: It's a test>] 365 365 django/branches/queryset-refactor/tests/regressiontests/backends/models.py
r6337 r6339 18 18 [<Square: -5 ** 2 == 25>, <Square: -4 ** 2 == 16>, <Square: -3 ** 2 == 9>, <Square: -2 ** 2 == 4>, <Square: -1 ** 2 == 1>, <Square: 0 ** 2 == 0>, <Square: 1 ** 2 == 1>, <Square: 2 ** 2 == 4>, <Square: 3 ** 2 == 9>, <Square: 4 ** 2 == 16>, <Square: 5 ** 2 == 25>] 19 19 20 #4765: executemany with params=None or params=[] does nothing 21 >>> cursor.executemany('INSERT INTO BACKENDS_SQUARE (ROOT, SQUARE) VALUES (%s, %s)', None) and None or None 22 >>> Square.objects.count() 23 11 24 20 #4765: executemany with params=[] does nothing 25 21 >>> cursor.executemany('INSERT INTO BACKENDS_SQUARE (ROOT, SQUARE) VALUES (%s, %s)', []) and None or None 26 22 >>> Square.objects.count() django/branches/queryset-refactor/tests/regressiontests/fixtures_regress/models.py
r5898 r6339 1 1 from django.db import models 2 2 from django.contrib.auth.models import User 3 from django.conf import settings 3 4 4 5 class Animal(models.Model):&nb
