Login

Top-rated snippets

Snippet List

Browser Verification

A page we used on Curse to stop users who are new, who are using old browsers (ones who usually have extreme issues with CSS handling) and recommend they update. Can easily be modified to suit your needs.

  • middleware
  • browsers
  • validation
Read More

Whore links

Finds links from a body of html so you can display them elsewhere.

  • beautiful-soup
  • links
Read More

Format transition middleware

Note: This is a testing middleware. This snippets may be changed frequently later. What's it ----------- Sometimes I thought thow to easy the output data into another format, except html format. One way, you can use decorator, just like: @render_template(template='xxx') def viewfunc(request,...): And the output data of viewfunc should be pure data. And if want to output json format, you should change the decorator to: @json_response def viewfunc(request,...): I think it's not difficult. But if we can make it easier? Of cause, using middleware. So you can see the code of `process_response`, it'll judge the response object first, if it's an instance of HttpResponse, then directly return it. If it's not, then get the format of requst, if it's `json` format, then use json_response() to render the result. How to setup `request.format`? In `process_request` you and see, if the `request.REQUEST` has a `format` (you can setup it in settings.py with FORMAT_STRING option), then the `request.format` will be set as it. If there is not a such key, then the default will be `json`. So in your view code, you can just return a python variable, this middleware will automatically render this python variable into json format data and return. For 0.2 it support xml-rpc. But it's very different from common implementation. For server url, you just need put the same url as the normal url, for example: http://localhost:8000/booklist/ajax_list/?format=xmlrpc Notice that the format is 'xmlrpc'. A text client program is: from xmlrpclib import ServerProxy server = ServerProxy("http://localhost:8000/booklist/ajax_list/?format=xmlrpc", verbose=True) print server.booklist({'name':'limodou'}) And the method 'booklist' of server is useless, because the url has include the really view function, so you can use any name after `server`. And for parameters of the method, you should use a dict, and this dict will automatically convert into request.POST item. For above example, `{'name':'limodou'}`, you can visit it via `request.POST['name']` . For `html` format, you can register a `format_processor` callable object in `request` object. And middleware will use this callable object if the format is `html`. Intall --------- Because the view function may return non-HttpResponse object, so this middleware should be installed at the end of MIDDLEWARE_CLASSES sections, so that the `process_response` of this middleware can be invoked at the first time before others middlewares. And I also think this mechanism can be extended later, for example support xml-rpc, template render later, etc, but I have not implemented them, just a thought. Options --------- FORMAT_STRING used for specify the key name of format variable pair in QUERY_STRING or POST data, if you don't set it in settings.py, default is 'format'. DEFAYLT_FORMAT used for default format, if you don't set it in settings.py, default is 'json'. Reference ----------- Snippets 8 [ajax protocol for data](http://www.djangosnippets.org/snippets/8/) for json_response

  • middleware
  • format
  • json
Read More

Another pygments for ReST

This is like [snippet 36](/snippets/36/). And it'll return css also. And it's not a filter.If the code parameter is skip, it'll test the code first, and if there is not a suiable lexer for the code, then use default python lexer to render the code. The code lanauage parameter is comes from pygments lexer alias. How to use it ---------------- html = to_html(rest_text) And there is a level parameter in to_html function, default is `2`, it's the sections level. And the html will be `css style + body` How to write ReST --------------------- Below is a example. This is a test. .. code:: def code(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): opt = {'display':'on'} opt.update(options) docnodes.Node(content, ''.join(arguments), **opt) if opt['display'].lower() == 'on': return [nodes.literal_block('', '\n'.join(content))] else: return [] .. code:: html+django <h1 id="title">通讯录</h1> <hr> <div> <table border="0" width="500"> <tr align="right"> <td>{% if has_previous %} <a href="/address?page={{ previous }}">上一页</a> {% endif %} {% if has_next %} <a href="/address?page={{ next }}">下一页</a> {% endif %}</td></tr> </table>

  • pygments
  • rest
Read More

Validator for data

This module is not aimed to replace the newforms, but I would like manually write html code, and just need a pure validate module, so I write this, and many things may be similar with newforms. So if you like me would only need a pure validator module, you can use it. And it has some different features from newforms: 1. Support validator_list parameter, so you could use it just like the old manipuator class 2. Supply easy method, such as `validate_and_save()`, so you can pass a request object, and get a tuple result `(flag, obj_or_error)`, if the `flag` is `True`, then the next value is an object; and if the `flag` is `False`, then the next value is error message. 3. Each field has a `validate_and_get` method, and it'll validate first and then return the result, maybe an object or error message. Just like above. 4. SplitDateTimeField is somewhat different from the newforms. For example:: c = SplitDateTimeField('date', 'time') print c.validate_and_get({'date':'2006/11/30', 'time':'12:13'}) So the first parameter is DateField's field_name, and the second parameter is TimeField's field_name. 5. Add yyyy/mm/dd date format support 6. Support default value of a field. You can add a default value for a field, if this field is not required, and the value is *empty*, Validator will return the default value. This module is new, so many things could be changed.

  • validator
Read More

Add Toggle Switch Widget to Django Forms

Implementation Suggestions use: ``` ....... widgets = { ...... }), 'solicitada_mpu': ToggleSwitchWidget(size='sm', active_color='#9333ea', inactive_color='#ccc', active_text='YES', inactive_text='NO' ), ............... ```

  • ToggleSwitchWidget
  • toggle-switches
Read More

Mask sensitive data from logger

This will help to secure the sensitive secrets, token, api keys, etc from logger. As we know there is security issue when we include the sensitive information to the logger in case logger got leaked/hacked. Before: ``` INFO ('192.168.1.1', 33321) - "WebSocket /ssh?token=abcdefg&width=20&heigh20" ``` After: ``` INFO ('192.168.1.1', 33321) - "WebSocket /ssh?token=********&width=20&heigh20" ```

  • django
  • security
  • logging
  • logger
Read More

Serializer factory with Django Rest Framework

Creates a model serializer class on the fly, just taking the model (class) as its argument. My use case: When importing data from spreadsheets, the DRF serializers are an easy way to create model instances from a dictionary. This function saves me from creating a custom serializer each time I add a new importer. Using `__all__` is dangerous ;-)

Read More

Django Collapsed Stacked Inlines

A simple jQuery javascript that collapses all stacked inline rows for better handling of large inline fieldsets. It also adds "Show"/"Hide"-buttons for showing/hiding each row, which could be customized and styled using css. **Usage (see below for example):** Include the javascript on your admin page, together with jQuery, and it'll automatically affect all stacked inlines. **Works with** Django 3.1.4 (Might work with other versions with or without adjustments, but not tested) **Use example:** *admin.py:* class DateInline(admin.StackedInline): model = Date extra = 10 class EventAdmin(admin.ModelAdmin): inlines = [DateInline] class Media: js = ['js/collapsed-stacked-inlines.js'] admin.site.register(Event, EventAdmin)

Read More

Python Django CRUD Example Tutorial

Hey Friends, In this quick example, let's see django tutorial & crud example with mysql and bootstrap. step by step explain django crud operations with mysql backend. step by step explain django crud operations with mysql bootstrap. let’s discuss about django crud operations with mysql database. Read more... [https://tuts-station.com/python-django-crud-example-tutorial.html](https://tuts-station.com/python-django-crud-example-tutorial.html)

  • django
  • python
  • crud
Read More

Generate and render HTML Table

A set of classes that enables fast and flexible generation of HTML tables from columns definitions and datasets. With classes arguments, it is easy to style it with bootstrap for example.

  • Table
  • HTML
  • Python rendering
Read More

3110 snippets posted so far.