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 / views.py View on Github external
'uptime',
            'topmost_filenames',
            'reason',
            'app_notes',
            'release_channel',
        ),
        '_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')
    writer.writerow([
        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 / models.py View on Github external
def get_super_entities(self):
        """
        Gets the super entities this entity belongs to.
        """
        return [self.team] if self.team 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 / models.py 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 / test_app.py View on Github external
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import pytest

from django.conf import settings
try:
    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")

@skip_new_haystack
def test_env_setting_old_haystack():
    assert settings.OLD_HAYSTACK is True


@skip_old_haystack
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 / models.py 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):

    SEX_CHOICES = {
        ('M', "Male"),
        ('F', "Female")
    }

    name = models.CharField(max_length=50)
    age = models.IntegerField(null=True, blank=True)
    sex = models.CharField(
        max_length=1,
        choices=SEX_CHOICES,
        null=True,
        blank=True
    )
    about = models.TextField(null=True, blank=True)
github django-danceschool / django-danceschool / danceschool / discounts / tests.py 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(
            discountType=DiscountCombo.DiscountType.addOn,
            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'))
        self.assertEqual(response.context_data.get('is_free'),False)
        self.assertEqual(response.context_data.get('total_discount_amount'),0)
        self.assertTrue(response.context_data.get('addonItems'))
        self.assertFalse(response.context_data.get('discount_codes'))
github getsentry / sentry / tests / sentry / api / endpoints / test_sentry_internal_app_tokens.py View on Github external
def setUp(self):
        self.user = self.create_user(email="boop@example.com")
        self.org = self.create_organization(owner=self.user, name="My Org")
        self.project = self.create_project(organization=self.org)

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

        self.url = reverse(
            "sentry-api-0-sentry-internal-app-tokens", args=[self.internal_sentry_app.slug]
        )
github django-haystack / django-haystack / test_haystack / test_views.py 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 / tests.py View on Github external
'software_version': self.software_version.id}
        response = self.client.post(reverse("emg_setting_edit", args=(emg_setting.id,)), self.data)
        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'
        self.data = {'action': 'save', 'name': name, 'description': description,
                     'software_version': self.software_version.id}
        response = self.client.post(reverse("emg_setting_edit", args=(emg_setting.id,)), self.data)
        self.assertEqual(response.status_code, 302)
        self.assertTrue(EMGSetting.objects.filter(name=name, description=description).exists())

        # remove an emg setting
        self.data = {'action': 'remove'}
        response = self.client.post(reverse("emg_setting_view", args=(emg_setting.id,)), self.data)
        self.assertEqual(response.status_code, 302)
github Nitrate / Nitrate / tcms / testplans / forms.py 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(
                self.error_messages['invalid_file_type'])

        if data.content_type in self.ODT_CONTENT_TYPES:
            try:
                return UploadedODTFile(data).get_content()
            except Exception:
                raise forms.ValidationError(
                    self.error_messages['unexcept_odf_error'])

        if data.content_type == MIMETYPE_HTML:
            try:
                return UploadedHTMLFile(data).get_content()
            except Exception:
                raise forms.ValidationError(
                    self.error_messages['unexpected_html_error'])