Login

3110 snippets

Snippet List

Readonly Select Widget Replacement

This is for situations where a ModelForm is needed on an existing object, but we want to disable ForeignKey widgets, and only use them as a display. Usage: save the code in the top half of the example above into a file somewhere in your django project, in this example we will call it customwidget.py The second half shows an example usage, but setting the widget and queryset in the __init__ method of the form. If the queryset returned by the ForeignKey model (Example.objects.all() ) is small, you can omit the __init__ code.

Read More

Basic Auth Middleware

A very basic Basic Auth middleware that uses a username/password defined in your settings.py as `BASICAUTH_USERNAME` and `BASICAUTH_PASSWORD`. Does not use Django auth. Handy for quickly securing an entire site during development, for example. In settings.py: BASICAUTH_USERNAME = 'user' BASICAUTH_PASSWORD = 'pass' MIDDLEWARE_CLASSES = ( 'app.module.BasicAuthMiddleware', #all other middleware )

  • middleware
  • basic
  • authentication
  • http-authorization
Read More

Load template from specific app

This is an updated of version snippets: * [https://djangosnippets.org/snippets/10489/](https://djangosnippets.org/snippets/10489/) * [https://djangosnippets.org/snippets/1376/](https://djangosnippets.org/snippets/10489/) Tested to with with Django 3.2 With this template loader you can extend templates from built-in Django apps such as Django admin. Example: {% extends "admin:admin/index.html" %} {% block sidebar %} {{block.super}} <div> < h1>Statistics< /h1> < a href="/admin/station/stats/">Published Stations< /a> </div> {% endblock %} Configuration: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ 'your_app/templates' ], 'OPTIONS': { # (...) # See: https://docs.djangoproject.com/en/3.2/ref/templates/api/#django.template.loaders.cached.Loader 'loaders': [ ('django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'your_app.template_loaders.SpecificAppTemplateLoader', ]), ], }, }, ]

  • template-loader
Read More

RangeField and RangeWidget

These field and widget are util for to those fields where you can put a star and end values. It supports most of field types and widgets (tested with IntegerField, CharField and DateField / TextInput and a customized DateInput). **Example of use:** class FormSearch(forms.Form): q = forms.CharField(max_length=50, label=_('Search for')) price_range = RangeField(forms.IntegerField, required=False) **Example of use (with forced widget):** class FormSearch(forms.Form): q = forms.CharField(max_length=50, label=_('Search for')) price_range = RangeField(forms.IntegerField, widget=MyWidget)

  • forms
  • field
  • widget
  • range
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

CBV to mix FormView and DetailView functionalities

Use this to display an object on a page AND be able to process a form on this page. This is just a copy of the [Django docs advice](https://docs.djangoproject.com/en/2.2/topics/class-based-views/mixins/#using-formmixin-with-detailview), but put as a reusable, standalone View.

  • view
  • form
  • cbv
  • detail
Read More

AdminPeepingMiddleware

Peeping middleware, that replaces active user to another one for current http request. Admin permissions required to activate, so you can place this snippet even on the production server. Very useful for debugging purposes. Wish it to be part of Django. How to use: Put this middleware after all other middlewares in the list. Then just add ?as_user=username or &as_user=username to the url, where username is the name of user whose views you want to see.

  • middleware
  • admin
  • view
  • permissions
  • peep
Read More

Send large files through Django, and how to generate Zip files

This snippet demonstrates how you can send a file (or file-like object) through Django without having to load the whole thing into memory. The FileWrapper will turn the file-like object into an iterator for chunks of 8KB. This is a full working example. Start a new app, save this snippet as views.py, and add the views to your URLconf. The send_file view will serve the source code of this file as a plaintext document, and the send_zipfile view will generate a Zip file with 10 copies of it. Use this solution for dynamic content only, or if you need password protection with Django's user accounts. Remember that you should serve static files directly through your web server, not through Django: http://www.djangoproject.com/documentation/modpython/#serving-media-files

  • sendfile
  • zipfile
  • tempfile
  • temporaryfile
  • filewrapper
Read More

JsonResponse

A subclass of `HttpResponse` useful as a shortcut in views; it chooses the correct JSON serializer based on whether or not it is passed a QuerySet.

  • ajax
  • serialize
  • json
Read More
Author: zakj
  • 24
  • 85

Amazon S3 browser-based upload form

A Django Form for creating a browser-based upload form that pushes files to Amazon S3. See http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1434

  • forms
  • upload
  • s3
  • amazon
Read More