How to use Django - 10 common examples

To help you get started, we’ve selected a few Django examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mozilla-services / socorro / webapp-django / crashstats / graphics / View on Github external
        '_results_number': batch_size,
        '_results_offset': 0,
    api = SuperSearch()
    # Do the first query. That'll give us the total and the first page's
    # worth of crashes.
    data = api.get(**params)
    assert 'hits' in data

    response = http.HttpResponse(content_type='text/csv')

    out = six.StringIO()
    writer = csv.writer(out, dialect=csv.excel, delimiter='\t')
        smart_text(part) for part in GRAPHICS_REPORT_HEADER

    pages = data['total'] // batch_size
    # if there is a remainder, add one more page
    if data['total'] % batch_size:
        pages += 1
    alias = {
        'crash_id': 'uuid',
        'os_name': 'platform',
        'os_version': 'platform_version',
        'date_processed': 'date',
github ambitioninc / django-entity / test_project / View on Github external
def get_super_entities(self):
        Gets the super entities this entity belongs to.
        return [] if is not None else []

    def is_super_entity_relationship_active(self, super_entity):
        Make it an inactive relationship when the account is a captain
        of a team.
        return not self.is_captain

class EntityPointer(models.Model):
    Describes a test model that points to an entity. Used for ensuring
    that syncing entities doesn't perform any Entity deletes (causing models like
    this to be cascade deleted)
    entity = models.ForeignKey(Entity)

class DummyModel(models.Model):
    Used to ensure that models that don't inherit from EntityModelMixin aren't syned.
    dummy_data = models.CharField(max_length=64)

    objects = EntityModelManager()
github bulkan / django-sqlpaginator / tests / View on Github external
# This is an auto-generated Django model module.

from django.db import models

class Album(models.Model):
    albumid = models.IntegerField(primary_key=True, db_column=u'AlbumId')
    title = models.TextField(db_column=u'Title') # Field name made lowercase. This field type is a guess.
    artistid = models.IntegerField(db_column=u'ArtistId')
    class Meta:
        db_table = u'Album'

    def __unicode__(self):
        return "" % (self.title, self.artistid)

class Artist(models.Model):
    artistid = models.IntegerField(primary_key=True, db_column=u'ArtistId')
    name = models.TextField(db_column=u'Name', blank=True) # Field name made lowercase. This field type is a guess.
    class Meta:
        db_table = u'Artist'

class Customer(models.Model):
github kezabelle / django-haystackbrowser / haystackbrowser / View on Github external
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import pytest

from django.conf import settings
    from django.core.urlresolvers import reverse, resolve
except ImportError:  # >= Django 2.0
    from django.urls import reverse, resolve
from .admin import Search404

skip_old_haystack = pytest.mark.skipif(settings.OLD_HAYSTACK is True,
                                  reason="Doesn't apply to Haystack 1.2.x")

skip_new_haystack = pytest.mark.skipif(settings.OLD_HAYSTACK is False,
                                       reason="Doesn't apply to Haystack 2.x")

def test_env_setting_old_haystack():
    assert settings.OLD_HAYSTACK is True

def test_env_setting_new_haystack():
    assert settings.OLD_HAYSTACK is False

def test_app_is_mounted_accessing_changelist_but_no_models_loaded(admin_user, rf):
github Kemaweyan / django-content-gallery / content_gallery_testapp / testapp / View on Github external
from django.db import models

from content_gallery.models import ContentGalleryMixin

# the ContentGalleryMixin enables the Content Gallery for the model

class Cat(ContentGalleryMixin, models.Model):

        ('M', "Male"),
        ('F', "Female")

    name = models.CharField(max_length=50)
    age = models.IntegerField(null=True, blank=True)
    sex = models.CharField(
    about = models.TextField(null=True, blank=True)
github django-danceschool / django-danceschool / danceschool / discounts / View on Github external
def test_addOnItem(self):
        Create a free add-on item and ensure that it is applied correctly.

        updateConstant('general__discountsEnabled', True)
        test_combo, test_component = self.create_discount(
            name='Test Free Add-On',
        s = self.create_series(pricingTier=self.defaultPricing)

        response = self.register_to_check_discount(s)

        self.assertEqual(response.redirect_chain,[(reverse('showRegSummary'), 302)])
        self.assertEqual(response.context_data.get('totalPrice'), s.getBasePrice())
        self.assertEqual(response.context_data.get('netPrice'), response.context_data.get('totalPrice'))
github getsentry / sentry / tests / sentry / api / endpoints / View on Github external
def setUp(self):
        self.user = self.create_user(email="") = self.create_organization(owner=self.user, name="My Org")
        self.project = self.create_project(

        self.internal_sentry_app = self.create_internal_integration(
            name="My Internal App",

        self.url = reverse(
            "sentry-api-0-sentry-internal-app-tokens", args=[self.internal_sentry_app.slug]
github django-haystack / django-haystack / test_haystack / View on Github external
def test_search_query(self):
        response = self.client.get(reverse('haystack_basic_search'), {'q': 'haystack'})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(type(response.context[-1]['form']), ModelSearchForm)
        self.assertEqual(len(response.context[-1]['page'].object_list), 3)
        self.assertEqual(response.context[-1]['page'].object_list[0].content_type(), u'core.mockmodel')
        self.assertEqual(response.context[-1]['page'].object_list[0].pk, '1')
        self.assertEqual(response.context[-1]['query'], u'haystack')
github neuromat / nes / patientregistrationsystem / qdc / experiment / View on Github external
        response ="emg_setting_edit", args=(,)),
        self.assertEqual(response.status_code, 302)
        self.assertTrue(EMGSetting.objects.filter(name=name, description=description).exists())

        name = 'EMG setting name updated'
        description = 'EMG setting description updated' = {'action': 'save', 'name': name, 'description': description,
        response ="emg_setting_edit", args=(,)),
        self.assertEqual(response.status_code, 302)
        self.assertTrue(EMGSetting.objects.filter(name=name, description=description).exists())

        # remove an emg setting = {'action': 'remove'}
        response ="emg_setting_view", args=(,)),
        self.assertEqual(response.status_code, 302)
github Nitrate / Nitrate / tcms / testplans / View on Github external
def clean(self, data, initial=None):
        f = super(PlanFileField, self).clean(data, initial)
        if f is None:
            return None
        elif not data and initial:
            return initial

        if data.content_type not in self.VALID_CONTENT_TYPES:
            raise forms.ValidationError(

        if data.content_type in self.ODT_CONTENT_TYPES:
                return UploadedODTFile(data).get_content()
            except Exception:
                raise forms.ValidationError(

        if data.content_type == MIMETYPE_HTML:
                return UploadedHTMLFile(data).get_content()
            except Exception:
                raise forms.ValidationError(