spaceless_json
Now you can format and compress json-data in django template
- django
- templatetag
- json
- spaceless
- formatting
- application/id+json
Now you can format and compress json-data in django template
Takes a tweet url, requests the json from Twitter oEmbed, parses the json for the html element and returns it to your template. The html returned is ready to go and will be shown as a tweet on your web page. This uses the Requests library for Python. A full example can be found on GitHub https://github.com/z3ke1r/django-tweet-embed.
Mixin for Django Rest Framework View/Viewsets to use different response data/serializers without unnecessary hacks. Just extend your DRFs view/viewset with this mixin after the DRF's APIView (sub)classes.
create custom permissions
- This is a filter to shorten the natural time value obtained using naturaltime function from humanize.
Using Django REST Framework for Model views there is always the issue of making duplicated queries without either prefetching the objects that will be accessed using the serializer and as such will lead to large number of queries being made to the database. This will help in optimizing the queryset used for the viewset by accessing the `_meta.fields` property of the serializer.
Create dynamic urlpatterns for classed based views
Generate unique slug refference by another field.
Instance class model with `class ModelName(models.Model, ContentTypeToGetModel):`
Returns `Video_ID` extracting from the given url of Youtube.
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 }}
With this awesome manage.py, it will try to migrate first when called with runserver. Also, this manege.py has super power to be used in your entry point as such: entry_points = { 'console_scripts': [ # u haz a setup.py -> u haz importable module :) 'yourcommand = yourproject.manage:main', ], }, Example output: $ yourcommand runserver Operations to perform: Apply all migrations: auth, contenttypes, admin, sessions Running migrations: Rendering model states... DONE Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying sessions.0001_initial... OK Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. Performing system checks... Username (leave blank to use 'jpic'): Email address: [email protected] Password: Password (again): Superuser created successfully. Welcome in 2017, where automation is king System check identified no issues (0 silenced). September 17, 2017 - 21:21:41 Django version 1.9.10, using settings 'crudlfap_example.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Extra note: it doesn't matter if migrate crashes for now, since django runserver doesn't support not being able to connect to database. So most of the time I hope to shouldn't need to disable this hack.
django online users, usage: `{{ request.online_now }}` or `{{ request.online_now_ids }}`, complete tutorial: https://python.web.id/blog/django-count-online-users/, this snippet forked from: https://gist.github.com/dfalk/1472104
Easy way to get base64 for the image to display in the template, eg: `<img src="{{ post.get_cover_base64 }}">`
[DRF browsable API interface](http://www.django-rest-framework.org/api-guide/filtering/#customizing-the-interface) for django-rest-framework-gis [InBBoxFilter](https://github.com/djangonauts/django-rest-framework-gis#inbboxfilter) Tested with Django==1.10.5 django-filter==1.0.1 djangorestframework==3.5.4 djangorestframework-gis==0.11 
213 snippets posted so far.