From b04967e10214d9d02a24bc549a088742d09c364c Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Tue, 19 Jun 2018 16:29:30 +0200 Subject: [PATCH 01/10] use six.python_2_unicode_compatible --- devicegroups/models.py | 5 ++++- devices/models.py | 23 ++++++++++++++++------- devicetags/models.py | 5 ++++- devicetypes/models.py | 11 ++++++++--- locations/models.py | 5 ++++- mail/models.py | 7 +++++-- network/models.py | 5 +++-- users/models.py | 7 +++++-- 8 files changed, 49 insertions(+), 19 deletions(-) diff --git a/devicegroups/models.py b/devicegroups/models.py index 0a8d9a78..21668333 100644 --- a/devicegroups/models.py +++ b/devicegroups/models.py @@ -1,16 +1,19 @@ from django.db import models from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse + +import six from reversion import revisions as reversion from users.models import Department +@six.python_2_unicode_compatible class Devicegroup(models.Model): name = models.CharField(max_length=200) department = models.ForeignKey(Department, null=True) - def __unicode__(self): + def __str__(self): return self.name class Meta: diff --git a/devices/models.py b/devices/models.py index f4814fc4..729a09a6 100644 --- a/devices/models.py +++ b/devices/models.py @@ -4,7 +4,9 @@ from django.db.models import Q from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse + import reversion +import six from users.models import Lageruser from devicetypes.models import Type, TypeAttributeValue @@ -15,6 +17,7 @@ @reversion.register() +@six.python_2_unicode_compatible class Building(models.Model): name = models.CharField(_('Name'), max_length=200, unique=True) street = models.CharField(_('Street'), max_length=100, blank=True) @@ -24,7 +27,7 @@ class Building(models.Model): state = models.CharField(_('State'), max_length=100, blank=True) country = models.CharField(_('Country'), max_length=100, blank=True) - def __unicode__(self): + def __str__(self): return self.name class Meta: @@ -42,12 +45,13 @@ def get_edit_url(self): @reversion.register() +@six.python_2_unicode_compatible class Room(models.Model): name = models.CharField(_('Name'), max_length=200) building = models.ForeignKey(Building, null=True, on_delete=models.SET_NULL) section = models.ForeignKey(Section, null=True, on_delete=models.SET_NULL, related_name="rooms", blank=True) - def __unicode__(self): + def __str__(self): if self.building: return self.name + " (" + self.building.__unicode__() + ")" else: @@ -68,10 +72,11 @@ def get_edit_url(self): @reversion.register() +@six.python_2_unicode_compatible class Manufacturer(models.Model): name = models.CharField(_('Manufacturer'), max_length=200, unique=True) - def __unicode__(self): + def __str__(self): return self.name class Meta: @@ -93,6 +98,7 @@ class Bookmark(models.Model): user = models.ForeignKey(Lageruser) +@six.python_2_unicode_compatible class Device(models.Model): created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) creator = models.ForeignKey(Lageruser, on_delete=models.SET_NULL, null=True) @@ -125,7 +131,7 @@ class Device(models.Model): is_private = models.BooleanField(default=False) used_in = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL,) - def __unicode__(self): + def __str__(self): return self.name class Meta: @@ -172,11 +178,12 @@ def devices_for_departments(departments=[]): ~Q(department__in=departments), is_private=True) +@six.python_2_unicode_compatible class DeviceInformationType(models.Model): keyname = models.CharField(_('Name'), max_length=200) humanname = models.CharField(_('Human readable name'), max_length=200) - def __unicode__(self): + def __str__(self): return self.humanname class Meta: @@ -184,12 +191,13 @@ class Meta: verbose_name_plural = _('Information Type') +@six.python_2_unicode_compatible class DeviceInformation(models.Model): information = models.CharField(_('Information'), max_length=200) device = models.ForeignKey(Device, related_name="information") infotype = models.ForeignKey(DeviceInformationType) - def __unicode__(self): + def __str__(self): return self.infotype.__unicode__() + ": " + self.information class Meta: @@ -212,6 +220,7 @@ class Lending(models.Model): smalldevice = models.CharField(_("Small Device"), max_length=200, null=True, blank=True) +@six.python_2_unicode_compatible class Template(models.Model): templatename = models.CharField(_('Templatename'), max_length=200) name = models.CharField(_('Name'), max_length=200) @@ -219,7 +228,7 @@ class Template(models.Model): description = models.CharField(_('Description'), max_length=1000, blank=True) devicetype = models.ForeignKey(Type, blank=True, null=True) - def __unicode__(self): + def __str__(self): return self.templatename class Meta: diff --git a/devicetags/models.py b/devicetags/models.py index 89545d8e..3276e5c6 100644 --- a/devicetags/models.py +++ b/devicetags/models.py @@ -2,15 +2,18 @@ from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse +import six + from devices.models import Device # Create your models here. +@six.python_2_unicode_compatible class Devicetag(models.Model): name = models.CharField(max_length=200, unique=True) devices = models.ManyToManyField(Device, related_name="tags") - def __unicode__(self): + def __str__(self): return self.name class Meta: diff --git a/devicetypes/models.py b/devicetypes/models.py index ac1b6729..d6e4e709 100644 --- a/devicetypes/models.py +++ b/devicetypes/models.py @@ -1,13 +1,16 @@ from django.db import models from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse + +import six from reversion import revisions as reversion +@six.python_2_unicode_compatible class Type(models.Model): name = models.CharField(_('Name'), max_length=200, unique=True) - def __unicode__(self): + def __str__(self): return self.name class Meta: @@ -24,6 +27,7 @@ def get_edit_url(self): return reverse('type-edit', kwargs={'pk': self.pk}) +@six.python_2_unicode_compatible class TypeAttribute(models.Model): devicetype = models.ForeignKey(Type) name = models.CharField(max_length=200) @@ -36,10 +40,11 @@ class Meta: def get_absolute_url(self): return reverse('type-detail', kwargs={'pk': self.devicetype.pk}) - def __unicode__(self): + def __str__(self): return self.name +@six.python_2_unicode_compatible class TypeAttributeValue(models.Model): typeattribute = models.ForeignKey(TypeAttribute) value = models.CharField(max_length=400) @@ -49,7 +54,7 @@ class Meta: verbose_name = _("Type-attribute value") verbose_name_plural = _("Type-attribute values") - def __unicode__(self): + def __str__(self): return self.value diff --git a/locations/models.py b/locations/models.py index e4dadc2d..f018210d 100644 --- a/locations/models.py +++ b/locations/models.py @@ -2,11 +2,14 @@ from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse +import six + +@six.python_2_unicode_compatible class Section(models.Model): name = models.CharField(max_length=200) - def __unicode__(self): + def __str__(self): return self.name class Meta: diff --git a/mail/models.py b/mail/models.py index 81a31ca2..b7d22acb 100644 --- a/mail/models.py +++ b/mail/models.py @@ -5,6 +5,7 @@ from django.core.mail import EmailMessage from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey + import pystache import six @@ -20,6 +21,7 @@ } +@six.python_2_unicode_compatible class MailTemplate(models.Model): name = models.CharField(_('Name'), max_length=200, unique=True) subject = models.CharField(_('Subject'), max_length=500) @@ -27,7 +29,7 @@ class MailTemplate(models.Model): department = models.ForeignKey(Department, null=True) usage = models.CharField(_('Usage'), choices=list(usages.items()), null=True, blank=True, max_length=200) - def __unicode__(self): + def __str__(self): return self.name class Meta: @@ -98,13 +100,14 @@ def send(self, request, recipients=None, data=None): mailhistory.save() +@six.python_2_unicode_compatible class MailTemplateRecipient(models.Model): mailtemplate = models.ForeignKey(MailTemplate, related_name='default_recipients') content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') - def __unicode__(self): + def __str__(self): return six.text_type(self.content_type.name + ": " + self.content_object.__unicode__()) diff --git a/network/models.py b/network/models.py index 5e05dea9..e6336119 100644 --- a/network/models.py +++ b/network/models.py @@ -5,10 +5,11 @@ from devices.models import Device from users.models import Lageruser, Department -# Create your models here. +import six from reversion import revisions as reversion +@six.python_2_unicode_compatible class IpAddress(models.Model): address = models.GenericIPAddressField(unique=True) device = models.ForeignKey(Device, blank=True, null=True, on_delete=models.SET_NULL) @@ -17,7 +18,7 @@ class IpAddress(models.Model): purpose = models.CharField(max_length=200, null=True, blank=True) department = models.ForeignKey(Department, null=True, blank=True) - def __unicode__(self): + def __str__(self): return self.address class Meta: diff --git a/users/models.py b/users/models.py index 492c462d..ef570215 100644 --- a/users/models.py +++ b/users/models.py @@ -17,10 +17,12 @@ from django.conf import settings import re +import six from datetime import date from Lagerregal import utils +@six.python_2_unicode_compatible class Lageruser(AbstractUser): language = models.CharField(max_length=10, null=True, blank=True, choices=settings.LANGUAGES, default=settings.LANGUAGES[0][0]) @@ -38,7 +40,7 @@ class Lageruser(AbstractUser): departments = models.ManyToManyField("users.Department", blank=True, through='users.DepartmentUser', related_name="members") - def __unicode__(self): + def __str__(self): if self.first_name != "" and self.last_name != "": return "{0} {1}".format(self.first_name, self.last_name) else: @@ -104,10 +106,11 @@ def populate_ldap_user(sender, signal, user, ldap_user, **kwargs): user.save() +@six.python_2_unicode_compatible class Department(models.Model): name = models.CharField(max_length=40, unique=True) - def __unicode__(self): + def __str__(self): return self.name class Meta: From 6d1f3bc188a14c0b78b6b29cbd8a8641010e2126 Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Tue, 19 Jun 2018 16:41:09 +0200 Subject: [PATCH 02/10] avoid calling __unicode__ directly --- devicegroups/tests.py | 6 ++++-- devices/ajax.py | 4 ++-- devices/models.py | 4 ++-- devices/tests.py | 18 ++++++++++-------- devicetags/tests.py | 6 ++++-- devicetypes/tests.py | 6 ++++-- history/views.py | 8 +++++--- locations/tests.py | 6 ++++-- mail/models.py | 6 +++--- mail/tests.py | 8 +++++--- network/views.py | 10 ++++++---- users/tests.py | 8 +++++--- 12 files changed, 54 insertions(+), 36 deletions(-) diff --git a/devicegroups/tests.py b/devicegroups/tests.py index a452b80a..b15a9a09 100644 --- a/devicegroups/tests.py +++ b/devicegroups/tests.py @@ -1,8 +1,10 @@ from django.test.client import Client from django.test import TestCase -from model_mommy import mommy from django.core.urlresolvers import reverse +import six +from model_mommy import mommy + from devicegroups.models import Devicegroup from users.models import Lageruser @@ -15,6 +17,6 @@ def setUp(self): def test_devicegroup_creation(self): devicegroup = mommy.make(Devicegroup) - self.assertEqual(devicegroup.__unicode__(), devicegroup.name) + self.assertEqual(six.text_type(devicegroup), devicegroup.name) self.assertEqual(devicegroup.get_absolute_url(), reverse('devicegroup-detail', kwargs={'pk': devicegroup.pk})) self.assertEqual(devicegroup.get_edit_url(), reverse('devicegroup-edit', kwargs={'pk': devicegroup.pk})) diff --git a/devices/ajax.py b/devices/ajax.py index a819ff9b..460fbb6b 100644 --- a/devices/ajax.py +++ b/devices/ajax.py @@ -251,10 +251,10 @@ def post(self, request): return HttpResponse("") if invert: data = [ - {"value": "not " + str(object.pk) + "-" + object.__unicode__(), "label": "not " + object.__unicode__()} + {"value": "not " + str(object.pk) + "-" + six.text_type(object), "label": "not " + six.text_type(object)} for object in items] else: - data = [{"value": str(object.pk) + "-" + object.__unicode__(), "label": object.__unicode__()} + data = [{"value": str(object.pk) + "-" + six.text_type(object), "label": six.text_type(object)} for object in items] return HttpResponse(json.dumps(data), content_type='application/json') diff --git a/devices/models.py b/devices/models.py index 729a09a6..a7608c25 100644 --- a/devices/models.py +++ b/devices/models.py @@ -53,7 +53,7 @@ class Room(models.Model): def __str__(self): if self.building: - return self.name + " (" + self.building.__unicode__() + ")" + return self.name + " (" + six.text_type(self.building) + ")" else: return self.name @@ -198,7 +198,7 @@ class DeviceInformation(models.Model): infotype = models.ForeignKey(DeviceInformationType) def __str__(self): - return self.infotype.__unicode__() + ": " + self.information + return six.text_type(self.infotype) + ": " + self.information class Meta: verbose_name = _('Information') diff --git a/devices/tests.py b/devices/tests.py index 645420d6..8450c36f 100644 --- a/devices/tests.py +++ b/devices/tests.py @@ -5,6 +5,8 @@ from django.test.client import Client from django.test import TestCase from django.core.urlresolvers import reverse + +import six from model_mommy import mommy from devices.models import Device, Building, Room, Manufacturer, Template, Note, Lending, DeviceInformationType, DeviceInformation, Picture @@ -28,7 +30,7 @@ def test_device_creation(self): lending_past = mommy.make(Lending, duedate = (datetime.today() - timedelta(days = 1)).date()) lending_future = mommy.make(Lending, duedate = (datetime.today() + timedelta(days = 1)).date()) self.assertTrue(isinstance(device, Device)) - self.assertEqual(device.__unicode__(), device.name) + self.assertEqual(six.text_type(device), device.name) self.assertEqual(device.get_absolute_url(), reverse('device-detail', kwargs={'pk': device.pk})) self.assertEqual(device.get_edit_url(), reverse('device-edit', kwargs={'pk': device.pk})) self.assertEqual(device.get_as_dict(), {"name": device.name, "description": device.description, "manufacturer": device.manufacturer, "devicetype" : device.devicetype, "room" : device.room}) @@ -244,7 +246,7 @@ def test_building_creation(self): building = mommy.make(Building) building.save() self.assertTrue(isinstance(building, Building)) - self.assertEqual(building.__unicode__(), building.name) + self.assertEqual(six.text_type(building), building.name) self.assertEqual(building.get_absolute_url(), reverse('building-detail', kwargs={'pk': building.pk})) self.assertEqual(building.get_edit_url(), reverse('building-edit', kwargs={'pk': building.pk})) @@ -303,9 +305,9 @@ def test_room_creation(self): building = mommy.make(Building) room_in_building = mommy.make(Room, building = building) self.assertTrue(isinstance(room, Room)) - self.assertEqual(room.__unicode__(), room.name) + self.assertEqual(six.text_type(room), room.name) self.assertTrue(isinstance(room_in_building, Room)) - self.assertEqual(room_in_building.__unicode__(), room_in_building.name + " (" + building.__unicode__() + ")") + self.assertEqual(six.text_type(room_in_building), room_in_building.name + " (" + six.text_type(building) + ")") self.assertEqual(room.get_absolute_url(), reverse('room-detail', kwargs={'pk': room.pk})) self.assertEqual(room.get_edit_url(), reverse('room-edit', kwargs={'pk': room.pk})) @@ -360,7 +362,7 @@ def setUp(self): def test_manufacturer_creation(self): manufacturer = mommy.make(Manufacturer) self.assertTrue(isinstance(manufacturer, Manufacturer)) - self.assertEqual(manufacturer.__unicode__(), manufacturer.name) + self.assertEqual(six.text_type(manufacturer), manufacturer.name) self.assertEqual(manufacturer.get_absolute_url(), reverse('manufacturer-detail', kwargs={'pk': manufacturer.pk})) self.assertEqual(manufacturer.get_edit_url(), reverse('manufacturer-edit', kwargs={'pk': manufacturer.pk})) @@ -416,7 +418,7 @@ def setUp(self): def test_template_creation(self): template = mommy.make(Template) self.assertTrue(isinstance(template, Template)) - self.assertEqual(template.__unicode__(), template.templatename) + self.assertEqual(six.text_type(template), template.templatename) self.assertEqual(template.get_absolute_url(), reverse('device-list')) self.assertEqual(template.get_as_dict(), {'name': template.name, 'description': template.description, 'manufacturer' : template.manufacturer, 'devicetype' : template.devicetype }) @@ -474,7 +476,7 @@ def setUp(self): def test_device_information_type_creation(self): information = mommy.make(DeviceInformationType) self.assertTrue(isinstance(information, DeviceInformationType)) - self.assertEqual(information.__unicode__(), information.humanname) + self.assertEqual(six.text_type(information), information.humanname) class DeviceInformationTests(TestCase): def setUp(self): @@ -484,7 +486,7 @@ def setUp(self): def test_device_information_creation(self): device_information = mommy.make(DeviceInformation) - self.assertEqual(device_information.__unicode__(), device_information.infotype.__unicode__() + ": " + device_information.information) + self.assertEqual(six.text_type(device_information), six.text_type(device_information.infotype) + ": " + device_information.information) class PictureTests(TestCase): diff --git a/devicetags/tests.py b/devicetags/tests.py index 2ae78767..6e28243f 100644 --- a/devicetags/tests.py +++ b/devicetags/tests.py @@ -1,8 +1,10 @@ from django.test.client import Client from django.test import TestCase -from model_mommy import mommy from django.core.urlresolvers import reverse +import six +from model_mommy import mommy + from devicetags.models import Devicetag from users.models import Lageruser @@ -15,7 +17,7 @@ def setUp(self): def test_devicetag_creation(self): tag = mommy.make(Devicetag) - self.assertEqual(tag.__unicode__(), tag.name) + self.assertEqual(six.text_type(tag), tag.name) # there is no devicetag detail view self.assertEqual(tag.get_absolute_url(), reverse('devicetag-edit', kwargs={'pk': tag.pk})) self.assertEqual(tag.get_edit_url(), reverse('devicetag-edit', kwargs={'pk': tag.pk})) diff --git a/devicetypes/tests.py b/devicetypes/tests.py index 0c452979..c1f9197d 100644 --- a/devicetypes/tests.py +++ b/devicetypes/tests.py @@ -1,8 +1,10 @@ from django.test.client import Client from django.test import TestCase -from model_mommy import mommy from django.core.urlresolvers import reverse +import six +from model_mommy import mommy + from devicetypes.models import Type, TypeAttribute, TypeAttributeValue from devicetypes.models import Type from users.models import Lageruser @@ -23,7 +25,7 @@ def test_type_creation(self): self.assertTrue(isinstance(devicetype, Type)) # testing naming - self.assertEqual(devicetype.__unicode__(), devicetype.name) + self.assertEqual(six.text_type(devicetype), devicetype.name) # testing creation of absolute and relative url self.assertEqual(devicetype.get_absolute_url(), reverse('type-detail', kwargs={'pk': devicetype.pk})) diff --git a/history/views.py b/history/views.py index 5f5bc150..adfe261c 100644 --- a/history/views.py +++ b/history/views.py @@ -7,9 +7,11 @@ from django.shortcuts import get_object_or_404 from django.contrib.contenttypes.models import ContentType from django.shortcuts import render +from django.apps import apps + +import six from reversion.models import Version, Revision from reversion import revisions as reversion -from django.apps import apps from Lagerregal.utils import PaginationMixin from devices.models import Device, Room, Manufacturer @@ -103,7 +105,7 @@ def get_context_data(self, **kwargs): context["breadcrumbs"] = [ (reverse("{0}-list".format(context["this_version"].content_type.model)), _(context["this_version"].content_type.name)), - (context["current_version"].get_absolute_url(), context["current_version"].__unicode__()), + (context["current_version"].get_absolute_url(), six.text_type(context["current_version"])), (reverse("history-list", kwargs={"content_type_id": context["this_version"].content_type.id, "object_id": context["this_version"].object_id}), _("History")), ("", _("Version {0}".format(context["this_version"].pk))) @@ -152,7 +154,7 @@ def get_context_data(self, **kwargs): context["breadcrumbs"] = [ (reverse("{0}-list".format(self.content_type.model)), _(self.content_type.name)), - (self.object.get_absolute_url(), self.object.__unicode__()), + (self.object.get_absolute_url(), six.text_type(self.object)), (reverse("history-list", kwargs={"content_type_id": self.content_type.id, "object_id": self.object.id}), _("History")) ] diff --git a/locations/tests.py b/locations/tests.py index 218fc222..397a7218 100644 --- a/locations/tests.py +++ b/locations/tests.py @@ -1,8 +1,10 @@ from django.test.client import Client from django.test import TestCase -from model_mommy import mommy from django.core.urlresolvers import reverse +import six +from model_mommy import mommy + from locations.models import Section from users.models import Lageruser @@ -15,6 +17,6 @@ def setUp(self): def test_section_creation(self): section = mommy.make(Section) - self.assertEqual(section.__unicode__(), section.name) + self.assertEqual(six.text_type(section), section.name) self.assertEqual(section.get_absolute_url(), reverse('section-detail', kwargs={'pk': section.pk})) self.assertEqual(section.get_edit_url(), reverse('section-edit', kwargs={'pk': section.pk})) diff --git a/mail/models.py b/mail/models.py index b7d22acb..854b8881 100644 --- a/mail/models.py +++ b/mail/models.py @@ -56,7 +56,7 @@ def send(self, request, recipients=None, data=None): "inventoried": data["device"].inventoried, "inventorynumber": data["device"].inventorynumber, "manufacturer": data["device"].manufacturer, - "name": data["device"].__unicode__(), + "name": six.text_type(data["device"]), "room": (data["device"].room.name + " (" + data["device"].room.building.name + ")" if data[ "device"].room is not None else ""), "serialnumber": data["device"].serialnumber, @@ -67,7 +67,7 @@ def send(self, request, recipients=None, data=None): } if data["device"].currentlending is not None: datadict["device"]["currentlending"] = { - "owner": data["device"].currentlending.owner.__unicode__(), + "owner": six.text_type(data["device"].currentlending.owner), "duedate": data["device"].currentlending.duedate, "lenddate": data["device"].currentlending.lenddate }, @@ -108,7 +108,7 @@ class MailTemplateRecipient(models.Model): content_object = GenericForeignKey('content_type', 'object_id') def __str__(self): - return six.text_type(self.content_type.name + ": " + self.content_object.__unicode__()) + return six.text_type(self.content_type.name + ": " + six.text_type(self.content_object)) class MailHistory(models.Model): diff --git a/mail/tests.py b/mail/tests.py index 77743b4a..22eb6294 100644 --- a/mail/tests.py +++ b/mail/tests.py @@ -2,10 +2,12 @@ from django.test.client import Client, RequestFactory from django.test import TestCase -from model_mommy import mommy from django.core.urlresolvers import reverse from django.contrib.contenttypes.models import ContentType +import six +from model_mommy import mommy + from mail.models import MailTemplate, MailTemplateRecipient, MailHistory from devices.models import Device, Room, Building, Lending from users.models import Lageruser @@ -19,7 +21,7 @@ def setUp(self): def test_template_creation(self): template = mommy.make(MailTemplate) - self.assertEqual(template.__unicode__(), template.name) + self.assertEqual(six.text_type(template), template.name) self.assertEqual(template.get_absolute_url(), reverse('mail-detail', kwargs={'pk': template.pk})) self.assertEqual(template.get_edit_url(), reverse('mail-edit', kwargs={'pk': template.pk})) @@ -34,7 +36,7 @@ def test_template_creation(self): # def test_template_creation(self): # con = mommy.make(ContentType) # rec = mommy.make(MailTemplateRecipient, content_type = con) -# self.assertEqual(rec.__unicode__(), unicode(rec.content_type.name + ": " + rec.content_object.__unicode__())) +# self.assertEqual(six.text_type(rec), unicode(rec.content_type.name + ": " + six.text_type(rec.content_object))) # find out why url does not exist # class TestMailHistory(TestCase): diff --git a/network/views.py b/network/views.py index 50b45124..0e9e1001 100644 --- a/network/views.py +++ b/network/views.py @@ -8,6 +8,8 @@ from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.shortcuts import render + +import six from reversion import revisions as reversion from network.models import IpAddress @@ -150,7 +152,7 @@ def get(self, request, *args, **kwargs): context["ipaddress"] = get_object_or_404(IpAddress, pk=kwargs["ipaddress"]) context["breadcrumbs"] = [ (reverse("user-list"), _("Users")), - (reverse("userprofile", kwargs={"pk": context["user"].pk}), context["user"].__unicode__()), + (reverse("userprofile", kwargs={"pk": context["user"].pk}), six.text_type(context["user"])), ("", _("Unassign IP-Address"))] return render(request, self.template_name, context) @@ -158,7 +160,7 @@ def post(self, request, *args, **kwargs): user = get_object_or_404(Lageruser, pk=kwargs["pk"]) ipaddress = get_object_or_404(IpAddress, pk=kwargs["ipaddress"]) ipaddress.user = None - reversion.set_comment(_("Removed from User {0}".format(user.__unicode__()))) + reversion.set_comment(_("Removed from User {0}".format(six.text_type(user)))) ipaddress.save() return HttpResponseRedirect(reverse("userprofile", kwargs={"pk": user.pk})) @@ -174,14 +176,14 @@ def get_context_data(self, **kwargs): user = context["form"].cleaned_data["user"] context["breadcrumbs"] = [ (reverse("user-list"), _("Users")), - (reverse("userprofile", kwargs={"pk": user.pk}), user.__unicode__()), + (reverse("userprofile", kwargs={"pk": user.pk}), six.text_type(user)), ("", _("Assign IP-Addresses"))] return context def form_valid(self, form): ipaddresses = form.cleaned_data["ipaddresses"] user = form.cleaned_data["user"] - reversion.set_comment(_("Assigned to User {0}").format(user.__unicode__())) + reversion.set_comment(_("Assigned to User {0}").format(six.text_type(user))) for ipaddress in ipaddresses: ipaddress.user = user ipaddress.save() diff --git a/users/tests.py b/users/tests.py index 92fa6da1..b6c80635 100644 --- a/users/tests.py +++ b/users/tests.py @@ -3,6 +3,8 @@ from django.test.client import Client from django.test import TestCase from django.core.urlresolvers import reverse + +import six from model_mommy import mommy from users.models import Lageruser, Department @@ -17,8 +19,8 @@ def setUp(self): def test_lageruser_creation(self): user1 = mommy.make(Lageruser, first_name="a", last_name="a") user2 = mommy.make(Lageruser, first_name="", last_name="a") - self.assertEqual(user1.__unicode__(), "{0} {1}".format(user1.first_name, user1.last_name)) - self.assertEqual(user2.__unicode__(), user2.username) + self.assertEqual(six.text_type(user1), "{0} {1}".format(user1.first_name, user1.last_name)) + self.assertEqual(six.text_type(user2), user2.username) self.assertEqual(user1.get_absolute_url(), reverse('userprofile', kwargs={'pk': user1.pk})) user1.clean() self.assertEqual(user1.expiration_date, None) @@ -32,4 +34,4 @@ def setUp(self): def test_department_creation(self): department = mommy.make(Department) - self.assertEqual(department.__unicode__(), department.name) + self.assertEqual(six.text_type(department), department.name) From 31821d94fa31bd38cc8dc6b186387e367b065900 Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Tue, 19 Jun 2018 17:00:56 +0200 Subject: [PATCH 03/10] add unicode_literals import where missing --- Lagerregal/template_development.py | 2 ++ Lagerregal/template_production.py | 2 ++ Lagerregal/urls.py | 2 ++ Lagerregal/wsgi.py | 2 ++ api/serializers.py | 2 ++ api/tests.py | 1 + devicegroups/models.py | 2 ++ devicegroups/tests.py | 2 ++ devices/admin.py | 2 ++ devices/context_processors.py | 2 ++ devices/models.py | 2 ++ devices/perms.py | 2 ++ devices/tests.py | 2 ++ devicetags/forms.py | 2 ++ devicetags/models.py | 2 ++ devicetags/tests.py | 2 ++ devicetags/views.py | 2 ++ devicetypes/ajax.py | 2 ++ devicetypes/models.py | 2 ++ devicetypes/tests.py | 2 ++ generate_secret_key.py | 2 ++ history/tests.py | 2 ++ locations/models.py | 2 ++ locations/tests.py | 2 ++ mail/forms.py | 2 ++ mail/models.py | 2 ++ mail/tests.py | 2 ++ mail/views.py | 2 ++ main/models.py | 2 ++ main/tests.py | 2 ++ main/views.py | 2 ++ network/forms.py | 2 ++ network/models.py | 2 ++ network/perms.py | 2 ++ network/tests.py | 2 ++ users/admin.py | 2 ++ users/middleware.py | 2 ++ users/perms.py | 2 ++ 38 files changed, 75 insertions(+) diff --git a/Lagerregal/template_development.py b/Lagerregal/template_development.py index 1a4e0d27..a891798e 100644 --- a/Lagerregal/template_development.py +++ b/Lagerregal/template_development.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from .base_settings import * DEBUG = True diff --git a/Lagerregal/template_production.py b/Lagerregal/template_production.py index 3b0a4447..98b6e7bf 100644 --- a/Lagerregal/template_production.py +++ b/Lagerregal/template_production.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from .base_settings import * DEBUG = False diff --git a/Lagerregal/urls.py b/Lagerregal/urls.py index 24d7bfa8..91b57135 100644 --- a/Lagerregal/urls.py +++ b/Lagerregal/urls.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.conf.urls import include, url from django.contrib.auth.decorators import login_required from django.contrib.auth.views import logout diff --git a/Lagerregal/wsgi.py b/Lagerregal/wsgi.py index 527df583..775de1a3 100644 --- a/Lagerregal/wsgi.py +++ b/Lagerregal/wsgi.py @@ -13,6 +13,8 @@ framework. """ +from __future__ import unicode_literals + import os import sys diff --git a/api/serializers.py b/api/serializers.py index d802bcca..afa7df31 100644 --- a/api/serializers.py +++ b/api/serializers.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from rest_framework import serializers from django.contrib.auth.models import Group, Permission diff --git a/api/tests.py b/api/tests.py index 501deb77..e61f392e 100644 --- a/api/tests.py +++ b/api/tests.py @@ -4,6 +4,7 @@ Replace this with more appropriate tests for your application. """ +from __future__ import unicode_literals from django.test import TestCase diff --git a/devicegroups/models.py b/devicegroups/models.py index 21668333..8b173fe0 100644 --- a/devicegroups/models.py +++ b/devicegroups/models.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.db import models from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse diff --git a/devicegroups/tests.py b/devicegroups/tests.py index b15a9a09..9571eecd 100644 --- a/devicegroups/tests.py +++ b/devicegroups/tests.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.test.client import Client from django.test import TestCase from django.core.urlresolvers import reverse diff --git a/devices/admin.py b/devices/admin.py index f00d152c..62976308 100644 --- a/devices/admin.py +++ b/devices/admin.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.contrib import admin from devices.models import * diff --git a/devices/context_processors.py b/devices/context_processors.py index 342340fc..d0fc7406 100644 --- a/devices/context_processors.py +++ b/devices/context_processors.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.conf import settings # import the settings file diff --git a/devices/models.py b/devices/models.py index a7608c25..c7286127 100644 --- a/devices/models.py +++ b/devices/models.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import datetime from django.db import models diff --git a/devices/perms.py b/devices/perms.py index 14536e67..29fb16fa 100644 --- a/devices/perms.py +++ b/devices/perms.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + __author__ = 'viirus' from permission.logics import PermissionLogic from permission.conf import settings diff --git a/devices/tests.py b/devices/tests.py index 8450c36f..7d3a9280 100644 --- a/devices/tests.py +++ b/devices/tests.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import os.path from datetime import datetime, timedelta diff --git a/devicetags/forms.py b/devicetags/forms.py index 508a3068..16dd0b03 100644 --- a/devicetags/forms.py +++ b/devicetags/forms.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django import forms from devicetags.models import Devicetag diff --git a/devicetags/models.py b/devicetags/models.py index 3276e5c6..b908c730 100644 --- a/devicetags/models.py +++ b/devicetags/models.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.db import models from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse diff --git a/devicetags/tests.py b/devicetags/tests.py index 6e28243f..b6816ca3 100644 --- a/devicetags/tests.py +++ b/devicetags/tests.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.test.client import Client from django.test import TestCase from django.core.urlresolvers import reverse diff --git a/devicetags/views.py b/devicetags/views.py index 06abe4dc..aff0c7db 100644 --- a/devicetags/views.py +++ b/devicetags/views.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.views.generic import ListView, CreateView, UpdateView, DeleteView, FormView from django.core.urlresolvers import reverse_lazy, reverse from django.utils.translation import ugettext_lazy as _ diff --git a/devicetypes/ajax.py b/devicetypes/ajax.py index 524896b8..49cbca99 100644 --- a/devicetypes/ajax.py +++ b/devicetypes/ajax.py @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*- +from __future__ import unicode_literals + import json from django.http import HttpResponse diff --git a/devicetypes/models.py b/devicetypes/models.py index d6e4e709..a7e3d130 100644 --- a/devicetypes/models.py +++ b/devicetypes/models.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.db import models from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse diff --git a/devicetypes/tests.py b/devicetypes/tests.py index c1f9197d..1b613188 100644 --- a/devicetypes/tests.py +++ b/devicetypes/tests.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.test.client import Client from django.test import TestCase from django.core.urlresolvers import reverse diff --git a/generate_secret_key.py b/generate_secret_key.py index 56fb0b90..c20bf29d 100644 --- a/generate_secret_key.py +++ b/generate_secret_key.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.utils.crypto import get_random_string chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*(-_=+)' diff --git a/history/tests.py b/history/tests.py index b280b529..0caac4ea 100644 --- a/history/tests.py +++ b/history/tests.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.test.client import Client from django.test import TestCase from model_mommy import mommy diff --git a/locations/models.py b/locations/models.py index f018210d..5ec62c88 100644 --- a/locations/models.py +++ b/locations/models.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.db import models from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse diff --git a/locations/tests.py b/locations/tests.py index 397a7218..83eea569 100644 --- a/locations/tests.py +++ b/locations/tests.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.test.client import Client from django.test import TestCase from django.core.urlresolvers import reverse diff --git a/mail/forms.py b/mail/forms.py index 42a7369e..7548a5f0 100644 --- a/mail/forms.py +++ b/mail/forms.py @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*- +from __future__ import unicode_literals + from django import forms from mail.models import MailTemplate diff --git a/mail/models.py b/mail/models.py index 854b8881..c6f86b8a 100644 --- a/mail/models.py +++ b/mail/models.py @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*- +from __future__ import unicode_literals + from django.db import models from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse diff --git a/mail/tests.py b/mail/tests.py index 22eb6294..b9702d74 100644 --- a/mail/tests.py +++ b/mail/tests.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import os.path from django.test.client import Client, RequestFactory diff --git a/mail/views.py b/mail/views.py index 9da58108..6fd02a14 100644 --- a/mail/views.py +++ b/mail/views.py @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*- +from __future__ import unicode_literals + from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.core.urlresolvers import reverse_lazy, reverse from django.utils.translation import ugettext_lazy as _ diff --git a/main/models.py b/main/models.py index da24bdb9..98ffd1c7 100644 --- a/main/models.py +++ b/main/models.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.db import models from django.utils.translation import ugettext_lazy as _ from django.db.models.signals import post_save diff --git a/main/tests.py b/main/tests.py index 16073e85..d37eafdb 100644 --- a/main/tests.py +++ b/main/tests.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.test import TestCase from main.models import get_progresscolor diff --git a/main/views.py b/main/views.py index 586382f5..0ef8e688 100644 --- a/main/views.py +++ b/main/views.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + import datetime from django.views.generic import TemplateView, ListView diff --git a/network/forms.py b/network/forms.py index f78c54ca..963916bc 100644 --- a/network/forms.py +++ b/network/forms.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django import forms from django.utils.translation import ugettext_lazy as _ diff --git a/network/models.py b/network/models.py index e6336119..a17f15b0 100644 --- a/network/models.py +++ b/network/models.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.db import models from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse diff --git a/network/perms.py b/network/perms.py index 02a760de..84f988df 100644 --- a/network/perms.py +++ b/network/perms.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + __author__ = 'viirus' from permission.logics import PermissionLogic from permission.conf import settings diff --git a/network/tests.py b/network/tests.py index 6f641793..96292138 100644 --- a/network/tests.py +++ b/network/tests.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.test.client import Client from django.test import TestCase from model_mommy import mommy diff --git a/users/admin.py b/users/admin.py index 8a61994f..0ec4aff0 100644 --- a/users/admin.py +++ b/users/admin.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.contrib import admin from users.models import Lageruser, Department, DepartmentUser diff --git a/users/middleware.py b/users/middleware.py index c89b80cf..662a5831 100644 --- a/users/middleware.py +++ b/users/middleware.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + from django.utils import timezone diff --git a/users/perms.py b/users/perms.py index 51bcf14a..4a03ed66 100644 --- a/users/perms.py +++ b/users/perms.py @@ -1,3 +1,5 @@ +from __future__ import unicode_literals + __author__ = 'viirus' from permission.logics import PermissionLogic from permission.conf import settings From bcb129ed35b6665632f176019c9cf4be9d66188f Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Tue, 19 Jun 2018 17:48:20 +0200 Subject: [PATCH 04/10] add linter config --- setup.cfg | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 setup.cfg diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 00000000..f5c9f360 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,15 @@ +[flake8] +exclude= + .git, + wsgi.py, + migrations, + settings.py, + template_*.py, + template, +# TODO fix some of these +ignore= E124, E126, E127, E128, E131, E501, E722, F403, F405, F999, W503 + +[isort] +known_django=django +sections=FUTURE,STDLIB,DJANGO,THIRDPARTY,FIRSTPARTY,LOCALFOLDER +line_length=120 From f3010a024bfb5cacbadb2aa6f62e31cd691b64d3 Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Tue, 19 Jun 2018 17:36:52 +0200 Subject: [PATCH 05/10] rm unused imports --- Lagerregal/base_settings.py | 1 - Lagerregal/utils.py | 8 -------- api/serializers.py | 1 - devices/admin.py | 1 - devices/ajax.py | 1 - devices/tests.py | 4 ---- devices/views.py | 3 --- devicetypes/tests.py | 1 - history/tests.py | 4 +--- history/views.py | 5 ++--- mail/ajax.py | 1 - mail/tests.py | 5 +---- network/forms.py | 2 +- network/perms.py | 2 -- network/tests.py | 2 +- users/models.py | 3 --- users/perms.py | 2 -- users/views.py | 2 +- 18 files changed, 7 insertions(+), 41 deletions(-) diff --git a/Lagerregal/base_settings.py b/Lagerregal/base_settings.py index 87532f82..752a2214 100644 --- a/Lagerregal/base_settings.py +++ b/Lagerregal/base_settings.py @@ -1,7 +1,6 @@ # Django settings for Lagerregal project. from __future__ import unicode_literals import os -from django.contrib.messages import constants as messages # Local time zone for this installation. Choices can be found here: diff --git a/Lagerregal/utils.py b/Lagerregal/utils.py index eda5f8b0..4e1503c5 100644 --- a/Lagerregal/utils.py +++ b/Lagerregal/utils.py @@ -1,18 +1,10 @@ from __future__ import unicode_literals -import csv -import codecs import uuid from datetime import date, timedelta -import six from django.conf import settings from django.test.runner import DiscoverRunner -try: - import io -except ImportError: - import cStringIO as io - class PaginationMixin(): def get_paginate_by(self, queryset): diff --git a/api/serializers.py b/api/serializers.py index afa7df31..90844717 100644 --- a/api/serializers.py +++ b/api/serializers.py @@ -4,7 +4,6 @@ from django.contrib.auth.models import Group, Permission from devices.models import Room, Building, Manufacturer, Device, Template, Lending, Picture -from django.contrib.auth.models import Group from devicetypes.models import Type, TypeAttribute from users.models import Lageruser, Department from network.models import IpAddress diff --git a/devices/admin.py b/devices/admin.py index 62976308..7401c2c4 100644 --- a/devices/admin.py +++ b/devices/admin.py @@ -3,7 +3,6 @@ from django.contrib import admin from devices.models import * -from reversion.models import Version, Revision class DeviceAdmin(admin.ModelAdmin): diff --git a/devices/ajax.py b/devices/ajax.py index 460fbb6b..4992f764 100644 --- a/devices/ajax.py +++ b/devices/ajax.py @@ -28,7 +28,6 @@ from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext from django.utils.dateparse import parse_date -from django.contrib import messages from devices.models import Device, Room, Building, Manufacturer, Lending from users.models import Lageruser, Department diff --git a/devices/tests.py b/devices/tests.py index 7d3a9280..1eee2663 100644 --- a/devices/tests.py +++ b/devices/tests.py @@ -1,7 +1,5 @@ from __future__ import unicode_literals -import os.path - from datetime import datetime, timedelta from django.test.client import Client @@ -14,8 +12,6 @@ from devices.models import Device, Building, Room, Manufacturer, Template, Note, Lending, DeviceInformationType, DeviceInformation, Picture from users.models import Lageruser from network.models import IpAddress -from devices.forms import IpAddressForm -from devices.forms import DeviceForm class DeviceTests(TestCase): diff --git a/devices/views.py b/devices/views.py index 5205c166..a283f1ea 100644 --- a/devices/views.py +++ b/devices/views.py @@ -3,10 +3,7 @@ import datetime import time import csv -from django.utils.translation import ugettext_lazy as _ -from django.utils.decorators import method_decorator -from django.views.decorators.clickjacking import xframe_options_exempt from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView, View, FormView, TemplateView from django.views.generic.detail import SingleObjectTemplateResponseMixin, BaseDetailView, SingleObjectMixin from django.core.urlresolvers import reverse_lazy, reverse diff --git a/devicetypes/tests.py b/devicetypes/tests.py index 1b613188..73dbd986 100644 --- a/devicetypes/tests.py +++ b/devicetypes/tests.py @@ -7,7 +7,6 @@ import six from model_mommy import mommy -from devicetypes.models import Type, TypeAttribute, TypeAttributeValue from devicetypes.models import Type from users.models import Lageruser diff --git a/history/tests.py b/history/tests.py index 0caac4ea..db9d79f7 100644 --- a/history/tests.py +++ b/history/tests.py @@ -5,10 +5,8 @@ from model_mommy import mommy from django.core.urlresolvers import reverse -from devices.models import Device, Building, Room, Manufacturer, Template, Note +from devices.models import Device from users.models import Lageruser -from network.models import IpAddress -from reversion.models import Version class HistoryTests(TestCase): diff --git a/history/views.py b/history/views.py index adfe261c..4b153f28 100644 --- a/history/views.py +++ b/history/views.py @@ -1,12 +1,11 @@ from __future__ import unicode_literals from django.contrib import messages from django.http import HttpResponseRedirect -from django.views.generic import ListView, View, UpdateView +from django.views.generic import ListView, UpdateView from django.core.urlresolvers import reverse -from django.utils.translation import ugettext_lazy as _, ugettext +from django.utils.translation import ugettext_lazy as _ from django.shortcuts import get_object_or_404 from django.contrib.contenttypes.models import ContentType -from django.shortcuts import render from django.apps import apps import six diff --git a/mail/ajax.py b/mail/ajax.py index 2ac401c2..66d369fe 100644 --- a/mail/ajax.py +++ b/mail/ajax.py @@ -4,7 +4,6 @@ import six from django.views.generic.base import View from django.http import HttpResponse -from django.utils.translation import ugettext_lazy as _ from mail.models import usages from mail.models import MailTemplate diff --git a/mail/tests.py b/mail/tests.py index b9702d74..fca92c2e 100644 --- a/mail/tests.py +++ b/mail/tests.py @@ -1,8 +1,6 @@ from __future__ import unicode_literals -import os.path - -from django.test.client import Client, RequestFactory +from django.test.client import Client from django.test import TestCase from django.core.urlresolvers import reverse from django.contrib.contenttypes.models import ContentType @@ -11,7 +9,6 @@ from model_mommy import mommy from mail.models import MailTemplate, MailTemplateRecipient, MailHistory -from devices.models import Device, Room, Building, Lending from users.models import Lageruser diff --git a/network/forms.py b/network/forms.py index 963916bc..ae363bb8 100644 --- a/network/forms.py +++ b/network/forms.py @@ -4,7 +4,7 @@ from django.utils.translation import ugettext_lazy as _ from network.models import IpAddress -from users.models import Lageruser, Department +from users.models import Lageruser from devices.forms import get_department_options VIEWFILTER = ( diff --git a/network/perms.py b/network/perms.py index 84f988df..08a6f93c 100644 --- a/network/perms.py +++ b/network/perms.py @@ -3,8 +3,6 @@ __author__ = 'viirus' from permission.logics import PermissionLogic from permission.conf import settings -from django.contrib import auth -from django.core.exceptions import PermissionDenied class IPAddressPermissionLogic(PermissionLogic): diff --git a/network/tests.py b/network/tests.py index 96292138..9e1ceecf 100644 --- a/network/tests.py +++ b/network/tests.py @@ -5,10 +5,10 @@ from model_mommy import mommy from django.core.urlresolvers import reverse -from devices.models import Device, Template, Note from users.models import Lageruser from network.models import IpAddress + class IpAddressTests(TestCase): def setUp(self): '''method for setting up a client for testing''' diff --git a/users/models.py b/users/models.py index ef570215..9a3c10c1 100644 --- a/users/models.py +++ b/users/models.py @@ -15,10 +15,7 @@ from django.dispatch import receiver from django_auth_ldap.backend import populate_user -from django.conf import settings -import re import six -from datetime import date from Lagerregal import utils diff --git a/users/perms.py b/users/perms.py index 4a03ed66..3b05662e 100644 --- a/users/perms.py +++ b/users/perms.py @@ -3,8 +3,6 @@ __author__ = 'viirus' from permission.logics import PermissionLogic from permission.conf import settings -from django.contrib import auth -from django.core.exceptions import PermissionDenied class DepartmentPermissionLogic(PermissionLogic): diff --git a/users/views.py b/users/views.py index 37351dff..4ba2d4a7 100644 --- a/users/views.py +++ b/users/views.py @@ -25,7 +25,7 @@ from permission.decorators import permission_required from users.models import Lageruser, Department, DepartmentUser -from devices.models import Lending, Device +from devices.models import Lending from users.forms import SettingsForm, AvatarForm, DepartmentAddUserForm from Lagerregal import settings from Lagerregal.utils import PaginationMixin From 1dd7aa3bc84048fa9a8447b92e886ff280013729 Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Tue, 19 Jun 2018 17:37:02 +0200 Subject: [PATCH 06/10] fix unused variables --- devicegroups/tests.py | 2 +- devices/ajax.py | 1 - devices/forms.py | 2 +- devices/management/commands/ldapimport.py | 6 ++-- devices/perms.py | 3 -- devices/tests.py | 40 ++++++++++------------- devices/views.py | 2 -- devicetags/tests.py | 2 +- devicetypes/tests.py | 6 ++-- locations/tests.py | 2 +- mail/tests.py | 2 +- network/tests.py | 6 ++-- users/tests.py | 4 +-- 13 files changed, 31 insertions(+), 47 deletions(-) diff --git a/devicegroups/tests.py b/devicegroups/tests.py index 9571eecd..b06609b4 100644 --- a/devicegroups/tests.py +++ b/devicegroups/tests.py @@ -14,7 +14,7 @@ class DevicegroupTests(TestCase): def setUp(self): self.client = Client() - my_admin = Lageruser.objects.create_superuser("test", "test@test.com", "test") + Lageruser.objects.create_superuser("test", "test@test.com", "test") self.client.login(username='test', password='test') def test_devicegroup_creation(self): diff --git a/devices/ajax.py b/devices/ajax.py index 4992f764..d55d25e7 100644 --- a/devices/ajax.py +++ b/devices/ajax.py @@ -546,7 +546,6 @@ def post(self, request): conn = httplib.HTTPSConnection(settings.PUPPETDB_SETTINGS['host'], settings.PUPPETDB_SETTINGS['port'], context=context) - req = settings.PUPPETDB_SETTINGS['req'] + params conn.request("GET", settings.PUPPETDB_SETTINGS['req'] + params) res = conn.getresponse() if res.status != httplib.OK: diff --git a/devices/forms.py b/devices/forms.py index a1fb72b1..8e519851 100644 --- a/devices/forms.py +++ b/devices/forms.py @@ -185,7 +185,7 @@ def __init__(self, pk=None, *args, **kwargs): device = None try: device = Device.objects.filter(pk = pk)[0] - except Exception as e: + except: pass if device: self.fields['owner'].initial = device.currentlending.owner diff --git a/devices/management/commands/ldapimport.py b/devices/management/commands/ldapimport.py index 1a7be2a9..c4f434dd 100644 --- a/devices/management/commands/ldapimport.py +++ b/devices/management/commands/ldapimport.py @@ -78,7 +78,7 @@ def handle(self, *args, **options): user = Lageruser.objects.get(username=userdata["sAMAccountName"][0]) except TypeError: continue - except Exception as e: + except: saveuser = True created = True user = Lageruser(username=userdata["sAMAccountName"][0]) @@ -90,7 +90,7 @@ def handle(self, *args, **options): try: department_name = re.findall(settings.AUTH_LDAP_DEPARTMENT_REGEX, new_value)[-1] new_value = Department.objects.get(name=department_name) - except Department.DoesNotExist as e: + except Department.DoesNotExist: new_value = Department(name=department_name) new_value.save() except IndexError: @@ -119,7 +119,7 @@ def handle(self, *args, **options): saveuser = True setattr(user, field, new_value) changes[field] = (old_value, new_value) - except Exception as e: + except: if attr == "accountExpires": continue if attr == "givenName" or attr == "sn": diff --git a/devices/perms.py b/devices/perms.py index 29fb16fa..92714f5e 100644 --- a/devices/perms.py +++ b/devices/perms.py @@ -64,9 +64,6 @@ def has_perm(self, user_obj, perm, obj=None): if not user_obj.is_authenticated(): return False - change_permission = self.get_full_permission_string('change') - delete_permission = self.get_full_permission_string('delete') - if obj is None: backend = auth.get_backends()[0] try: diff --git a/devices/tests.py b/devices/tests.py index 1eee2663..f8ef85a3 100644 --- a/devices/tests.py +++ b/devices/tests.py @@ -19,7 +19,7 @@ class DeviceTests(TestCase): def setUp(self): '''method for setting up a client for testing''' self.client = Client() - my_admin = Lageruser.objects.create_superuser('test', 'test@test.com', "test") + Lageruser.objects.create_superuser('test', 'test@test.com', "test") self.client.login(username="test", password="test") def test_device_creation(self): @@ -37,7 +37,7 @@ def test_device_creation(self): self.assertFalse(mommy.make(Device, currentlending = lending_future).is_overdue()) def test_device_list(self): - devices = mommy.make(Device, _quantity=40) + mommy.make(Device, _quantity=40) url = reverse("device-list") resp = self.client.get(url) self.assertEqual(resp.status_code, 200) @@ -124,14 +124,14 @@ def test_device_trash_sets_child_used_in_to_none(self): device = mommy.make(Device) used_device = mommy.make(Device, used_in = device) trashurl = reverse('device-trash', kwargs={'pk': device.pk}) - resp = self.client.post(trashurl) + self.client.post(trashurl) used_device = Device.objects.filter(pk = used_device.pk)[0] self.assertIsNone(used_device.used_in) def test_device_trash_sets_self_used_in_to_none(self): device = mommy.make(Device, _fill_optional=['used_in']) trashurl = reverse("device-trash", kwargs={'pk' : device.pk}) - resp = self.client.post(trashurl) + self.client.post(trashurl) device = Device.objects.filter(pk = device.pk)[0] self.assertIsNone(device.used_in) @@ -140,7 +140,7 @@ def test_device_trash_returns_lending(self): lending.device.currentlending = lending lending.device.save() trashurl = reverse("device-trash", kwargs={"pk": lending.device.pk}) - resp = self.client.post(trashurl) + self.client.post(trashurl) lending.refresh_from_db() self.assertIsNotNone(lending.returndate) @@ -237,7 +237,7 @@ def test_device_return(self): class BuildingTests(TestCase): def setUp(self): self.client = Client() - my_admin = Lageruser.objects.create_superuser('test', 'test@test.com', "test") + Lageruser.objects.create_superuser('test', 'test@test.com', "test") self.client.login(username="test", password="test") def test_building_creation(self): @@ -249,7 +249,7 @@ def test_building_creation(self): self.assertEqual(building.get_edit_url(), reverse('building-edit', kwargs={'pk': building.pk})) def test_building_list(self): - buildings = mommy.make(Building, _quantity=40) + mommy.make(Building, _quantity=40) url = reverse("building-list") resp = self.client.get(url) self.assertEqual(resp.status_code, 200) @@ -268,9 +268,6 @@ def test_building_detail(self): self.assertEqual(resp.status_code, 200) def test_building_add(self): - building = mommy.make(Building) - buildings = Building.objects.all() - building = buildings[0] url = reverse("building-add") resp = self.client.get(url) self.assertEqual(resp.status_code, 200) @@ -295,7 +292,7 @@ def test_building_delete(self): class RoomTests(TestCase): def setUp(self): self.client = Client() - my_admin = Lageruser.objects.create_superuser('test', 'test@test.com', "test") + Lageruser.objects.create_superuser('test', 'test@test.com', "test") self.client.login(username="test", password="test") def test_room_creation(self): @@ -310,7 +307,7 @@ def test_room_creation(self): self.assertEqual(room.get_edit_url(), reverse('room-edit', kwargs={'pk': room.pk})) def test_room_list(self): - rooms = mommy.make(Room, _quantity=40) + mommy.make(Room, _quantity=40) url = reverse("room-list") resp = self.client.get(url) self.assertEqual(resp.status_code, 200) @@ -329,7 +326,6 @@ def test_room_detail(self): self.assertEqual(resp.status_code, 200) def test_room_add(self): - room = mommy.make(Room) url = reverse("room-add") resp = self.client.get(url) self.assertEqual(resp.status_code, 200) @@ -354,7 +350,7 @@ def test_room_delete(self): class ManufacturerTests(TestCase): def setUp(self): self.client = Client() - my_admin = Lageruser.objects.create_superuser('test', 'test@test.com', "test") + Lageruser.objects.create_superuser('test', 'test@test.com', "test") self.client.login(username="test", password="test") def test_manufacturer_creation(self): @@ -366,7 +362,7 @@ def test_manufacturer_creation(self): self.assertEqual(manufacturer.get_edit_url(), reverse('manufacturer-edit', kwargs={'pk': manufacturer.pk})) def test_manufacturer_list(self): - manufacturers = mommy.make(Manufacturer, _quantity=40) + mommy.make(Manufacturer, _quantity=40) url = reverse("manufacturer-list") resp = self.client.get(url) self.assertEqual(resp.status_code, 200) @@ -385,7 +381,6 @@ def test_manufacturer_detail(self): self.assertEqual(resp.status_code, 200) def test_manufacturer_add(self): - manufacturer = mommy.make(Manufacturer) url = reverse("manufacturer-add") resp = self.client.get(url) self.assertEqual(resp.status_code, 200) @@ -410,7 +405,7 @@ def test_manufacturer_delete(self): class TemplateTests(TestCase): def setUp(self): self.client = Client() - my_admin = Lageruser.objects.create_superuser('test', 'test@test.com', "test") + Lageruser.objects.create_superuser('test', 'test@test.com', "test") self.client.login(username="test", password="test") def test_template_creation(self): @@ -421,7 +416,7 @@ def test_template_creation(self): self.assertEqual(template.get_as_dict(), {'name': template.name, 'description': template.description, 'manufacturer' : template.manufacturer, 'devicetype' : template.devicetype }) def test_template_list(self): - templates = mommy.make(Template, _quantity=40) + mommy.make(Template, _quantity=40) url = reverse("template-list") resp = self.client.get(url) self.assertEqual(resp.status_code, 200) @@ -432,7 +427,6 @@ def test_template_list(self): self.assertEqual(resp.status_code, 200) def test_template_add(self): - template = mommy.make(Template) url = reverse("template-add") resp = self.client.get(url) self.assertEqual(resp.status_code, 200) @@ -457,7 +451,7 @@ def test_template_delete(self): class NoteTests(TestCase): def setUp(self): self.client = Client() - my_admin = Lageruser.objects.create_superuser('test', 'test@test.com', "test") + Lageruser.objects.create_superuser('test', 'test@test.com', "test") self.client.login(username="test", password="test") def test_note_creation(self): @@ -468,7 +462,7 @@ def test_note_creation(self): class DeviceInformationTypeTests(TestCase): def setUp(self): self.client = Client() - my_admin = Lageruser.objects.create_superuser('test', 'test@test.com', 'test') + Lageruser.objects.create_superuser('test', 'test@test.com', 'test') self.client.login(username = 'test', password = 'test') def test_device_information_type_creation(self): @@ -479,7 +473,7 @@ def test_device_information_type_creation(self): class DeviceInformationTests(TestCase): def setUp(self): self.client = Client() - my_admin = Lageruser.objects.create_superuser('test', 'test@test.com', 'test') + Lageruser.objects.create_superuser('test', 'test@test.com', 'test') self.client.login(username = 'test', password = 'test') def test_device_information_creation(self): @@ -490,7 +484,7 @@ def test_device_information_creation(self): class PictureTests(TestCase): def setUp(self): self.client = Client() - my_admin = Lageruser.objects.create_superuser('test', 'test@test.com', "test") + Lageruser.objects.create_superuser('test', 'test@test.com', "test") self.client.login(username="test", password="test") def test_picture_creation(self): diff --git a/devices/views.py b/devices/views.py index a283f1ea..8db552bb 100644 --- a/devices/views.py +++ b/devices/views.py @@ -164,7 +164,6 @@ def post(self, request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="' + str(int(time.time())) + '_searchresult.csv"' devices = None - departments = None searchvalues = ["id", "name", "inventorynumber", "devicetype__name", "room__name", "group__name"] if request.POST['viewfilter'] == "active": @@ -532,7 +531,6 @@ def form_valid(self, form): if form.cleaned_data["department"]: if not form.cleaned_data["department"] in self.request.user.departments.all(): return HttpResponseBadRequest() - deviceid = self.kwargs["pk"] device = self.object if device.archived is not None: messages.error(self.request, _("Archived Devices can't be edited")) diff --git a/devicetags/tests.py b/devicetags/tests.py index b6816ca3..de9258ac 100644 --- a/devicetags/tests.py +++ b/devicetags/tests.py @@ -14,7 +14,7 @@ class DevitagsTests(TestCase): def setUp(self): self.client = Client() - myadmin = Lageruser.objects.create_superuser('test', 'test@test.com', 'test') + Lageruser.objects.create_superuser('test', 'test@test.com', 'test') self.client.login(username='test', password='test') def test_devicetag_creation(self): diff --git a/devicetypes/tests.py b/devicetypes/tests.py index 73dbd986..02c1193e 100644 --- a/devicetypes/tests.py +++ b/devicetypes/tests.py @@ -16,7 +16,7 @@ class TypeTests(TestCase): def setUp(self): '''method for setting up a client for testing''' self.client = Client() - my_admin = Lageruser.objects.create_superuser('test', 'test@test.com', "test") + Lageruser.objects.create_superuser('test', 'test@test.com', "test") self.client.login(username="test", password="test") def test_type_creation(self): @@ -34,7 +34,7 @@ def test_type_creation(self): def test_type_list(self): '''method for testing the presentation and reachability of the list of devicestypes over several pages''' - devicetypes = mommy.make(Type, _quantity=40) + mommy.make(Type, _quantity=40) # testing if loading of devicetype-list-page was successful (statuscode 2xx) url = reverse("type-list") @@ -64,8 +64,6 @@ def test_type_detail(self): def test_type_add(self): '''method for testing adding a devicetype''' - devicetype = mommy.make(Type) - # testing successful loading of devicetype-page of added device (statuscode 2xx) url = reverse("type-add") resp = self.client.get(url) diff --git a/locations/tests.py b/locations/tests.py index 83eea569..c62cfd1e 100644 --- a/locations/tests.py +++ b/locations/tests.py @@ -14,7 +14,7 @@ class SectionTests(TestCase): def setUp(self): self.client = Client() - myadmin = Lageruser.objects.create_superuser("test", "test@test.com", "test") + Lageruser.objects.create_superuser("test", "test@test.com", "test") self.client.login(username="test", password="test") def test_section_creation(self): diff --git a/mail/tests.py b/mail/tests.py index fca92c2e..73f8167f 100644 --- a/mail/tests.py +++ b/mail/tests.py @@ -15,7 +15,7 @@ class TestMailTemplate(TestCase): def setUp(self): self.client = Client() - myadmin = Lageruser.objects.create_superuser("test", "test@test.com", "test") + Lageruser.objects.create_superuser("test", "test@test.com", "test") self.client.login(username="test", password="test") def test_template_creation(self): diff --git a/network/tests.py b/network/tests.py index 9e1ceecf..3ade8216 100644 --- a/network/tests.py +++ b/network/tests.py @@ -13,7 +13,7 @@ class IpAddressTests(TestCase): def setUp(self): '''method for setting up a client for testing''' self.client = Client() - myadmin = Lageruser.objects.create_superuser("test", "test@test.com", 'test') + Lageruser.objects.create_superuser("test", "test@test.com", 'test') self.client.login(username="test", password="test") def test_IpAddress_creation(self): @@ -27,7 +27,7 @@ def test_IpAddress_creation(self): def test_IpAddress_list(self): '''method for testing the presentation and reachability of the list of IpAdresses over several pages''' - address = mommy.make(IpAddress, _quantity=40) + mommy.make(IpAddress, _quantity=40) # testing if loading of device-list-page was successful (statuscode 2xx) url = reverse("ipaddress-list") @@ -57,8 +57,6 @@ def test_IpAddress_detail(self): def test_IpAddress_add(self): '''method for testing adding a Ipaddress''' - address = mommy.make(IpAddress) - # testing successful loading of Ipaddress-page of added device (statuscode 2xx) url = reverse("ipaddress-add") resp = self.client.get(url) diff --git a/users/tests.py b/users/tests.py index b6c80635..f24d5ea7 100644 --- a/users/tests.py +++ b/users/tests.py @@ -13,7 +13,7 @@ class LageruserTests(TestCase): def setUp(self): self.client = Client() - myadmin = Lageruser.objects.create_superuser('test', "test@test.com", "test") + Lageruser.objects.create_superuser('test', "test@test.com", "test") self.client.login(username="test", password="test") def test_lageruser_creation(self): @@ -29,7 +29,7 @@ def test_lageruser_creation(self): class DepartmentTests(TestCase): def setUp(self): self.client = Client() - myadmin = Lageruser.objects.create_superuser('test', "test@test.com", "test") + Lageruser.objects.create_superuser('test', "test@test.com", "test") self.client.login(username="test", password="test") def test_department_creation(self): From 1aae4f2139dd2ce329062d928eb8db416946c7a5 Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Tue, 19 Jun 2018 17:35:01 +0200 Subject: [PATCH 07/10] Gardening --- Lagerregal/base_settings.py | 4 +- Lagerregal/urls.py | 5 +- Lagerregal/utils.py | 5 +- api/views.py | 1 + devices/ajax.py | 3 +- devices/forms.py | 9 ++-- devices/management/commands/ldapimport.py | 4 +- devices/models.py | 8 +-- devices/perms.py | 8 +-- devices/templatetags/devicetags.py | 6 ++- devices/tests.py | 61 ++++++++++++++--------- devices/views.py | 27 +++++----- devicetypes/ajax.py | 2 +- devicetypes/forms.py | 1 + devicetypes/tests.py | 1 - history/tests.py | 5 +- history/views.py | 1 + mail/ajax.py | 6 ++- mail/forms.py | 6 +-- mail/tests.py | 47 +++++++++-------- main/ajax.py | 1 + network/models.py | 6 +-- network/perms.py | 3 +- network/tests.py | 3 +- users/forms.py | 1 + users/models.py | 7 ++- users/perms.py | 3 +- users/views.py | 2 +- 28 files changed, 135 insertions(+), 101 deletions(-) diff --git a/Lagerregal/base_settings.py b/Lagerregal/base_settings.py index 752a2214..7328e904 100644 --- a/Lagerregal/base_settings.py +++ b/Lagerregal/base_settings.py @@ -126,8 +126,8 @@ ) LANGUAGES = ( - ('de', 'German'), - ('en', 'English'), + ('de', 'German'), + ('en', 'English'), ) AUTH_USER_MODEL = 'users.Lageruser' diff --git a/Lagerregal/urls.py b/Lagerregal/urls.py index 91b57135..5284d1d4 100644 --- a/Lagerregal/urls.py +++ b/Lagerregal/urls.py @@ -26,11 +26,12 @@ # Uncomment the next two lines to enable the admin: from django.contrib import admin from django.utils.translation import ugettext_lazy as _ -admin.autodiscover() -import permission; permission.autodiscover() +import permission from permission.decorators import permission_required from django.views.decorators.clickjacking import xframe_options_exempt +admin.autodiscover() +permission.autodiscover() urlpatterns = [ url(r'^$', login_required(Home.as_view()), name="home"), diff --git a/Lagerregal/utils.py b/Lagerregal/utils.py index 4e1503c5..65f927c5 100644 --- a/Lagerregal/utils.py +++ b/Lagerregal/utils.py @@ -1,4 +1,5 @@ from __future__ import unicode_literals + import uuid from datetime import date, timedelta @@ -42,7 +43,7 @@ def convert_ad_accountexpires(timestamp): if timestamp is None or timestamp == 0: return None epoch_start = date(year=1601, month=1, day=1) - seconds_since_epoch = timestamp/10**7 + seconds_since_epoch = timestamp / 10 ** 7 try: # ad timestamp can be > than date.max, return None (==never expires) new_date = epoch_start + timedelta(seconds=seconds_since_epoch) @@ -50,7 +51,7 @@ def convert_ad_accountexpires(timestamp): except OverflowError: return None except Exception: - print('Cannot convert expiration_date "{0}", falling back to None'.format(self.expiration_date)) + print('Cannot convert expiration_date "{0}", falling back to None'.format(timestamp)) class DetectableTestRunner(DiscoverRunner): diff --git a/api/views.py b/api/views.py index f28451b9..f3664265 100644 --- a/api/views.py +++ b/api/views.py @@ -242,6 +242,7 @@ class DeviceApiPicture(generics.RetrieveDestroyAPIView): queryset = Picture.objects.all() serializer_class = PictureSerializer + class DeviceApiPictureRotate(generics.RetrieveUpdateAPIView): model = Picture queryset = Picture.objects.all() diff --git a/devices/ajax.py b/devices/ajax.py index d55d25e7..05162c3f 100644 --- a/devices/ajax.py +++ b/devices/ajax.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals + import json import time import csv @@ -442,7 +443,7 @@ def post(self, request): return render(request, 'devices/searchresult.html', context) except ValueError: context = { - "wrong_id_format" : True + "wrong_id_format": True } return render(request, 'devices/searchempty.html', context) except Device.DoesNotExist: diff --git a/devices/forms.py b/devices/forms.py index 8e519851..09b4ad00 100644 --- a/devices/forms.py +++ b/devices/forms.py @@ -1,4 +1,5 @@ from __future__ import unicode_literals + import re from django import forms @@ -66,14 +67,14 @@ def get_department_options(): try: - return DEPARTMENT_OPTIONS+list(Department.objects.all().values_list("id", "name")) + return DEPARTMENT_OPTIONS + list(Department.objects.all().values_list("id", "name")) except OperationalError: return [] def get_devicegroup_options(): try: - return [('all', _('All Groups')), ]+list(Devicegroup.objects.all().values_list("id", "name")) + return [('all', _('All Groups'))] + list(Devicegroup.objects.all().values_list("id", "name")) except OperationalError: return [] @@ -184,7 +185,7 @@ def __init__(self, pk=None, *args, **kwargs): super(LendForm, self).__init__(*args, **kwargs) device = None try: - device = Device.objects.filter(pk = pk)[0] + device = Device.objects.filter(pk=pk)[0] except: pass if device: @@ -194,8 +195,6 @@ def __init__(self, pk=None, *args, **kwargs): self.fields['device'].initial = device print(self.fields['device'].initial) - - def clean_device(self): device = self.cleaned_data["device"] return device diff --git a/devices/management/commands/ldapimport.py b/devices/management/commands/ldapimport.py index c4f434dd..311829d4 100644 --- a/devices/management/commands/ldapimport.py +++ b/devices/management/commands/ldapimport.py @@ -29,7 +29,7 @@ def paged_search_ext_s(self, base, scope, filterstr='(objectClass=*)', attrlist= # Send first search request msgid = self.search_ext( *settings.LDAP_USER_SEARCH, - serverctrls=(serverctrls or [])+[req_ctrl] + serverctrls=(serverctrls or []) + [req_ctrl] ) result_pages = 0 @@ -49,7 +49,7 @@ def paged_search_ext_s(self, base, scope, filterstr='(objectClass=*)', attrlist= if pctrls[0].cookie: # Copy cookie from response control to request control req_ctrl.cookie = pctrls[0].cookie - msgid = self.search_ext(*settings.LDAP_USER_SEARCH, serverctrls=(serverctrls or [])+[req_ctrl]) + msgid = self.search_ext(*settings.LDAP_USER_SEARCH, serverctrls=(serverctrls or []) + [req_ctrl]) else: break return result_pages, all_results diff --git a/devices/models.py b/devices/models.py index c7286127..75939d8f 100644 --- a/devices/models.py +++ b/devices/models.py @@ -164,7 +164,7 @@ def get_as_dict(self): return dict def is_overdue(self): - if self.currentlending == None: + if self.currentlending is None: return False if self.currentlending.duedate < datetime.date.today(): return True @@ -207,10 +207,12 @@ class Meta: verbose_name_plural = _('Information') -reversion.register(Device, follow=["typeattributevalue_set", ], exclude= -["archived", "currentlending", "inventoried", "bookmarks", "trashed"], ignore_duplicates=True) +reversion.register(Device, follow=["typeattributevalue_set", ], exclude=[ + "archived", "currentlending", "inventoried", "bookmarks", "trashed", +], ignore_duplicates=True) reversion.register(TypeAttributeValue) + @reversion.register(ignore_duplicates=True) class Lending(models.Model): owner = models.ForeignKey(Lageruser, verbose_name=_("Lent to"), on_delete=models.SET_NULL, null=True) diff --git a/devices/perms.py b/devices/perms.py index 92714f5e..64f4ba80 100644 --- a/devices/perms.py +++ b/devices/perms.py @@ -1,11 +1,13 @@ from __future__ import unicode_literals -__author__ = 'viirus' -from permission.logics import PermissionLogic -from permission.conf import settings from django.contrib import auth from django.core.exceptions import PermissionDenied +from permission.conf import settings +from permission.logics import PermissionLogic + +__author__ = 'viirus' + class DevicePermissionLogic(PermissionLogic): def __init__(self, diff --git a/devices/templatetags/devicetags.py b/devices/templatetags/devicetags.py index 30a2a748..435dc259 100644 --- a/devices/templatetags/devicetags.py +++ b/devices/templatetags/devicetags.py @@ -1,12 +1,14 @@ from __future__ import unicode_literals -import re + import os +import re -import six from django.template import Library from django.utils.safestring import mark_safe from django.forms import CheckboxInput +import six + from devices.models import Bookmark register = Library() diff --git a/devices/tests.py b/devices/tests.py index f8ef85a3..54f8f287 100644 --- a/devices/tests.py +++ b/devices/tests.py @@ -25,16 +25,22 @@ def setUp(self): def test_device_creation(self): '''method for testing the functionality of creating a new device''' device = mommy.make(Device) - lending_past = mommy.make(Lending, duedate = (datetime.today() - timedelta(days = 1)).date()) - lending_future = mommy.make(Lending, duedate = (datetime.today() + timedelta(days = 1)).date()) + lending_past = mommy.make(Lending, duedate=(datetime.today() - timedelta(days=1)).date()) + lending_future = mommy.make(Lending, duedate=(datetime.today() + timedelta(days=1)).date()) self.assertTrue(isinstance(device, Device)) self.assertEqual(six.text_type(device), device.name) self.assertEqual(device.get_absolute_url(), reverse('device-detail', kwargs={'pk': device.pk})) self.assertEqual(device.get_edit_url(), reverse('device-edit', kwargs={'pk': device.pk})) - self.assertEqual(device.get_as_dict(), {"name": device.name, "description": device.description, "manufacturer": device.manufacturer, "devicetype" : device.devicetype, "room" : device.room}) + self.assertEqual(device.get_as_dict(), { + "name": device.name, + "description": device.description, + "manufacturer": device.manufacturer, + "devicetype": device.devicetype, + "room": device.room, + }) self.assertFalse(device.is_overdue()) - self.assertTrue(mommy.make(Device, currentlending = lending_past).is_overdue()) - self.assertFalse(mommy.make(Device, currentlending = lending_future).is_overdue()) + self.assertTrue(mommy.make(Device, currentlending=lending_past).is_overdue()) + self.assertFalse(mommy.make(Device, currentlending=lending_future).is_overdue()) def test_device_list(self): mommy.make(Device, _quantity=40) @@ -58,7 +64,7 @@ def test_device_detail(self): self.assertEqual(resp.status_code, 200) def test_device_add(self): - device = mommy.make(Device, name = "used") + device = mommy.make(Device, name="used") url = reverse("device-add") resp = self.client.get(url) self.assertEqual(resp.status_code, 200) @@ -67,7 +73,7 @@ def test_device_add(self): data['uses'] = device.id data['name'] = "uses" resp = self.client.post(url, data) - device = Device.objects.filter(name = 'used')[0] + device = Device.objects.filter(name='used')[0] self.assertEqual(device.used_in.name, 'uses') def test_device_edit(self): @@ -122,17 +128,17 @@ def test_device_trash(self): def test_device_trash_sets_child_used_in_to_none(self): device = mommy.make(Device) - used_device = mommy.make(Device, used_in = device) + used_device = mommy.make(Device, used_in=device) trashurl = reverse('device-trash', kwargs={'pk': device.pk}) self.client.post(trashurl) - used_device = Device.objects.filter(pk = used_device.pk)[0] + used_device = Device.objects.filter(pk=used_device.pk)[0] self.assertIsNone(used_device.used_in) def test_device_trash_sets_self_used_in_to_none(self): device = mommy.make(Device, _fill_optional=['used_in']) - trashurl = reverse("device-trash", kwargs={'pk' : device.pk}) + trashurl = reverse("device-trash", kwargs={'pk': device.pk}) self.client.post(trashurl) - device = Device.objects.filter(pk = device.pk)[0] + device = Device.objects.filter(pk=device.pk)[0] self.assertIsNone(device.used_in) def test_device_trash_returns_lending(self): @@ -197,13 +203,13 @@ def test_device_ipaddress(self): def test_device_lending_list(self): lending = mommy.make(Lending) - device = mommy.make(Device, currentlending = lending) - url = reverse("device-lending-list", kwargs = {"pk": device.pk}) + device = mommy.make(Device, currentlending=lending) + url = reverse("device-lending-list", kwargs={"pk": device.pk}) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) def test_device_lend(self): - device = mommy.make(Device, archived = None) + device = mommy.make(Device, archived=None) room = mommy.make(Room) room.save() lending = mommy.make(Lending) @@ -223,13 +229,13 @@ def test_device_return(self): device = devices[0] user = mommy.make(Lageruser) - lending = mommy.make(Lending, owner = user) - url = reverse("device-return", kwargs = {"lending": lending.id}) + lending = mommy.make(Lending, owner=user) + url = reverse("device-return", kwargs={"lending": lending.id}) resp = self.client.post(url) self.assertEqual(resp.status_code, 302) - lending2 = mommy.make(Lending, device = device) - url = reverse("device-return", kwargs = {"lending": lending2.id}) + lending2 = mommy.make(Lending, device=device) + url = reverse("device-return", kwargs={"lending": lending2.id}) resp = self.client.post(url) self.assertEqual(resp.status_code, 302) @@ -298,7 +304,7 @@ def setUp(self): def test_room_creation(self): room = mommy.make(Room) building = mommy.make(Building) - room_in_building = mommy.make(Room, building = building) + room_in_building = mommy.make(Room, building=building) self.assertTrue(isinstance(room, Room)) self.assertEqual(six.text_type(room), room.name) self.assertTrue(isinstance(room_in_building, Room)) @@ -413,7 +419,12 @@ def test_template_creation(self): self.assertTrue(isinstance(template, Template)) self.assertEqual(six.text_type(template), template.templatename) self.assertEqual(template.get_absolute_url(), reverse('device-list')) - self.assertEqual(template.get_as_dict(), {'name': template.name, 'description': template.description, 'manufacturer' : template.manufacturer, 'devicetype' : template.devicetype }) + self.assertEqual(template.get_as_dict(), { + 'name': template.name, + 'description': template.description, + 'manufacturer': template.manufacturer, + 'devicetype': template.devicetype, + }) def test_template_list(self): mommy.make(Template, _quantity=40) @@ -459,22 +470,24 @@ def test_note_creation(self): self.assertTrue(isinstance(note, Note)) self.assertEqual(note.get_absolute_url(), reverse('device-detail', kwargs={'pk': note.device.pk})) + class DeviceInformationTypeTests(TestCase): def setUp(self): self.client = Client() Lageruser.objects.create_superuser('test', 'test@test.com', 'test') - self.client.login(username = 'test', password = 'test') + self.client.login(username='test', password='test') def test_device_information_type_creation(self): information = mommy.make(DeviceInformationType) self.assertTrue(isinstance(information, DeviceInformationType)) self.assertEqual(six.text_type(information), information.humanname) + class DeviceInformationTests(TestCase): def setUp(self): self.client = Client() Lageruser.objects.create_superuser('test', 'test@test.com', 'test') - self.client.login(username = 'test', password = 'test') + self.client.login(username='test', password='test') def test_device_information_creation(self): device_information = mommy.make(DeviceInformation) @@ -489,6 +502,6 @@ def setUp(self): def test_picture_creation(self): device = mommy.make(Device) - picture = mommy.make(Picture, device = device) + picture = mommy.make(Picture, device=device) self.assertTrue(isinstance(picture, Picture)) - self.assertEqual(picture.get_absolute_url(), reverse('device-detail', kwargs={'pk': picture.device.pk}) ) + self.assertEqual(picture.get_absolute_url(), reverse('device-detail', kwargs={'pk': picture.device.pk})) diff --git a/devices/views.py b/devices/views.py index 8db552bb..74ce4bfb 100644 --- a/devices/views.py +++ b/devices/views.py @@ -1,5 +1,6 @@ # coding: utf-8 from __future__ import unicode_literals + import datetime import time import csv @@ -40,7 +41,7 @@ @permission_required('devices.read_device', raise_exception=True) -class DeviceList(PaginationMixin, ListView): +class DeviceList(PaginationMixin, ListView): context_object_name = 'device_list' template_name = 'devices/device_list.html' viewfilter = None @@ -49,7 +50,7 @@ class DeviceList(PaginationMixin, ListView): def post(self, request): '''post-requesting the detail-view of device by id''' if 'deviceid' in request.POST: - return HttpResponseRedirect(reverse('device-detail', kwargs={'pk':request.POST['deviceid']})) + return HttpResponseRedirect(reverse('device-detail', kwargs={'pk': request.POST['deviceid']})) else: return HttpResponseRedirect(reverse('device-list')) @@ -87,7 +88,7 @@ def get_queryset(self): devices = Device.active() self.departmentfilter = self.kwargs.get("department", "all") - #if user has departments: set departments as filter + # if user has departments: set departments as filter if hasattr(self.request.user, 'departments'): if self.request.user.departments.count() > 0: self.departmentfilter = self.kwargs.get("department", "my") @@ -191,9 +192,9 @@ def post(self, request): devices = self.request.user.bookmarks.all() if request.POST["departmentfilter"] == "my": - devices = devices.filter(department__in=request.user.departments.all()) # does this work? + devices = devices.filter(department__in=request.user.departments.all()) # does this work? elif request.POST["departmentfilter"].isdigit(): - devices = devices.filter(department__in=Department.objects.filter(id = int(request.POST["departmentfilter"]))) + devices = devices.filter(department__in=Department.objects.filter(id=int(request.POST["departmentfilter"]))) elif request.POST["departmentfilter"] == "all": pass @@ -206,7 +207,6 @@ def post(self, request): return response - @permission_required('devices.read_device', raise_exception=True) class DeviceDetail(DetailView): # get related data to chosen device @@ -230,8 +230,7 @@ def get_object(self, queryset=None): def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super(DeviceDetail, self).get_context_data(**kwargs) - context['usedset'] = Device.objects.filter(used_in = self.object) - + context['usedset'] = Device.objects.filter(used_in=self.object) # Add in a QuerySet of all the books @@ -254,7 +253,6 @@ def get_context_data(self, **kwargs): context["mail_list"] = MailHistory.objects.filter(device=context["device"])\ .select_related("sent_by").order_by("-pk")[:10] - context["today"] = datetime.datetime.utcnow().replace(tzinfo=utc) context["weekago"] = context["today"] - datetime.timedelta(days=7) context["attributevalue_list"] = TypeAttributeValue.objects.filter(device=context["device"]) @@ -267,7 +265,7 @@ def get_context_data(self, **kwargs): mailinitial["owner"] = currentowner mailinitial["emailrecipients"] = ("u" + str(currentowner.id), currentowner.username) try: - mailinitial["mailtemplate"] = MailTemplate.objects.get(usage="reminder", department = self.request.user.main_department, ) + mailinitial["mailtemplate"] = MailTemplate.objects.get(usage="reminder", department=self.request.user.main_department, ) mailinitial["emailsubject"] = mailinitial["mailtemplate"].subject mailinitial["emailbody"] = mailinitial["mailtemplate"].body except: @@ -309,7 +307,8 @@ def get_context_data(self, **kwargs): return context -#### to do + +# to do @permission_required('devices.change_device', raise_exception=True) class DeviceIpAddressRemove(View): template_name = 'devices/unassign_ipaddress.html' @@ -499,7 +498,7 @@ def form_valid(self, form): if "uses" in form.changed_data: for element in form.cleaned_data["uses"]: - used_device = Device.objects.filter(id = element)[0] + used_device = Device.objects.filter(id=element)[0] used_device.used_in = self.object used_device.save() @@ -635,17 +634,15 @@ def get_context_data(self, **kwargs): (reverse("device-list"), _("Devices")), ("", _("Lend"))] if self.kwargs and 'pk' in self.kwargs: - device = get_object_or_404(Device, pk = self.kwargs['pk']) + device = get_object_or_404(Device, pk=self.kwargs['pk']) context["breadcrumbs"] = context["breadcrumbs"][:-1] + [(reverse("device-detail", kwargs={"pk": device.pk}), device.name)] + context['breadcrumbs'][-1:] return context - def get_form_kwargs(self): kwargs = super(DeviceLend, self).get_form_kwargs() kwargs.update(self.kwargs) return kwargs - def form_valid(self, form): device = None templates = [] diff --git a/devicetypes/ajax.py b/devicetypes/ajax.py index 49cbca99..04ef5ec8 100644 --- a/devicetypes/ajax.py +++ b/devicetypes/ajax.py @@ -26,4 +26,4 @@ def post(self, request): return HttpResponse(json.dumps(data), content_type='application/json') - return HttpResponse("") \ No newline at end of file + return HttpResponse("") diff --git a/devicetypes/forms.py b/devicetypes/forms.py index ee210047..eaf870af 100644 --- a/devicetypes/forms.py +++ b/devicetypes/forms.py @@ -1,4 +1,5 @@ from __future__ import unicode_literals + from django import forms from devicetypes.models import Type diff --git a/devicetypes/tests.py b/devicetypes/tests.py index 02c1193e..16a0f008 100644 --- a/devicetypes/tests.py +++ b/devicetypes/tests.py @@ -90,7 +90,6 @@ def test_type_delete(self): devicetypes = Type.objects.all() devicetype = devicetypes[0] - # testing successful loading of devicetype-page after deletion (statuscode 2xx) url = reverse("type-edit", kwargs={"pk": devicetype.pk}) resp = self.client.get(url) diff --git a/history/tests.py b/history/tests.py index db9d79f7..76ce7dbf 100644 --- a/history/tests.py +++ b/history/tests.py @@ -1,9 +1,10 @@ from __future__ import unicode_literals from django.test.client import Client +from django.core.urlresolvers import reverse from django.test import TestCase + from model_mommy import mommy -from django.core.urlresolvers import reverse from devices.models import Device from users.models import Lageruser @@ -25,4 +26,4 @@ def test_history_detail(self): url = reverse("history-detail", kwargs={"pk": 1}) resp = self.client.get(url) - self.assertEqual(resp.status_code, 200) \ No newline at end of file + self.assertEqual(resp.status_code, 200) diff --git a/history/views.py b/history/views.py index 4b153f28..238fada6 100644 --- a/history/views.py +++ b/history/views.py @@ -1,4 +1,5 @@ from __future__ import unicode_literals + from django.contrib import messages from django.http import HttpResponseRedirect from django.views.generic import ListView, UpdateView diff --git a/mail/ajax.py b/mail/ajax.py index 66d369fe..5f0ef034 100644 --- a/mail/ajax.py +++ b/mail/ajax.py @@ -1,10 +1,12 @@ from __future__ import unicode_literals + import json -import six from django.views.generic.base import View from django.http import HttpResponse +import six + from mail.models import usages from mail.models import MailTemplate @@ -14,5 +16,5 @@ def post(self, request, *args, **kwargs): department = request.POST["department"] used = MailTemplate.objects.values_list('usage', flat=True).filter(department=department) valid = {str(x): six.text_type(y) for x, y in usages.items() if not any(z in x for z in used)} - valid.update({'': '--------'}) + valid.update({'': '--------'}) return(HttpResponse(json.dumps(valid), content_type="application/json")) diff --git a/mail/forms.py b/mail/forms.py index 7548a5f0..2289ff12 100644 --- a/mail/forms.py +++ b/mail/forms.py @@ -25,14 +25,14 @@ class MailTemplateUpdateForm(MailTemplateForm): def __init__(self, *args, **kwargs): super(MailTemplateForm, self).__init__(*args, **kwargs) if self.instance.department: - #a query set + # a query set used_db = MailTemplate.objects.values_list('usage', flat=True).filter(department=kwargs["instance"].department) used = [] for x in used_db: if x is not None: - #the current templates' usage can't be excluded although it is in the used_db queryset + # the current templates' usage can't be excluded although it is in the used_db queryset if not self.instance.usage == x: used.append(x) - #all usages that are not in used + # all usages that are not in used valid = [x for x in self.fields['usage'].choices if not any(y in x for y in used)] self.fields['usage'].choices = valid diff --git a/mail/tests.py b/mail/tests.py index 73f8167f..3b1cc90f 100644 --- a/mail/tests.py +++ b/mail/tests.py @@ -1,5 +1,7 @@ from __future__ import unicode_literals +import unittest + from django.test.client import Client from django.test import TestCase from django.core.urlresolvers import reverse @@ -25,25 +27,26 @@ def test_template_creation(self): self.assertEqual(template.get_edit_url(), reverse('mail-edit', kwargs={'pk': template.pk})) -# first figuring out strange behaviour of content_object -# class TestMailTemplateRecipient(TestCase): -# def setUp(self): -# self.client = Client() -# myadmin = Lageruser.objects.create_superuser("test", "test@test.com", "test") -# self.client.login(username = "test", password = "test") -# -# def test_template_creation(self): -# con = mommy.make(ContentType) -# rec = mommy.make(MailTemplateRecipient, content_type = con) -# self.assertEqual(six.text_type(rec), unicode(rec.content_type.name + ": " + six.text_type(rec.content_object))) - -# find out why url does not exist -# class TestMailHistory(TestCase): -# def setUp(self): -# self.client = Client() -# myadmin = Lageruser.objects.create_superuser("test", "test@test.com", "test") -# self.client.login(username = "test", password = "test") -# -# def test_mail_history_creation(self): -# hist = mommy.make(MailHistory) -# self.assertEqual(hist.get_absolute_url(), reverse('mailhistory-detail', kwargs={'pk': hist.pk}) ) +class TestMailTemplateRecipient(TestCase): + def setUp(self): + self.client = Client() + Lageruser.objects.create_superuser("test", "test@test.com", "test") + self.client.login(username="test", password="test") + + @unittest.skip("first figuring out strange behaviour of content_object") + def test_template_creation(self): + con = mommy.make(ContentType) + rec = mommy.make(MailTemplateRecipient, content_type=con) + self.assertEqual(six.text_type(rec), six.text_type(rec.content_type.name + ": " + six.text_type(rec.content_object))) + + +class TestMailHistory(TestCase): + def setUp(self): + self.client = Client() + Lageruser.objects.create_superuser("test", "test@test.com", "test") + self.client.login(username="test", password="test") + + @unittest.skip("find out why url does not exist") + def test_mail_history_creation(self): + hist = mommy.make(MailHistory) + self.assertEqual(hist.get_absolute_url(), reverse('mailhistory-detail', kwargs={'pk': hist.pk})) diff --git a/main/ajax.py b/main/ajax.py index a6e78ba7..72ee986f 100644 --- a/main/ajax.py +++ b/main/ajax.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals + import json from django.db.models import Max diff --git a/network/models.py b/network/models.py index a17f15b0..ff637cf9 100644 --- a/network/models.py +++ b/network/models.py @@ -4,12 +4,12 @@ from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse -from devices.models import Device -from users.models import Lageruser, Department - import six from reversion import revisions as reversion +from devices.models import Device +from users.models import Department, Lageruser + @six.python_2_unicode_compatible class IpAddress(models.Model): diff --git a/network/perms.py b/network/perms.py index 08a6f93c..44192bea 100644 --- a/network/perms.py +++ b/network/perms.py @@ -1,9 +1,10 @@ from __future__ import unicode_literals -__author__ = 'viirus' from permission.logics import PermissionLogic from permission.conf import settings +__author__ = 'viirus' + class IPAddressPermissionLogic(PermissionLogic): def __init__(self, diff --git a/network/tests.py b/network/tests.py index 3ade8216..ed88b471 100644 --- a/network/tests.py +++ b/network/tests.py @@ -1,9 +1,10 @@ from __future__ import unicode_literals from django.test.client import Client +from django.core.urlresolvers import reverse from django.test import TestCase + from model_mommy import mommy -from django.core.urlresolvers import reverse from users.models import Lageruser from network.models import IpAddress diff --git a/users/forms.py b/users/forms.py index 2a45a240..880322c1 100644 --- a/users/forms.py +++ b/users/forms.py @@ -1,4 +1,5 @@ from __future__ import unicode_literals + from django import forms from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext diff --git a/users/models.py b/users/models.py index 9a3c10c1..1870f01b 100644 --- a/users/models.py +++ b/users/models.py @@ -5,7 +5,6 @@ from datetime import date import logging -import pytz from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ @@ -13,9 +12,11 @@ from django.conf import settings from django.core.urlresolvers import reverse from django.dispatch import receiver -from django_auth_ldap.backend import populate_user +import pytz import six +from django_auth_ldap.backend import populate_user + from Lagerregal import utils @@ -103,6 +104,7 @@ def populate_ldap_user(sender, signal, user, ldap_user, **kwargs): user.save() + @six.python_2_unicode_compatible class Department(models.Model): name = models.CharField(max_length=40, unique=True) @@ -118,6 +120,7 @@ class Meta: ("add_department_user", _("Can add a User to a Department")), ("delete_department_user", _("Can remove a User from a Department")),) + class DepartmentUser(models.Model): user = models.ForeignKey(Lageruser) department = models.ForeignKey(Department) diff --git a/users/perms.py b/users/perms.py index 3b05662e..f3566b13 100644 --- a/users/perms.py +++ b/users/perms.py @@ -1,9 +1,10 @@ from __future__ import unicode_literals -__author__ = 'viirus' from permission.logics import PermissionLogic from permission.conf import settings +__author__ = 'viirus' + class DepartmentPermissionLogic(PermissionLogic): def __init__(self, diff --git a/users/views.py b/users/views.py index 4ba2d4a7..c86cedd5 100644 --- a/users/views.py +++ b/users/views.py @@ -21,8 +21,8 @@ from django.core.exceptions import PermissionDenied from django.shortcuts import get_object_or_404 from django.db.models import Q -from reversion.models import Version from permission.decorators import permission_required +from reversion.models import Version from users.models import Lageruser, Department, DepartmentUser from devices.models import Lending From ed74790caee8bd72d81a33c198c9469752a5cec6 Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Tue, 19 Jun 2018 17:53:14 +0200 Subject: [PATCH 08/10] run linter on travis --- .travis.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index d7a97a7c..3852a7f1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,9 +4,12 @@ python: # command to install dependencies install: - "pip install -r dependencies.txt" + - "pip install flake8" - npm install -g casperjs # create the database - "cp Lagerregal/template_development.py Lagerregal/settings.py" - "./manage.py migrate" # command to run tests -script: "./manage.py test" +script: + - flake8 --config=setup.cfg + - "./manage.py test" From 057d262c736fb132b483f38d2fab2b8fcb4ef695 Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Wed, 20 Jun 2018 09:15:09 +0200 Subject: [PATCH 09/10] Ignore yet another error category --- setup.cfg | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/setup.cfg b/setup.cfg index f5c9f360..dcb02dd8 100644 --- a/setup.cfg +++ b/setup.cfg @@ -6,8 +6,9 @@ exclude= settings.py, template_*.py, template, + .env, # TODO fix some of these -ignore= E124, E126, E127, E128, E131, E501, E722, F403, F405, F999, W503 +ignore= E124, E126, E127, E128, E131, E501, E722, E741, F403, F405, F999, W503 [isort] known_django=django From 4fbf9aae2a0a28f4ad87cbbdac87201e9b18ce14 Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Wed, 20 Jun 2018 13:42:05 +0200 Subject: [PATCH 10/10] use lists instead of dicts for choices (see #222) --- mail/ajax.py | 4 ++-- mail/models.py | 18 +++++++++--------- main/ajax.py | 10 +++++----- main/models.py | 26 +++++++++++++------------- main/views.py | 4 ++-- 5 files changed, 31 insertions(+), 31 deletions(-) diff --git a/mail/ajax.py b/mail/ajax.py index 5f0ef034..2b9a0f84 100644 --- a/mail/ajax.py +++ b/mail/ajax.py @@ -7,7 +7,7 @@ import six -from mail.models import usages +from mail.models import USAGES from mail.models import MailTemplate @@ -15,6 +15,6 @@ class LoadChoices(View): def post(self, request, *args, **kwargs): department = request.POST["department"] used = MailTemplate.objects.values_list('usage', flat=True).filter(department=department) - valid = {str(x): six.text_type(y) for x, y in usages.items() if not any(z in x for z in used)} + valid = {str(x): six.text_type(y) for x, y in USAGES if not any(z in x for z in used)} valid.update({'': '--------'}) return(HttpResponse(json.dumps(valid), content_type="application/json")) diff --git a/mail/models.py b/mail/models.py index c6f86b8a..c6707ff8 100644 --- a/mail/models.py +++ b/mail/models.py @@ -13,14 +13,14 @@ from users.models import Lageruser, Department -usages = { - "new": _("New Device is created"), - "room": _("Room is changed"), - "owner": _("person currently lending is changed"), - "reminder": _("Reminder that device is still owned"), - "overdue": _("Reminder that device is overdue"), - "trashed": _("Device is trashed") -} +USAGES = [ + ("new", _("New Device is created")), + ("room", _("Room is changed")), + ("owner", _("person currently lending is changed")), + ("reminder", _("Reminder that device is still owned")), + ("overdue", _("Reminder that device is overdue")), + ("trashed", _("Device is trashed")), +] @six.python_2_unicode_compatible @@ -29,7 +29,7 @@ class MailTemplate(models.Model): subject = models.CharField(_('Subject'), max_length=500) body = models.CharField(_('Body'), max_length=10000) department = models.ForeignKey(Department, null=True) - usage = models.CharField(_('Usage'), choices=list(usages.items()), null=True, blank=True, max_length=200) + usage = models.CharField(_('Usage'), choices=USAGES, null=True, blank=True, max_length=200) def __str__(self): return self.name diff --git a/main/ajax.py b/main/ajax.py index 72ee986f..fdb214d7 100644 --- a/main/ajax.py +++ b/main/ajax.py @@ -8,14 +8,14 @@ from django.views.generic.base import View from django.http import HttpResponse -from main.models import DashboardWidget, widgets +from main.models import DashboardWidget, WIDGETS from main.views import get_widget_data class WidgetAdd(View): def post(self, request): widgetname = request.POST["widgetname"] - if widgetname in widgets: + if widgetname in dict(WIDGETS): userwidgets = DashboardWidget.objects.filter(user=request.user) if len(userwidgets.filter(widgetname=widgetname)) != 0: return HttpResponse("") @@ -37,7 +37,7 @@ def post(self, request): class WidgetRemove(View): def post(self, request): widgetname = request.POST["widgetname"] - if widgetname in widgets: + if widgetname in dict(WIDGETS): DashboardWidget.objects.get(user=request.user, widgetname=widgetname).delete() return HttpResponse("") else: @@ -47,7 +47,7 @@ def post(self, request): class WidgetToggle(View): def post(self, request): widgetname = request.POST["widgetname"] - if widgetname in widgets: + if widgetname in dict(WIDGETS): w = DashboardWidget.objects.get(user=request.user, widgetname=widgetname) w.minimized = not w.minimized w.save() @@ -61,7 +61,7 @@ def post(self, request): userwidgets = json.loads(request.POST["widgets"]) for widgetname, widgetattr in userwidgets.items(): - if widgetname in widgets: + if widgetname in dict(WIDGETS): w = DashboardWidget.objects.get(user=request.user, widgetname=widgetname) if w.index != widgetattr["index"] or w.column != widgetattr["column"]: w.index = widgetattr["index"] diff --git a/main/models.py b/main/models.py index 98ffd1c7..60787ba3 100644 --- a/main/models.py +++ b/main/models.py @@ -7,18 +7,18 @@ from users.models import Lageruser -widgets = { - "edithistory": _("Edit history"), - "newestdevices": _("Newest devices"), - "overdue": _("Overdue devices"), - "statistics": _("Statistics"), - "groups": _("Groups"), - "sections": _("Sections"), - "recentlendings": _("Recent lendings"), - "shorttermdevices": _("Devices for short term lending"), - "bookmarks": _("Bookmarked Devices"), - "returnsoon": _("Devices, that are due soon") -} +WIDGETS = [ + ("edithistory", _("Edit history")), + ("newestdevices", _("Newest devices")), + ("overdue", _("Overdue devices")), + ("statistics", _("Statistics")), + ("groups", _("Groups")), + ("sections", _("Sections")), + ("recentlendings", _("Recent lendings")), + ("shorttermdevices", _("Devices for short term lending")), + ("bookmarks", _("Bookmarked Devices")), + ("returnsoon", _("Devices, that are due soon")), +] def get_progresscolor(percent): @@ -33,7 +33,7 @@ def get_progresscolor(percent): class DashboardWidget(models.Model): column = models.CharField(max_length=1, choices=[("l", "left"), ("r", "right")]) index = models.IntegerField() - widgetname = models.CharField(max_length=200, choices=list(widgets.items())) + widgetname = models.CharField(max_length=200, choices=WIDGETS) user = models.ForeignKey(Lageruser) minimized = models.BooleanField(default=False) diff --git a/main/views.py b/main/views.py index 0ef8e688..af47b6d0 100644 --- a/main/views.py +++ b/main/views.py @@ -10,7 +10,7 @@ from network.models import * from devicegroups.models import Devicegroup from locations.models import Section -from main.models import DashboardWidget, widgets, get_progresscolor +from main.models import DashboardWidget, WIDGETS, get_progresscolor from Lagerregal.utils import PaginationMixin from devices.forms import LendForm @@ -93,7 +93,7 @@ def get_context_data(self, **kwargs): ).order_by("index") context["widgets_right"] = DashboardWidget.objects.filter(user=self.request.user, column="r" ).order_by("index") - userwidget_list = dict(widgets) + userwidget_list = dict(WIDGETS) widgetlist = [x[0] for x in DashboardWidget.objects.filter(user=self.request.user ).values_list("widgetname")] context.update(get_widget_data(self.request.user, widgetlist, self.request.user.departments.all()))