Login

Most bookmarked snippets

Snippet List

TemplateTag to call a method / function WITH arguments

**Callmethod** - TemplateTag to call a method on an object with arguments from within a template {% callmethod hotel.room_price_for_night night_date="2018-01-02" room_type=room_type_context_var %} ## equals ## >>> hotel.room_price_for_night(night_date="2018-01-02", room_type="standard") #Assuming "standard" is the value of room_type_context_var Django doesn't allow calling a method with arguments in the template to ensure good separation of design and code logic. However, sometimes you will be in situations where it is more maintainable to pass an argument to a method in the template than build an iterable (with the values already resolved) in a view. Furthermore, Django doesn't strictly follow its own ideology: the {% url "url:scheme" arg, kwarg=var %} templatetag readily accepts variables as parameters!! This template tag allows you to call a method on an object, with the specified arguments. Usage: {% callmethod object_var.method_name "arg1_is_a_string" arg2_is_a_var kwarg1="a string" kwarg2=another_contect_variable %} e.g. {% callmethod hotel.room_price_for_night date="2018-01-02" room_type="standard" %} {% callmethod hotel.get_booking_tsandcs "standard" %} NB: If for whatever reason you've ended up with a template context variable with the same name as the method you want to call on your object, you will need to force the template tag to regard that method as a string by putting it in quotes: {# Ensure we call hotel.room_price_for_night() even though there's a template var called {{ room_price_for_night }}! #} {% callmethod hotel."room_price_for_night" date="2018-01-02" room_type="standard" %} * **@author:** Dr Michael J T Brooks * **@version:** 2018-01-05 * **@copyright:** Onley Group 2018 (Onley Technical Consulting Ltd) [http://www.onleygroup.com](http://www.onleygroup.com) * **@license:** MIT (use as you wish, AS IS, no warranty on performance, no liability for losses, please retain the notice) * **@write_code_GET_PAID:** Want to work from home as a Django developer? Earn £30-£50 per hour ($40-$70) depending on experience for helping Onley Group develop its clients' Django-based web apps. E-mail your CV and some sample portfolio code to: [email protected] Copyright 2018 Onley Group Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice, credits, and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

  • template
  • tag
  • templatetag
  • function
  • template-tag
  • args
  • kwargs
  • methods
  • argument
  • template-arguments
Read More

inline forms for deeply nested models

I had a problem trying to display my model would have a foreign key and that model would have one too etc. Now there was a point I wanted to display the foreign keys of that field and display its fields and so on so forth. This pretty much expands the models by getting the base form that worked best for me. It is intended to only work alongside `Forms`. I haven't been able to get it to work with `ModelForm`. Example usage: forms.py class AddressForm(forms.Form): address_0 = forms.CharField(label="address", max_length=64) address_1 = forms.CharField( label="address cont'd", max_length=64, required=False) city = forms.CharField(max_length=64) state = USStateField(widget=USStateSelect) # django_localflavor_us.forms zip_code = USZipCodeField(label='zipcode') # django_localflavor_us.forms class ContactInfoForm(ForeignKeyFormMixin, forms.Form): name = forms.CharField(max_length=50) # address = model.ForeignKey(Address) # is a foreignkey in my model for Address phone = PhoneNumberField() # phonenumber_field.formfields (irrelevant could very well be forms.CharField) fax = PhoneNumberField(required=False) # phonenumber_field.formfields (irrelevant could very well be forms.CharField) email = forms.EmailField() foreign_keys = {'address': AddressForm} # foreign forms I want to introduce, key acts as a related_name def __init__(self, *args, **kwargs): super(ContactInfoForm, self).__init__(*args, **kwargs) class GenerationForm(ForeignKeyFormMixin, forms.Form): company = forms.CharField(max_length=50) code = forms.CharField(max_length=50, required=False) # contact = model.ForeignKey(ContactInfo) # is a foreignkey in my model for Contact # facility_address = model.ForeignKey(AddressForm, related_name='facility') # is a foreignkey in my model for Address # mailing_address = model.ForeignKey(AddressForm, related_name='mailing') # is a foreignkey in my model for Address foreign_keys = {'contact': ContactInfoForm, 'facility_address': AddressForm, 'mailing_address': AddressForm} view.py def generation_create_view(self): if self.request.method == 'POST': generator_form = GenerationForm(self.request.POST) if generator_form.is_valid(): cleaned_data = generator_form.cleaned_data (contact_address, created) = Address.objects.get_or_create( address_0=cleaned_data['contact_address_address_0'], # notice naming. trying to keep it orgnized as possible and reuse the "foreign key" you want to expand address_1=cleaned_data['contact_address_address_1'], city=cleaned_data['contact_address_city'].title(), state=cleaned_data['contact_address_state'][:2].upper(), zip_code=cleaned_data['contact_address_zip_code'], ) print contact_address (contact_info, created) = ContactInfo.objects.get_or_create( name=cleaned_data['contact_name'], address=contact_address, phone=cleaned_data['contact_fax'], email=cleaned_data['contact_email'], ) print contact_info # ... # (assuming you have created other models as above) (generator, created) = Generator.objects.get_or_create( contact=contact_info, company=cleaned_data['company'], facility_address=facility_address, mailing_address=mailing_address, code=cleaned_data['code'], ) return redirect('to some where') else: generator_form = GenerationForm() return render(request, 'generation_create.html', {'generator_form': generator_form, }) generator_form.html # assuming your standard form tags are setup `<form class="form"...>...`. you would access form and display as follows # I am using https://django-bootstrap.readthedocs.io/en/latest/index.html # to help display forms in bootstrap <p class="lead">Contact</p> {% bootstrap_form generator_form.contact %} # can also just do {{ generator_form.contact }} {% bootstrap_field generator_form.company %} # can also just do {{ generator_form.company }} <p class="lead">Facility:</p> {% bootstrap_form generator_form.facility_address %} # can also just do {{ generator_form.facility_address }} <p class="lead">Mailing:</p> {% bootstrap_form generator_form.mailing_address %} # can also just do {{ generator_form.mailing_address }} {% bootstrap_field generator_form.code %} # can also just do {{ generator_form.code }}

  • django
  • django-forms
Read More

Do Not Escape Characters When Using dumpdata Command (Tested in Django 1.11)

Adds `--pretty` option to django `./manage.py dumpdata` command, which produces pretty utf-8 strings instead of ugly unicode-escaped s**t: > $ ./manage.py dumpdata app.pricingplan --indent=1 <pre> <code>[ { "pk": 1, "model": "app.pricingplan", "fields": { "name": "\u0411\u0430\u0437\u043e\u0432\u044b\u0439", } }, { "pk": 2, "model": "app.pricingplan", "fields": { "name": "\u0425\u0443\u044f\u0437\u043e\u0432\u044b\u0439", } } ] </code> </pre> > ./manage.py dumpdata app.pricingplan --indent=1 --pretty <pre> <code>[ { "pk": 1, "model": "app.pricingplan", "fields": { "name": "Базовый", } }, { "pk": 2, "model": "app.pricingplan", "fields": { "name": "Хуязовый", } } ] </code> </pre> Forked from an [old versions snippet](https://djangosnippets.org/snippets/2258/)

  • pretty
  • dumpdata
  • pretty-print
Read More

Friendly ID(Python 3.X)

This is just modified version of [friendly id](https://djangosnippets.org/snippets/1249/) for make this script compatible with python 3.x Invoice numbers like "0000004" are a little unprofessional in that they expose how many sales a system has made, and can be used to monitor the rate of sales over a given time. They are also harder for customers to read back to you, especially if they are 10 digits long. This is simply a perfect hash function to convert an integer (from eg an ID AutoField) to a unique number. The ID is then made shorter and more user-friendly by converting to a string of letters and numbers that wont be confused for one another (in speech or text). To use it: import friendly_id class MyModel(models.Model): invoice_id = models.CharField(max_length=6, null=True, blank=True, unique=True) def save(self, *args, **kwargs): super(MyModel, self).save(*args, **kwargs) # Populate the invoice_id if it is missing if self.id and not self.invoice_id: self.invoice_id = friendly_id.encode(self.id) self.save() if self.id and not self.invoice_id When an object from this model is saved, an invoice ID will be generated that does not resemble those surrounding it. For example, where you are expecting millions of invoices the IDs generated from the AutoField primary key will be: obj.id obj.invoice_id 1 TTH9R 2 45FLU 3 6ACXD 4 8G98W 5 AQ6HF 6 DV3TY ... 9999999 J8UE5 The functions are deterministic, so running it again sometime will give the same result, and generated strings are unique for the given range (the default max is 10,000,000). Specifying a higher range allows you to have more IDs, but all the strings will then be longer. You have to decide which you need: short strings or many strings :-) This problem could have also been solved using a random invoice_id generator, but that might cause collisions which cost time to rectify, especially when a decent proportion of the available values are taken (eg 10%). Anyhow, someone else has now already written this little module for you, so now you don't have to write your own :-)

  • database
  • field-id
  • invoice-id
  • invoice
Read More

Decorator to add placeholders to field

Decorator to automagically add placeholders to form widgets. `cls` can be any class derived from `django.forms.Form` or `django.forms.ModelForm`. The field labels are used as value for the placeholder. This will affect all form instances of this class. * add_placeholders only to forms.TextInput and form.Textarea * add_placeholders_to_any_field adds placeholders to any field Usage: @add_placeholders class Form(forms.Form): name = forms.CharField The name field will render as `<input type="text" placeholder="name">`

  • decorator
  • placeholder
Read More

query builder

""" Takes arguments & constructs Qs for filter() We make sure we don't construct empty filters that would return too many results We return an empty dict if we have no filters so we can still return an empty response from the view """

  • query
  • queryset
Read More

aggregate filter

Makes it possible to add a filtering condition directly after the aggregate function (or possible, `aggregate(expression) WITHIN GROUP (ordering clause)`. This is mostly useful if the annotation has two or more expressions, so it's possible to compare the result with and without the applied filter; it's more compact than using `Case`. It's suggested to add `values` to the queryset to get a proper group by. Usage example: `books = Book.objects.values('publisher__name').annotate( count=Count('*'), filtercount=Filter(expression=Count('publisher__name'), condition=Q(rating__gte=5)) ) ` Supported on Postgresql 9.4+. Possible other third-party backends.

  • filter
  • postgresql
  • olap
  • aggregate
  • expression
Read More

Django chunked queryset iterator

The function slices a queryset into smaller querysets containing chunk_size objects and then yield them. It is used to avoid memory error when processing huge queryset, and also database error due to that the database pulls whole table at once. Concurrent database modification wouldn't make some entries repeated or skipped in this process.

  • django
  • python
  • database
  • queryset
  • iterator
  • memoryerror
Read More

Cachable Django Paginator

This is a modificated version of `CachedPaginator` by **daniellindsley** [https://djangosnippets.org/snippets/1173/](https://djangosnippets.org/snippets/1173/) ([web-arhive-link](https://web.archive.org/web/20150927100427/https://djangosnippets.org/snippets/1173/)). Which not only cache `result_objects`, but the `total_count` of the `queryset` too (usefull if computating the count is an expensive operation too).

  • django
  • cache
  • pagination
Read More

Dead Code Finder

Rough check for unused methods in our apps. Scans models, views, utils, api, forms and signals files for what look like methods calls, then looks at all of our classes' methods to ensure each is called. Do not trust this blindly but it's a good way to get leads on what may be dead code. Assumes a setting called `LOCAL_APPS` so it only bothers to look at the code you've written rather than everything in `INSTALLED_APPS`.

  • refactor
  • cleanup
Read More

3110 snippets posted so far.