Upload multi images
Upload multi images
- Image
- Multi
Upload multi images
FileField delete file on delete or update
Inline
generate unique slug
Instance class model with `class ModelName(models.Model, ContentTypeToGetModel):`
**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.
If you create alot of data via fixtures or by inserting the pk you will more than likely see alot of issues with the sequences being out in postgres when creating new records. Similar to: Foo with the pk(x) already exists This you have to fix by updating the postgres sequences to start at the correct number. The below will ensure after every migrate all sequences in predefined apps get reset.
Returns `Video_ID` extracting from the given url of Youtube.
Sorry, this snippet only tested on Django ver.2.0rc1.
A permission helper that can be included in any generic CBV, it uses the model attribute of the class to load all the permissions and tests a user can perform that action before dispatching the view.
Automatically hyphenate raw text or HTML code
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 }}
add comment "# coding:utf8# to all python file
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/)
The Mixin approach for applying permissions to CBV views suffers from 3 issues: 1. you need to read the code to see what permissions are being applied to a View 2. multiple bits of disparate code required to specify, e.g., a simple permission check 3. permissions set on a base class are overridden by permission set on sub-class, unless special care is taken Here's a nice trick, using only built-in django machinery, apply a decorator intended to decorate a django view function to a CBV view. https://docs.djangoproject.com/en/1.11/topics/class-based-views/intro/#decorating-the-class This approach works for any function decorators with arguments - simply wrap it in a function that takes the same arguments: def my_cbv_decorator(*args **kwargs): return method_decorator(a_view_function_decorator(*args, **kwargs), name='dispatch') Use your new CBV decorator to decorate View sub-classes: @my_cbv_decorator('some_parameter') class MyCBView(django.views.generic.TemplateView): pass # dispatch method for this view is now wrapped by a_view_function_decorator Note: you can also pass decorator parameter directly to method_decorator, but wrapping it up like this makes the code read nicer.
2955 snippets posted so far.