class Car(models.Model): state_choice = ( ('AL', 'Alabama'), ('AK', 'Alaska'), ('AZ', 'Arizona'), ('AR', 'Arkansas'), ('CA', 'California'), ('CO', 'Colorado'), ('CT', 'Connecticut'), ('DE', 'Delaware'), ('DC', 'District Of Columbia'), ('FL', 'Florida'), ('GA', 'Georgia'), ('HI', 'Hawaii'), ('ID', 'Idaho'), ('IL', 'Illinois'), ('IN', 'Indiana'), ('IA', 'Iowa'), ('KS', 'Kansas'), ('KY', 'Kentucky'), ('LA', 'Louisiana'), ('ME', 'Maine'), ('MD', 'Maryland'), ('MA', 'Massachusetts'), ('MI', 'Michigan'), ('MN', 'Minnesota'), ('MS', 'Mississippi'), ('MO', 'Missouri'), ('MT', 'Montana'), ('NE', 'Nebraska'), ('NV', 'Nevada'), ('NH', 'New Hampshire'), ('NJ', 'New Jersey'), ('NM', 'New Mexico'), ('NY', 'New York'), ('NC', 'North Carolina'), ('ND', 'North Dakota'), ('OH', 'Ohio'), ('OK', 'Oklahoma'), ('OR', 'Oregon'), ('PA', 'Pennsylvania'), ('RI', 'Rhode Island'), ('SC', 'South Carolina'), ('SD', 'South Dakota'), ('TN', 'Tennessee'), ('TX', 'Texas'), ('UT', 'Utah'), ('VT', 'Vermont'), ('VA', 'Virginia'), ('WA', 'Washington'), ('WV', 'West Virginia'), ('WI', 'Wisconsin'), ('WY', 'Wyoming'), ) year_choice = [] for r in range(2000, (datetime.now().year + 1)): year_choice.append((r, r)) features_choices = ( ('Cruise Control', 'Cruise Control'), ('Audio Interface', 'Audio Interface'), ('Airbags', 'Airbags'), ('Air Conditioning', 'Air Conditioning'), ('Seat Heating', 'Seat Heating'), ('Alarm System', 'Alarm System'), ('ParkAssist', 'ParkAssist'), ('Power Steering', 'Power Steering'), ('Reversing Camera', 'Reversing Camera'), ('Direct Fuel Injection', 'Direct Fuel Injection'), ('Auto Start/Stop', 'Auto Start/Stop'), ('Wind Deflector', 'Wind Deflector'), ('Bluetooth Handset', 'Bluetooth Handset'), ) door_choices = ( ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'), ) car_title = models.CharField(max_length=255) state = models.CharField(choices=state_choice, max_length=100) city = models.CharField(max_length=100) color = models.CharField(max_length=100) model = models.CharField(max_length=100) year = models.IntegerField(('year'), choices=year_choice) condition = models.CharField(max_length=100) price = models.IntegerField() description = RichTextField() car_photo = models.ImageField(upload_to='photos/%y/%m/%d/') car_photo_1 = models.ImageField(upload_to='photos/%y/%m/%d/', blank=True) car_photo_2 = models.ImageField(upload_to='photos/%y/%m/%d/', blank=True) car_photo_3 = models.ImageField(upload_to='photos/%y/%m/%d/', blank=True) car_photo_4 = models.ImageField(upload_to='photos/%y/%m/%d/', blank=True) features = MultiSelectField(choices=features_choices) body_style = models.CharField(max_length=100) engine = models.CharField(max_length=100) transmission = models.CharField(max_length=100) interior = models.CharField(max_length=100) miles = models.IntegerField() doors = models.CharField(choices=door_choices, max_length=10) passengers = models.IntegerField() vin_no = models.CharField(max_length=100) milage = models.IntegerField() fuel_type = models.CharField(max_length=50) no_of_owners = models.CharField(max_length=100) is_featured = models.BooleanField(default=False) created_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.car_title
class Customer(models.Model): """ 客户表 """ qq = models.CharField('QQ', max_length=64, unique=True, help_text='QQ号必须唯一') qq_name = models.CharField('QQ昵称', max_length=64, blank=True, null=True, default='') name = models.CharField('姓名', max_length=32, blank=True, null=True, help_text='学员报名后,请改为真实姓名', default='') sex_type = (('male', '男'), ('female', '女')) sex = models.CharField("性别", choices=sex_type, max_length=16, default='male', blank=True, null=True) birthday = models.DateField('出生日期', default=None, help_text="格式yyyy-mm-dd", blank=True, null=True) phone = models.BigIntegerField('手机号', blank=True, null=True) source = models.CharField('客户来源', max_length=64, choices=source_type, default='qq') introduce_from = models.ForeignKey('Customer', verbose_name="转介绍自学员", blank=True, null=True, on_delete=models.CASCADE) course = MultiSelectField("咨询课程", choices=course_choices) class_type = models.CharField("班级类型", max_length=64, choices=class_type_choices, default='fulltime') customer_note = models.TextField( "客户备注", blank=True, null=True, ) status = models.CharField("状态", choices=enroll_status_choices, max_length=64, default="unregistered", help_text="选择客户此时的状态") date = models.DateTimeField("咨询日期", auto_now_add=True) last_consult_date = models.DateField("最后跟进日期", auto_now_add=True) next_date = models.DateField("预计再次跟进时间", blank=True, null=True) consultant = models.ForeignKey('UserInfo', verbose_name="销售", related_name='customers', blank=True, null=True, on_delete=models.CASCADE) class_list = models.ManyToManyField('ClassList', verbose_name="已报班级") deal_date = models.DateField('报名日期', blank=True, null=True) def __str__(self): return "qq:{},姓名:{}".format(self.qq, self.name) def get_classlist(self): """获取班级信息""" cls_list = [] for cls in self.class_list.all(): cls_list.append(str(cls)) return ','.join(cls_list) def get_status_color_show(self): """返回不同状态不同颜色""" status_color = { 'unregistered': '#FF4500', 'signed': '#00FF00', 'studying': '#00FFFF', 'paid_in_full': '#0000FF', } return mark_safe( '<span style="background-color:#E5E5E5;color:%s">%s</sapn>' % (status_color[self.status], self.get_status_display()))
class Product(models.Model): STAGES = ProductionStages.get_stages_choices() # STAGES = ( # ('MT', 'Montagem'), # ('PT', 'Pintura'), # ('CP', 'Carpintaria'), # ) ref_code = models.CharField(max_length=200, unique=True) name = models.CharField(max_length=200) color = models.CharField(max_length=20, default='raw') size = models.CharField(max_length=20) final = models.BooleanField(default=False) stages = MultiSelectField(choices=STAGES, default=[STAGES[0][0]]) components = models.ManyToManyField('self', through='Quantity', symmetrical=False, blank=True) stock = models.IntegerField(default=0) def __str__(self): return str(self.ref_code ) + ":" + self.name + ":" + self.color + ":" + self.size def get_components(self): return Quantity.objects.filter(product=self) def get_components_from_stage(self, stage): components_and_quantities_from_stage = [] for component_and_quantity in self.get_components_all(): product = component_and_quantity[0] quantity = component_and_quantity[1] if str(product.get_stages()[0]) == stage: components_and_quantities_from_stage.append( [product, quantity]) return components_and_quantities_from_stage def get_components_all(self): return self._get_components() def _get_components(self, multiplier=1): components_and_quantities = [] for component in self.get_components(): product = component.component quantity = component.quantity * multiplier components_and_quantities.append([product, quantity]) components_and_quantities.extend(product._get_components(quantity)) return components_and_quantities def add_component(self, component, quantity): try: Quantity.objects.get(product=self, component=component) return except ObjectDoesNotExist: new_component = Quantity.objects.create(product=self, component=component, quantity=quantity) new_component.save() def get_stages(self): ordered_stages = [] for stage in self.STAGES: if stage[0] in self.stages: ordered_stages.append(stage[0]) return ordered_stages def get_main_stage(self): return self.get_stages()[0]
class _AccessDelegation(GenericModel, UnitEditableModel): unit = FalseFK('units.models.Unit') access = MultiSelectField(choices=_Role.ACCESS_CHOICES, blank=True, null=True) valid_for_sub_units = models.BooleanField( _(u'Valide pour les sous-unités'), default=False, help_text= _(u'Si sélectionné, les accès supplémentaires dans l\'unité courante seront aussi valides dans les sous-unités' )) user = models.ForeignKey( TruffeUser, blank=True, null=True, help_text= _(u'(Optionnel !) L\'utilisateur concerné. L\'utilisateur doit disposer d\'une accréditation dans l\'unité.' ), on_delete=PROTECT) role = FalseFK('units.models.Role', blank=True, null=True, help_text=_(u'(Optionnel !) Le rôle concerné.')) class MetaRightsUnit(UnitEditableModel.MetaRightsUnit): unit_ro_access = True access = 'ACCREDITATION' class MetaData: list_display = [('get_display_list', ''), ('user', _('Utilisateur')), ('role', _(u'Rôle')), ('get_access', _(u'Accès'))] details_display = [('user', _('Utilisateur')), ('role', _('Rôle')), ('get_access', _(u'Accès supplémentaires')), ('valid_for_sub_units', _(u'Valide pour les sous-unités'))] default_sort = "[0, 'asc']" # id filter_fields = ('user__first_name', 'user__last_name', 'user__username', 'role__name', 'access') not_sortable_columns = [ 'get_display_list', ] base_title = _(u'Délégation d\'accès') list_title = _(u'Liste de toutes les délégations d\'accès') base_icon = 'fa fa-list' elem_icon = 'fa fa-group' menu_id = 'menu-units-delegations' yes_or_no_fields = ['valid_for_sub_units'] has_unit = True help_list = _( u"""Les délégations d'accès permettent de donner des accès supplémentaires dans une unité. Les accès sont normalement déterminés en fonction des accréditations, au niveau global. Par exemple, une personne accréditée en temps que 'Trésorier' dans une unité disposera de l'accès TRESORERIE pour l'unité. Avec les délégations d'accês, il est par exemple possible de donner l'accès "COMMUNICATION" à tout les membres d'une unité en créant une délégations d'accès. Il est aussi possible de restreindre une délégation â un utilisateur ou à un rôle particulier.""" ) class Meta: abstract = True def get_access(self): if self.access: return u', '.join(list(self.access)) def __str__(self): return _(u'Accês supplémentaire n°%s' % (self.pk, )) def delete_signal(self, request): self.save_signal() def save_signal(self): """Cleanup rights""" for user in self.unit.get_users(): user.clear_rights_cache() def get_display_list(self): return _(u'Délégation #{}'.format(self.pk))
class Customer(models.Model): """ 客户表(最开始的时候大家都是客户,销售就不停的撩你,你还没交钱就是个客户) """ qq = models.CharField(verbose_name='QQ', max_length=64, unique=True, help_text='QQ号必须唯一') qq_name = models.CharField('QQ昵称', max_length=64, blank=True, null=True) name = models.CharField('姓名', max_length=32, blank=True, null=True, help_text='学员报名后,请改为真实姓名') sex_type = (('male', '男'), ('female', '女')) sex = models.CharField("性别", choices=sex_type, max_length=16, default='male', blank=True, null=True) #存的是male或者female,字符串 birthday = models.DateField('出生日期', default=None, help_text="格式yyyy-mm-dd", blank=True, null=True) phone = models.CharField('手机号', blank=True, null=True, max_length=32) # phone = models.CharField('手机号', blank=True, null=True) source = models.CharField('客户来源', max_length=64, choices=source_type, default='qq') introduce_from = models.ForeignKey( 'self', verbose_name="转介绍自学员", blank=True, null=True, on_delete=True) #self指的就是自己这个表,和下面写法是一样的效果 # introduce_from = models.ForeignKey('Customer', verbose_name="转介绍自学员", blank=True, null=True,on_delete=models.CASCADE) course = MultiSelectField("咨询课程", choices=course_choices, null=True) #多选,并且存成一个列表的格式 # course = models.CharField("咨询课程", choices=course_choices) #如果你不想用上面的多选功能,可以使用Charfield来存 class_type = models.CharField("班级类型", max_length=64, choices=class_type_choices, default='fulltime') customer_note = models.TextField( "客户备注", blank=True, null=True, ) status = models.CharField( "状态", choices=enroll_status_choices, max_length=64, default="unregistered", help_text="选择客户此时的状态") #help_text这种参数基本都是针对admin应用里面用的 date = models.DateTimeField("咨询日期", auto_now_add=True) last_consult_date = models.DateField( "最后跟进日期", auto_now_add=True) #考核销售的跟进情况,如果多天没有跟进,会影响销售的绩效等 next_date = models.DateField("预计再次跟进时间", blank=True, null=True) #销售自己大概记录一下自己下一次会什么时候跟进,也没啥用 #用户表中存放的是自己公司的所有员工。 consultant = models.ForeignKey('UserInfo', verbose_name="销售", blank=True, null=True, on_delete=True) #一个客户可以报多个班,报个脱产班,再报个周末班等,所以是多对多。 class_list = models.ManyToManyField( 'ClassList', verbose_name="已报班级", ) #去掉了null def __str__(self): return self.name + ":" + self.qq #主要__str__最好是个字符串昂,不然你会遇到很多的坑,还有我们返回的这两个字段填写数据的时候必须写上数据,必然相加会报错,null类型和str类型不能相加等错误信息。 def get_classlist(self): #当我们通过self.get_classlist的时候,就拿到了所有的班级信息,前端显示的时候用 l = [] for cls in self.class_list.all(): l.append(str(cls)) # return mark_safe(",".join(l)) #纯文本,不用mark_safe也可以昂 return ",".join(l) #纯文本,不用mark_safe也可以昂
class Project(models.Model): name = models.CharField(max_length=30) sourceID = models.ForeignKey('Source', blank=True, on_delete=models.CASCADE, related_name='+', null=True) #owner = models.ForeignKey(User, on_delete=models.CASCADE, null = True) bPic = models.ImageField("Choose Your Project Banner Picture", default='defaultproban.jpg', upload_to='project_banner') logo = models.ImageField("Choose Your Project Logo", default='defaultlogo.jpg', upload_to='project_logo') dep_choice1 = ( ('Behavioral Sciences and Leadership', ('Behavioral Sciences and Leadership')), ('Chemistry and Life Science', ('Chemistry and Life Science')), ('Civil and Mechanical Engineering', ('Civil and Mechanical Engineering')), ('Electrical Engineering and Comptuer Science', ('Electrical Engineering and Comptuer Science')), ('English and Philosophy', ('English and Philosophy')), ('Foreign Languages', ('Foreign Languages')), ('Geography and Environmental Engineering', ('Geography and Environmental Engineering')), ('History', ('History')), ('Law', ('Law')), ('Mathematical Sciences', ('Mathematical Sciences')), ('Physics and Nuclear Engineering', ('Physics and Nuclear Engineering')), ('Social Sciences', ('Social Sciences')), ('Systems Engineering', ('Systems Engineering')), ('Independent', ('Independent')), ) department = models.CharField( # should be models.AutoOneToFieldOne(Department) max_length=50, choices=dep_choice1, default='Independent', ) mission = models.CharField( "What are is this project trying to accomplish?", max_length=50, null=True) vision = models.CharField( "How does your project's application fit in to the future?", max_length=50, null=True) description = models.TextField("Describe this project.", null=True) dateFounded = models.DateField(null=True, blank=True) look = ( ('Expert Cadets.', ('motivated cadets with niche expertise.')), ('Any cadet who wants to help.', ('cadets who want to learn and help.')), ('an engineering cadet.', ('an engineering Cadet')), ('a cadet with a scientific background.', ('a cadet with a scientific background')), ('cadets with programming experience.', ('cadets with programming experience')), ('Stem interests.', ('cadets with an interest in STEM.')), ('scholarship', ('cadets seeking scholarships from research')), ('a lot of work.', ('cadets who can work 10-20 hours a week')), ('anyone', ('anyone!')), ('Nothing', ('nothing at the moment')), ) lookingFor = MultiSelectField("What Does This Project Need", choices=look, max_choices=5) recruit = ( ('Yes', ('Yes')), ('No', ('No')), ) recruiting = models.CharField( "Is This Project Currently Recruiting?", max_length=50, choices=recruit, default='Yes', ) statusOptions = ( ('Active', ('Active')), ('Archived', ('Archived')), ('Deleted', ('Deleted')), ) status = models.CharField( max_length=50, choices=statusOptions, default='Active', ) class Meta: verbose_name_plural = "projects" def __str__(self): return self.name
class Translator(models.Model): upvote = models.PositiveIntegerField(null=True) languages = MultiSelectField(min_choices=1, choices=LANG_CHOICE, default='') response = models.TextField(blank=True)
class Advertise_with_Us(models.Model): Payments_Choices = ( ('Cash', 'Cash'), ('Cheque', 'Cheque'), ('Credit Card / Debit Card', 'Credit Card / Debit Card'), ('NEFT/RTGS', 'NEFT/RTGS'), ('UPI', 'UPI'), ) Added_by = models.ForeignKey('accounts.CustomUser', on_delete=models.CASCADE) Business_Name = models.CharField(max_length=100) slug = models.SlugField(unique=True, null=True, blank=True) Business_Category = models.ForeignKey(Category, on_delete=models.CASCADE) Business_Subcategory = models.ManyToManyField(Subcategory) Business_Services = models.ManyToManyField(Services) Business_Website = models.URLField(null=True, blank=True) Business_Facebook = models.URLField(null=True, blank=True) Business_Instagram = models.URLField(null=True, blank=True) Business_Twitter = models.URLField(null=True, blank=True) Business_Linkedin = models.URLField(null=True, blank=True) Business_Pinterest = models.URLField(null=True, blank=True) Business_Github = models.URLField(null=True, blank=True) Business_Email = models.EmailField(null=True, blank=True) # Business_Location = models.CharField(max_length=300) Business_Location = LocationField(null=True, blank=True) Address = AddressAutoHiddenField(null=True, blank=True) Business_Address = models.CharField(max_length=300) Business_Telephone = models.CharField( validators=[RegexValidator("0?[5-9]{1}\d{9}$")], max_length=15, ) Business_WhatsApp = models.CharField(null=True, blank=True, max_length=15, validators=[RegexValidator("0?[5-9]{1}\d{9}$")]) Business_Description = models.TextField() Business_Logo = models.ImageField(upload_to=advertise_logo_directory_path, validators=[FileExtensionValidator(['png', 'jpg', 'jpeg'])]) Business_Images = models.ImageField(upload_to=advertise_images_directory_path, validators=[FileExtensionValidator(['png', 'jpg', 'jpeg'])], verbose_name='Business Images',null=True, blank=True) Business_Established_Date = models.DateField() Added_at = models.DateTimeField(auto_now_add=True) tags = TaggableManager(verbose_name='Business Keywords', help_text='Tag your business here') view = models.PositiveIntegerField(default=0) Mode_Of_Payments = MultiSelectField(choices=Payments_Choices) title = models.CharField(max_length=200, null=True, blank=True) description = models.TextField(null=True, blank=True) keywords = models.TextField(null=True, blank=True, help_text='Comma separated keywords here') verified = models.BooleanField(default=False) def __str__(self): return self.Business_Name def get_absolute_url(self): return reverse("Advertise With Us") class Meta: verbose_name = "Advertise With Us" verbose_name_plural = "Advertise With Us" ordering = ('-id',) def save(self, *args, **kwargs): self.slug = slugify(self.Business_Name) super(Advertise_with_Us, self).save(*args,**kwargs) def averagereview(self): reviews = AdvertiseComment.objects.filter(advertise=self).aggregate(average=Avg('rate')) avg = 0 if reviews['average'] is not None: avg = float(reviews["average"]) return avg def countreview(self): reviews = AdvertiseComment.objects.filter(advertise=self).aggregate(count=Count('id')) cnt = 0 if reviews["count"] is not None: cnt = int(reviews["count"]) return cnt
class Survey(models.Model): JOB_CHOICES = ( ('company', 'Company'), ('home', 'Home'), ('teach', 'Teach'), ('army', 'Army'), ('none', 'None'), ) HAVEJOB_CHOICES = ( ('yes', 'Yes'), ('no', 'No'), ) TERMJOB_CHOICES = (('twoless', 'Twoless'), ('twomore', 'Twomore'), ('many', 'Many')) MANAGEJOB_CHOICES = ( ('yes', 'Yes'), ('no', 'No'), ) STUDENT_CHOICES = ( ('yes', 'Yes'), ('no', 'No'), ) HAVELESSON_CHOICES = ( ('degree', 'Degree'), ('lifetime', 'Lifetime'), ('language', 'Language'), ) LIVE_CHOICES = ( ('solo', 'Solo'), ('duo', 'Duo'), ('family', 'Family'), ('school', 'School'), ('bunker', 'Bunker'), ) # 다중 문항 LEISURE_CHOICES = ( ('movie', 'Movie'), ('club', 'Club'), ('perform', 'Perform'), ('concert', 'Concert'), ('museum', 'Museum'), ('park', 'Park'), ('camping', 'Camping'), ('beach', 'Beach'), ('sports', 'Sports'), ('house', 'House'), ('bar', 'Bar'), ('cafe', 'Cafe'), ('game', 'Game'), ('poll', 'Poll'), ('chess', 'Chess'), ('sns', 'Sns'), ('message', 'Message'), ('study', 'Study'), ('news', 'News'), ('cook', 'Cook'), ('drive', 'Drive'), ('spa', 'Spa'), ('job', 'Job'), ('service', 'Service'), ) HOBBY_CHOICES = ( ('book', 'Book'), ('music', 'Music'), ('play', 'Play'), ('sing', 'Sing'), ('dance', 'Dance'), ('write', 'Write'), ('drawing', 'Drawing'), ('cook', 'Cook'), ('animal', 'Animal'), ('stock', 'Stock'), ('news', 'News'), ('magazine', 'Magazine'), ('photo', 'Photo'), ) SPORTS_CHOICES = ( ('basketball', 'Basketball'), ('baseball', 'Baseball'), ('soccer', 'Soccer'), ('football', 'Football'), ('hockey', 'Hockey'), ('cricket', 'Cricket'), ('golf', 'Golf'), ('volleyball', 'Volleyball'), ('tennis', 'Tennis'), ('badminton', 'Badminton'), ('pingpong', 'Pingpong'), ('swimming', 'Swimming'), ('bicycle', 'Bicycle'), ('ski', 'Ski'), ('skate', 'Skate'), ('jogging', 'Jogging'), ('walking', 'Walking'), ('yoga', 'Yoga'), ('hiking', 'Hiking'), ('fishing', 'Fishing'), ('health', 'Health'), ('taekwondo', 'Taekwondo'), ('lesson', 'Lesson'), ('none', 'None'), ) REST_CHOICES = ( ('inbusiness', 'Inbusiness'), ('outbusiness', 'Outbusiness'), ('home', 'Home'), ('intravle', 'Intravle'), ('outtravle', 'Outtravle'), ) job = models.CharField(max_length=100, choices=JOB_CHOICES, null=True) haveJob = models.CharField(max_length=100, choices=HAVEJOB_CHOICES, null=True) TermJob = models.CharField(max_length=100, choices=TERMJOB_CHOICES, null=True) ManageJob = models.CharField(max_length=100, choices=MANAGEJOB_CHOICES, null=True) Student = models.CharField(max_length=100, choices=STUDENT_CHOICES, null=True) HaveLesson = models.CharField(max_length=100, choices=HAVELESSON_CHOICES, null=True) Live = models.CharField(max_length=100, choices=LIVE_CHOICES, null=True) Leisure = MultiSelectField(choices=LEISURE_CHOICES, null=True) Hobby = MultiSelectField(choices=HOBBY_CHOICES, null=True) Sports = MultiSelectField(choices=SPORTS_CHOICES, null=True) Rest = MultiSelectField(choices=REST_CHOICES, null=True)
class Condo(models.Model): name = models.CharField(max_length=100, unique=True) description = models.TextField(max_length=500) number_of_floors = models.IntegerField(default=1) # admin only juristic_persons_number = models.TextField(max_length=25) common_fee_account = models.TextField(max_length=25) AMENITY_TYPES = ( ('elevator', 'Elevator'), ('parking_lot', 'Parking Lot'), ('cctv', 'CCTV'), ('security', 'Security'), ('wifi', 'WiFi'), ('swimming_pool', 'Swimming Pool'), ('sauna', 'Sauna'), ('garden', 'Garden'), ('playground', 'Playground'), ('gym', 'Gym'), ('shop', 'Shop'), ('restaurant', 'Restaurant'), ) amenities = MultiSelectField( choices=AMENITY_TYPES, default=None, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def __str__(self): """Return the name of the condo.""" return self.name def get_rooms(self): rooms = self.room_set.all() return rooms def get_available_units(self): available_units = 0 for unit in self.get_rooms(): if not unit.still_on_contract: available_units += 1 return available_units def get_all_register_unit(self): all_units = 0 for unit in self.get_rooms(): all_units += 1 return all_units def get_images(self): return self.condoimages_set.all() # first().image.url.replace('/estate', '..', 1) def get_first_image(self): return self.condoimages_set.first().image.url.replace('/estate', '', 1) def get_class_name(self): return 'Condo'
class Customer(models.Model): """ 客户表(最开始的时候大家都是客户,销售就不停的撩你,你还没交钱就是个客户) """ qq = models.CharField(verbose_name='QQ', max_length=64, unique=True, help_text='QQ号必须唯一') qq_name = models.CharField('QQ昵称', max_length=64, blank=True, null=True) #requierd:False name = models.CharField('姓名', max_length=32, blank=True, null=True, help_text='学员报名后,请改为真实姓名') #可为空,有些人就不愿意给自己的真实姓名 sex_type = (('male', '男'), ('female', '女')) # sex = models.CharField("性别", choices=sex_type, max_length=16, default='male', blank=True, null=True) #存的是male或者female,字符串 birthday = models.DateField('出生日期', default=None, help_text="格式yyyy-mm-dd", blank=True, null=True) phone = models.BigIntegerField('手机号', blank=True, null=True) #手机号改成字符串的,不然不好搜索 # phone = models.CharField('手机号', blank=True, null=True) source = models.CharField('客户来源', max_length=64, choices=source_type, default='qq') introduce_from = models.ForeignKey( 'self', verbose_name="转介绍自学员", blank=True, null=True, on_delete=models.CASCADE) #self指的就是自己这个表,和下面写法是一样的效果 # ''' # id name introduce_from # 1 dz None # 2 xf 1 # 3 cg 1 # # ''' # introduce_from = models.ForeignKey('Customer', verbose_name="转介绍自学员", blank=True, null=True,on_delete=models.CASCADE) course = MultiSelectField( "咨询课程", choices=course_choices) #多选,并且存成一个列表的格式,通过modelform来用的时候,会成为一个多选框 # course = models.CharField("咨询课程", choices=course_choices) #如果你不想用上面的多选功能,可以使用Charfield来存 class_type = models.CharField("班级类型", max_length=64, choices=class_type_choices, default='fulltime') customer_note = models.TextField( "客户备注", blank=True, null=True, ) status = models.CharField( "状态", choices=enroll_status_choices, max_length=64, default="unregistered", help_text="选择客户此时的状态") #help_text这种参数基本都是针对admin应用里面用的 date = models.DateTimeField( "咨询日期", auto_now_add=True) #这个没啥用昂,我问销售,销售说是为了一周年的时候给客户发一个祝福信息啥的 last_consult_date = models.DateField( "最后跟进日期", auto_now_add=True) #考核销售的跟进情况,如果多天没有跟进,会影响销售的绩效等 next_date = models.DateField("预计再次跟进时间", blank=True, null=True) #销售自己大概记录一下自己下一次会什么时候跟进,也没啥用 #用户表中存放的是自己公司的所有员工。 consultant = models.ForeignKey('UserInfo', verbose_name="销售", related_name='customers', blank=True, null=True, on_delete=models.CASCADE) # 一个客户可以报多个班,报个脱产班,再报个周末班等,所以是多对多。 class_list = models.ManyToManyField('ClassList', verbose_name="已报班级", blank=True) # 成单日期,统计成单日期的时候会用到 deal_date = models.DateField(null=True) class Meta: ordering = [ 'id', ] verbose_name = '客户信息表' verbose_name_plural = '客户信息表' def __str__(self): return self.name + ":" + self.qq enroll_status_choices = (('signed', "已报名"), ('unregistered', "未报名"), ('studying', '学习中'), ('paid_in_full', "学费已交齐")) def status_show(self): status_color = { 'paid_in_full': 'green', 'unregistered': 'red', 'studying': 'lightblue', 'signed': 'yellow', } return mark_safe( "<span style='background-color:{0}'>{1}</span>".format( status_color[self.status], self.get_status_display())) def get_classlist(self): #当我们通过self.get_classlist的时候,就拿到了所有的班级信息,前端显示的时候用 l = [] for cls in self.class_list.all(): l.append(str(cls)) return mark_safe(",".join(l)) #纯文本,不用mark_safe也可以昂
class Profile(BaseModel): """ """ active = models.BooleanField(default=True) app_admin = models.BooleanField(default=False) is_contact = models.BooleanField(default=False) notify = models.BooleanField(default=True) published = models.BooleanField(default=False) dashboard_items = MultiSelectField('Dashboard Items', choices=DASHBOARD_ITEMS, null=True, blank=True) editor = models.CharField(max_length=8, choices=EDITOR_CHOICES, null=True, blank=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) icon_size = models.CharField(max_length=255, blank=True, null=True, choices=ICON_CHOICES) icon_color = models.CharField(max_length=255, blank=True, null=True, choices=COLOR_CHOICES) page_size = models.PositiveIntegerField(blank=True, null=True) preferred_username = models.CharField('Preferred Username', max_length=150, blank=True, null=True) rate = models.DecimalField('Hourly Rate (United States Dollar - USD)', blank=True, null=True, max_digits=12, decimal_places=2) unit = models.DecimalField("Unit", default=1.0, blank=True, null=True, max_digits=12, decimal_places=2) avatar_url = models.URLField("Avatar URL", blank=True, null=True) bio = models.TextField(blank=True, null=True) address = models.TextField(blank=True, null=True) preferred_payment_method = models.CharField('Preferred Payment Method', max_length=255, blank=True, null=True, choices=PAYMENT_CHOICES) def __str__(self): if self.user: return self.user.username else: return '-'.join([self._meta.verbose_name, str(self.pk)]) def get_avatar_url(self): if self.avatar_url is not None: return self.avatar_url else: return gravatar_url(self.user.email) def get_username(self): if self.preferred_username is not None: return self.preferred_username elif self.user: return self.user.username else: return '-'.join([self._meta.verbose_name, str(self.pk)])
class Customer(models.Model): """ 客户表(最开始的时候大家都是客户,销售就不停的撩你,你还没交钱就是个客户) """ qq = models.CharField(verbose_name='QQ', max_length=64, unique=True, help_text='QQ号必须唯一') qq_name = models.CharField('QQ昵称', max_length=64, blank=True, null=True) name = models.CharField('姓名', default="潜在客户", max_length=32, blank=True, null=True, help_text='学员报名后,请改为真实姓名') gender_type = (('male', '男'), ('female', '女')) gender = models.CharField("性别", choices=gender_type, max_length=16, default='male', blank=True, null=True) # 存的是male或者female,字符串 birthday = models.DateField('出生日期', default=None, help_text="格式yyyy-mm-dd", blank=True, null=True) phone = models.CharField('手机号', blank=True, null=True, max_length=32) # phone = models.CharField('手机号', blank=True, null=True) source = models.CharField('客户来源', max_length=64, choices=source_type, default='qq') introduce_from = models.ForeignKey( 'self', verbose_name="转介绍自学员", blank=True, null=True, on_delete=True) # self指的就是自己这个表,和下面写法是一样的效果 # introduce_from = models.ForeignKey('Customer', verbose_name="转介绍自学员", blank=True, null=True,on_delete=models.CASCADE) course = MultiSelectField("咨询课程", choices=course_choices, blank=True, null=True) # 多选,并且存成一个列表的格式 # course = models.CharField("咨询课程", choices=course_choices) #如果你不想用上面的多选功能,可以使用Charfield来存 class_type = models.CharField("咨询班级类型", max_length=64, choices=class_type_choices, default='fulltime', blank=True, null=True) customer_note = models.TextField( "客户备注", blank=True, null=True, ) status = models.CharField( "状态", choices=enroll_status_choices, max_length=64, default="unregistered", help_text="选择客户此时的状态") # help_text这种参数基本都是针对admin应用里面用的 date = models.DateTimeField("咨询日期", ) last_consult_date = models.DateField( "最后跟进日期", auto_now_add=True) # 考核销售的跟进情况,如果多天没有跟进,会影响销售的绩效等 next_date = models.DateField("预计再次跟进时间", blank=True, null=True) # 销售自己大概记录一下自己下一次会什么时候跟进,也没啥用 # 用户表中存放的是自己公司的所有员工。 consultant = models.ForeignKey('rbac.UserInfo', verbose_name="销售", blank=True, null=True, on_delete=True) def __str__(self): return self.name + ":" + self.qq_name + "(" + self.qq + ")" # 主要__str__最好是个字符串昂,不然你会遇到很多的坑,还有我们返回的这两个字段填写数据的时候必须写上数据,必然相加会报错,null类型和str类型不能相加等错误信息。
def test_get_prep_value(self): f = MultiSelectField() self.assertEqual(f.get_prep_value(None), None) self.assertEqual(f.get_prep_value(['a', 'b']), 'a,b')
class Customer(models.Model): """ 客户表 """ qq = models.CharField('QQ', max_length=64, unique=True, help_text='QQ号必须唯一') qq_name = models.CharField('QQ昵称', max_length=64, blank=True, null=True) name = models.CharField('姓名', max_length=32, blank=True, null=True, help_text='学员报名后,请改为真实姓名') sex_type = (('male', '男'), ('female', '女')) sex = models.CharField("性别", choices=sex_type, max_length=16, default='male', blank=True, null=True) birthday = models.DateField('出生日期', default=None, help_text="格式yyyy-mm-dd", blank=True, null=True) phone = models.BigIntegerField('手机号', blank=True, null=True) source = models.CharField('客户来源', max_length=64, choices=source_type, default='qq') introduce_from = models.ForeignKey('self', verbose_name="转介绍自学员", blank=True, null=True) course = MultiSelectField("咨询课程", choices=course_choices) class_type = models.CharField("班级类型", max_length=64, choices=class_type_choices, default='fulltime') customer_note = models.TextField( "客户备注", blank=True, null=True, ) status = models.CharField("状态", choices=enroll_status_choices, max_length=64, default="unregistered", help_text="选择客户此时的状态") network_consult_note = models.TextField(blank=True, null=True, verbose_name='网络咨询师咨询内容') date = models.DateTimeField("咨询日期", auto_now_add=True) last_consult_date = models.DateField("最后跟进日期", auto_now_add=True) next_date = models.DateField("预计再次跟进时间", blank=True, null=True) network_consultant = models.ForeignKey('UserProfile', blank=True, null=True, verbose_name='咨询师', related_name='network_consultant') consultant = models.ForeignKey( 'UserProfile', verbose_name="销售", related_name='customers', blank=True, null=True, ) class_list = models.ManyToManyField( 'ClassList', verbose_name="已报班级", )
class Fisioterapia(models.Model): enfermedades_previas = models.TextField(max_length=200) otras_enfermedades = models.TextField(max_length=200) patologia_familiar = models.TextField( max_length=500, default= "ENFERMEDAD: | GRADO DE CONSANGUINEIDAD: ") sintomas = models.CharField(max_length=200, help_text="Del ultimo año") Otros_sintomas = models.TextField(max_length=500) intervenciones_quirurgicas = models.TextField(max_length=500) fechas_de_la_intervencion = models.TextField(max_length=500) tipo_de_intervencion = models.TextField(max_length=200) embarazo = models.BooleanField(default=False) tratamientos_previos = models.TextField( max_length=500, help_text="Para el tratamiento actual") encontro_mejoria = models.BooleanField(default=False) otros_tratamientos = models.TextField(max_length=500) descripcion_del_proceso_actual = models.TextField(max_length=500) expectativas_del_paciente = models.TextField(max_length=500) expectativas_de_la_familia = models.TextField(max_length=500) datos_de_interes = models.TextField(max_length=500) habitos_de_salud = MultiSelectField(choices=HABITOS_SALUD) peso = models.IntegerField() talla = models.IntegerField() indice_de_masa_corporal = models.IntegerField() exploraciones_complementarias = models.TextField(max_length=200) hallazgos_relevantes = models.TextField(max_length=200) preescripciones_para_el_tratamiento_actual = models.TextField( max_length=200) automedicaciones = models.TextField(max_length=200) otras_medicaciones = models.TextField(max_length=200, blank=True) especificaciones_de_la_medicacion = models.TextField(max_length=200) el_paciente_vive_con = models.TextField(max_length=200) situacion_laboral = models.TextField(max_length=200) acceso_de_vivienda = models.TextField( max_length=200, help_text="¿Para acceder a la vivienda habitual de quien depende?") ayudas_tecnicas = models.TextField(max_length=200) dificultades = models.TextField(max_length=200) dicultad_en_el_autocuidado = models.TextField(max_length=200) dificultad_en_las_actividades_del_hogar = models.TextField(max_length=200) dificultad_en_las_actividades_sociales = models.TextField(max_length=200) ingreso = models.CharField(max_length=50, choices=INGRESO) dolor = models.CharField(max_length=50, choices=DOLOR) localizacion = models.CharField(max_length=100) factor_desencadenante = models.TextField(max_length=200) tipo_de_dolor = MultiSelectField(choices=TIPO_DOLOR) EAV = models.CharField(max_length=100, choices=EAV) resultados = models.TextField(max_length=200) tipo_morfologico = MultiSelectField(choices=TIPO_MORFOLOGICO) desequilibrio = MultiSelectField(choices=DESEQUILIBRIO) SHOUARD = models.CharField(max_length=50, choices=IZQ_DER) ECOM = models.CharField(max_length=50, choices=IZQ_DER) musculos_afectados = models.TextField(max_length=200) escoliosis = models.BooleanField(default=False) componente_rotacional = models.BooleanField(default=False) EDEMA = models.TextField(max_length=200) bandas_palpables = models.TextField(max_length=200) fascinas_adheridas = models.BooleanField(default=False) puntos_gatillos = models.BooleanField(default=False) puntos_dolorosos = models.BooleanField(default=False) confractura_muscular = models.BooleanField(default=False) retraccion_muscular = models.TextField( max_length=200, help_text="especifica Y/O Neuromeningeas") amplitud_articular = models.TextField( max_length=500, default="SEGMENTO ARTICULAR | MOVIMIENTO | GRADO ") sensibilidad_superficial = models.TextField(max_length=200) fuerza_muscular = models.TextField(max_length=200) tipo_de_funcionalidad = models.CharField(max_length=100, choices=TIPO_FUNCIONALIDAD) equilibrio_y_reacciones_de_enderezamiento = models.TextField( max_length=200) propiocepcion = models.TextField(max_length=200) miembros_superiores = models.IntegerField() miembros_inferiores = models.IntegerField() Columna = models.IntegerField() diagnostico = models.TextField(max_length=200) intervencion_fisioterapeutica = models.TextField(max_length=500) recomendaciones_caseras = MultiSelectField(choices=RECOM_CASERAS) resultados = models.CharField(max_length=100) sesiones_autorizadas = models.IntegerField() sesiones_realizadas = models.IntegerField() inasistencias = models.IntegerField() escala_funcional_final = models.IntegerField() definicion_de_manejo = models.TextField(max_length=200) evolucion = models.TextField(max_length=800) def get_absolute_url(self): return reverse('fisio-lista')
class Resell(Life): OPTION = (('seller', '판매'), ('buyer', '구매')) purpose = MultiSelectField(choices=OPTION, default='seller') price = models.CharField(max_length=256)
class Event(GetFieldsMixin, models.Model): class PrivacyLevel(models.IntegerChoices): Public = 1 University_Private = 2 RSO_Private = 3 class Frequency(models.TextChoices): Once = "ONCE" Daily = "DAILY" Weekly = "WEEKLY" # Not implemented yet # Monthly = "MONTHLY" # Yearly = "YEARLY" class Weekday(models.TextChoices): Monday = "MO" Tuesday = "TU" Wednesday = "WE" Thursday = "TH" Friday = "FR" Saturday = "SA" Sunday = "SU" id = models.AutoField(db_column="event_id", primary_key=True) summary = models.TextField(db_column="summary") privacy_level = models.IntegerField( db_column="privacy_level", null=False, blank=False, choices=PrivacyLevel.choices, default=PrivacyLevel.Public, ) description = models.TextField(db_column="description", blank=True, null=False, default="") phone = models.TextField(db_column="phone", blank=False, null=False) email = models.TextField(db_column="email", blank=False, null=False) dtstart = models.DateTimeField(db_column="dtstart", blank=False, null=False) dtend = models.DateTimeField(db_column="dtend", blank=True) freq = models.TextField( db_column="freq", null=False, blank=False, choices=Frequency.choices, default=Frequency.Once, verbose_name="frequency", ) until = models.DateField(db_column="until", blank=True, null=True) byday = MultiSelectField( db_column="byday", blank=True, null=True, choices=Weekday.choices, verbose_name="Repeat on", ) location = models.ForeignKey(Location, on_delete=models.CASCADE, blank=False, null=False) rso = models.ForeignKey(RSO, on_delete=models.CASCADE, related_name="events", blank=False, null=False) university = models.ForeignKey(University, on_delete=models.CASCADE, related_name="events", blank=False, null=False) tags: "models.manager.RelatedManager" class Meta: db_table = "event" unique_together = ("summary", "dtstart", "dtend", "rso") def formatted_tags(self): return ", ".join(t.text for t in self.tags.all()) @classmethod def safe_filter(cls, user: User, query=None, **kwargs): rso_specific_query = Q() for rso in user.rso_memberships.all(): rso_specific_query |= Q(rso_id=rso.id) privacy_level_checks = ( Q(privacy_level=cls.PrivacyLevel.Public.value) | Q(privacy_level=cls.PrivacyLevel.University_Private.value, university_id=user.university_id) | rso_specific_query) query = privacy_level_checks if query is None else privacy_level_checks & query return cls.objects.filter(query, **kwargs)
class Rent(Life): OPTION = (('lender', '빌려줄게요'), ('user', '빌려주세요')) purpose = MultiSelectField(choices=OPTION, default='lender') deposit = models.CharField(max_length=256) start_date = models.DateTimeField(blank=False, default=timezone.now) end_date = models.DateTimeField(blank=False, default=timezone.now)
class Post(models.Model): OUR_MISSION = "our_mission" FILM_MARKETPLACE = "film_marketplace" PUBLIC_SCREENINGS = "public_screenings" CONTENT_DELIVERY = "content_delivery" template_helper = { OUR_MISSION: "Our Mission", FILM_MARKETPLACE: "Film Marketplace", PUBLIC_SCREENINGS: "Public Screenings", CONTENT_DELIVERY: "Content Delivery", } ACTIVE = "ACTIVE" DISABLED = "DISABLED" TAG_CHOICES = [ (OUR_MISSION, "Our Mission"), (FILM_MARKETPLACE, "Film Marketplace"), (PUBLIC_SCREENINGS, "Public Screenings"), (CONTENT_DELIVERY, "Content Delivery"), ] STATUS_CHOICES = [("ACTIVE", "Active"), ("DISABLED", "Disabled")] main_title = models.CharField(max_length=100, default=" ", blank=True) slug = models.SlugField(unique=True, null=True, blank=True) title = models.CharField(max_length=100, default=" ", blank=True) content = models.TextField(default=" ", blank=True) image = models.ImageField(upload_to='blog_pics', blank=True, null=True) title2 = models.CharField(max_length=100, default=" ", blank=True) content2 = models.TextField(default=" ", blank=True) image2 = models.ImageField(upload_to='blog_pics', blank=True, null=True) title3 = models.CharField(max_length=100, default=" ", blank=True) content3 = models.TextField(default=" ", blank=True) image3 = models.ImageField(upload_to='blog_pics', blank=True, null=True) title4 = models.CharField(max_length=100, default=" ", blank=True) content4 = models.TextField(default=" ", blank=True) image4 = models.ImageField(upload_to='blog_pics', blank=True, null=True) title5 = models.CharField(max_length=100, default=" ", blank=True) content5 = models.TextField(default=" ", blank=True) image5 = models.ImageField(upload_to='blog_pics', blank=True, null=True) socials_title = models.CharField(max_length=100, default=" ", blank=True) socials_pitch = models.TextField(default=" ", blank=True) name_link = models.CharField(max_length=100, default=" ", blank=True) link = models.URLField(default=" ", blank=True) name_link2 = models.CharField(max_length=100, default=" ", blank=True) link2 = models.URLField(default=" ", blank=True) name_link3 = models.CharField(max_length=100, default=" ", blank=True) link3 = models.URLField(default=" ", blank=True) tag = MultiSelectField(max_length=200, choices=TAG_CHOICES) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default=ACTIVE) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.main_title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.main_title) return super().save(*args, **kwargs) def get_absolute_url(self): return reverse('post-detail', kwargs={'slug': self.slug}) @register.filter def get_item(dictionary, key): return dictionary.get(key)
class Keep(Life): OPTION = (('lender', '보관할래요'), ('user', '보관해줄게요')) purpose = MultiSelectField(choices=OPTION, default='lender') reward = models.CharField(max_length=256) start_date = models.DateTimeField(blank=False, default=timezone.now) end_date = models.DateTimeField(blank=False, default=timezone.now)
class shared_room(models.Model): user_name = models.CharField(max_length=120, null=True) user = models.CharField(max_length=120, null=True) email = models.EmailField(max_length=120, null=True) phone = models.IntegerField(null=True) City = models.CharField(max_length=100, blank=False, null=True) Area = models.CharField(max_length=100, blank=False, null=True) Address = models.CharField(max_length=200, blank=False, null=True) rent = models.IntegerField(default=0) securitydeposit = models.IntegerField(default=0) Numbers = [(i, i) for i in range(11)] Area_sqft = models.IntegerField(default=0) bed_rooms = models.IntegerField(choices=Numbers, default=0) bathrooms = models.IntegerField(choices=Numbers, default=0) kitchen = models.IntegerField(choices=Numbers, default=0) hall = models.IntegerField(choices=Numbers, default=0) beds_available = models.IntegerField(default=0) gender_choices = (('male', 'male'), ('female', 'female'), ('family', 'family'), ('any', 'any')) gender = models.CharField(max_length=20, choices=gender_choices, default="any") Furniture_choices = (('full', 'full furnished'), ('semi', 'semi furnished'), ('no', 'no furnished')) Furniture = models.CharField(max_length=20, choices=Furniture_choices, default='full') available_choices = (('yes', 'Yes'), ('no', 'No')) Available = models.CharField(max_length=10, choices=available_choices, default='no') essential_amenities = (('parking', 'Car parking'), ('security', 'Security services'), ('water', 'Water supply'), ('elevator', 'Elevators'), ('power', 'Power backup'), ('maintenance', '24-hour maintenance')) essentialamenities = MultiSelectField(choices=essential_amenities, default='parking') optional_amenities = (('play', 'Play area'), ('gym', 'Gym'), ('salon', 'Spa and salon'), ('Concierge', 'Concierge services'), ('hospital', 'Hospitals'), ('restaurant', 'Restaurants'), ('temples', 'Temple and religious activity place'), ('wifi', 'Wi-Fi connectivity')) optionalamenities = MultiSelectField(choices=optional_amenities, default='play') description = models.TextField(blank=False, null=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) image1 = models.ImageField(upload_to=upload_location, verbose_name='Image(optional)', blank=True) image2 = models.ImageField(upload_to=upload_location, verbose_name='Image(optional)', blank=True) image3 = models.ImageField(upload_to=upload_location, verbose_name='Image(optional)', blank=True) image4 = models.ImageField(upload_to=upload_location, verbose_name='Image(optional)', blank=True) image5 = models.ImageField(upload_to=upload_location, verbose_name='Image(optional)', blank=True) image6 = models.ImageField(upload_to=upload_location, verbose_name='Image(optional)', blank=True) def get_absolute_url(self): return reverse("house-detail", kwargs={"my_id": self.id}) return f"/question_list/{self.id}/" class Meta: ordering = ["-updated", "-timestamp"]
class RMEC_Employee(models.Model): last_name = models.CharField( max_length=200, blank=True, null=True, ) first_name = models.CharField( max_length=200, blank=True, null=True, ) doc_no = models.IntegerField(verbose_name="DOC #", unique=True) correctional_facility = models.CharField( max_length=100, blank=True, null=True, ) home_address = models.CharField( max_length=200, blank=True, null=True, ) city = models.CharField( max_length=200, blank=True, null=True, ) state = models.CharField( max_length=200, choices=STATE_CHOICE, blank=True, null=True, ) zip_code = models.CharField( max_length=200, blank=True, null=True, ) phone = models.CharField( max_length=15, blank=True, null=True, ) email = models.EmailField( max_length=200, blank=True, null=True, ) education = models.CharField( max_length=200, choices=EDUCATION_CHOICES, blank=True, null=True, ) certificate = MultiSelectField( max_length=300, choices=CERTIFICATE_CHOCIES, blank=True, max_choices=11, null=True, ) work_area = MultiSelectField( max_length=300, choices=WORKAREA_CHOCIES, blank=True, max_choices=6, null=True, ) job_status = models.BooleanField(default=False) hired_date = models.DateField( max_length=200, blank=True, null=True, ) created_date = models.DateField( max_length=200, blank=True, null=True, ) updated_date = models.DateField( max_length=200, blank=True, null=True, ) hired_by = models.CharField( max_length=200, blank=True, null=True, )
class _Role(GenericModel, AgepolyEditableModel, SearchableModel): """Un role, pour une accred""" class MetaRightsAgepoly(AgepolyEditableModel.MetaRightsAgepoly): access = 'INFORMATIQUE' world_ro_access = True name = models.CharField(max_length=255, default='---') id_epfl = models.CharField( max_length=255, null=True, blank=True, help_text=_( u'Mettre ici l\'ID accred du rôle pour la synchronisation EPFL')) description = models.TextField(null=True, blank=True) order = models.IntegerField( null=True, blank=True, help_text= _(u'Il n\'est pas possible d\'accréditer la même personne dans la même unité plusieurs fois. Le rôle avec le plus PETIT ordre sera pris en compte' )) need_validation = models.BooleanField( _(u'Nécessite validation'), default=False, help_text= _(u'A cocher pour indiquer que le comité de l\'AGEPoly doit valider l\'attribution du rôle' )) ACCESS_CHOICES = (('PRESIDENCE', _(u'Présidence')), ('TRESORERIE', _(u'Trésorerie')), ('COMMUNICATION', _('Communication')), ('INFORMATIQUE', _('Informatique')), ('ACCREDITATION', _(u'Accréditations')), ('LOGISTIQUE', _('Logistique')), ('SECRETARIAT', _(u'Secrétariat')), ('COMMISSIONS', _(u'Commissions'))) access = MultiSelectField(choices=ACCESS_CHOICES, blank=True, null=True) def __str__(self): return self.name def get_access(self): if self.access: return u', '.join(list(self.access)) def __init__(self, *args, **kwargs): super(_Role, self).__init__(*args, **kwargs) self.MetaRights = type("MetaRights", (self.MetaRights, ), {}) self.MetaRights.rights_update({ 'DISPLAY_ACTIVE_USERS': _(u'Peut afficher la liste des gens possédant l\'accréditation'), }) def rights_can_DISPLAY_ACTIVE_USERS(self, user): if user.is_superuser: return True return self.rights_in_root_unit(user, 'INFORMATIQUE') class MetaData: list_display = [('name', _('Nom')), ('id_epfl', _('ID EPFL ?')), ('need_validation', _('Validation ?')), ('order', _('Ordre'))] details_display = [ ('name', _('Nom')), ('description', _('Description')), ('id_epfl', _('ID EPFL ?')), ('need_validation', _('Validation ?')), ('order', _('Ordre')), ('get_access', _(u'Accès')), ] default_sort = "[1, 'asc']" # name filter_fields = ('name', 'id_epfl', 'description') yes_or_no_fields = ['need_validation'] base_title = _(u'Rôles') list_title = _(u'Liste de tous les rôles') base_icon = 'fa fa-list' elem_icon = 'fa fa-group' menu_id = 'menu-units-roles' help_list = _( u"""Les rôles sont les différents type d'accréditations possibles pour une unité. Certains rôles donnent des accès particuliers. Par exemple, le rôle 'Trésorier' donne l'accès TRÉSORERIE. Les droits sont gérés en fonction des accès !""" ) class MetaSearch(SearchableModel.MetaSearch): extra_text = u'rôle role roles' fields = [ 'name', 'description', 'get_access', ] class Meta: abstract = True def can_delete(self): if self.accreditation_set.count(): return ( False, _(u'Au moins une accréditation existe avec ce rôle, impossible de supprimer le rôle (NB: Historique compris)' )) return (True, None)
class Category(models.Model): name = MultiSelectField(choices=MY_CHOICES, max_choices=3) def __str__(self): return f"{self.id} - {self.name}"
class Site(ZoningPropertiesMixin, AddPropertyMixin, PublishableMixin, MapEntityMixin, StructureRelated, TimeStampedModelMixin, MPTTModel): ORIENTATION_CHOICES = ( ('N', _("↑ N")), ('NE', _("↗ NE")), ('E', _("→ E")), ('SE', _("↘ SE")), ('S', _("↓ S")), ('SW', _("↙ SW")), ('W', _("← W")), ('NW', _("↖ NW")), ) geom = models.GeometryCollectionField(verbose_name=_("Location"), srid=settings.SRID) parent = TreeForeignKey('Site', related_name="children", on_delete=models.PROTECT, verbose_name=_("Parent"), null=True, blank=True) practice = models.ForeignKey('Practice', related_name="sites", on_delete=models.PROTECT, verbose_name=_("Practice"), null=True, blank=True) description = models.TextField(verbose_name=_("Description"), blank=True, help_text=_("Complete description")) description_teaser = models.TextField( verbose_name=_("Description teaser"), blank=True, help_text=_("A brief summary (map pop-ups)")) ambiance = models.TextField(verbose_name=_("Ambiance"), blank=True, help_text=_("Main attraction and interest")) advice = models.TextField(verbose_name=_("Advice"), blank=True, help_text=_("Risks, danger, best period, ...")) ratings_min = models.ManyToManyField(Rating, related_name='sites_min', blank=True) ratings_max = models.ManyToManyField(Rating, related_name='sites_max', blank=True) period = models.CharField(verbose_name=_("Period"), max_length=1024, blank=True) orientation = MultiSelectField(verbose_name=_("Orientation"), blank=True, max_length=20, choices=ORIENTATION_CHOICES) wind = MultiSelectField(verbose_name=_("Wind"), blank=True, max_length=20, choices=ORIENTATION_CHOICES) labels = models.ManyToManyField('common.Label', related_name='sites', blank=True, verbose_name=_("Labels")) themes = models.ManyToManyField('common.Theme', related_name="sites", blank=True, verbose_name=_("Themes"), help_text=_("Main theme(s)")) information_desks = models.ManyToManyField( 'tourism.InformationDesk', related_name='sites', blank=True, verbose_name=_("Information desks"), help_text=_("Where to obtain information")) portal = models.ManyToManyField('common.TargetPortal', blank=True, related_name='sites', verbose_name=_("Portal")) source = models.ManyToManyField('common.RecordSource', blank=True, related_name='sites', verbose_name=_("Source")) web_links = models.ManyToManyField('trekking.WebLink', related_name="sites", blank=True, verbose_name=_("Web links"), help_text=_("External resources")) type = models.ForeignKey(SiteType, related_name="sites", on_delete=models.PROTECT, verbose_name=_("Type"), null=True, blank=True) eid = models.CharField(verbose_name=_("External id"), max_length=1024, blank=True, null=True) class Meta: verbose_name = _("Outdoor site") verbose_name_plural = _("Outdoor sites") ordering = ('name', ) class MPTTMeta: order_insertion_by = ['name'] def __str__(self): return self.name @property def name_display(self): return "- " * self.level + super().name_display def distance(self, to_cls): """Distance to associate this site to another class""" return None @classmethod def get_create_label(cls): return _("Add a new outdoor site") @property def published_children(self): if not settings.PUBLISHED_BY_LANG: return self.children.filter(published=True) q = Q() for lang in settings.MODELTRANSLATION_LANGUAGES: q |= Q(**{'published_{}'.format(lang): True}) return self.children.filter(q) @property def super_practices(self): "Return practices of itself and its descendants" practices_id = self.get_descendants(include_self=True) \ .exclude(practice=None) \ .values_list('practice_id', flat=True) return Practice.objects.filter( id__in=practices_id) # Sorted and unique @property def super_practices_display(self): practices = self.super_practices if not practices: return "" verbose = [ str(practice) if practice == self.practice else "<i>{}</i>".format( escape(practice)) for practice in practices ] return ", ".join(verbose) super_practices_verbose_name = _('Practices') @property def super_sectors(self): "Return sectors of itself and its descendants" sectors_id = self.get_descendants(include_self=True) \ .exclude(practice=None) \ .values_list('practice__sector_id', flat=True) return Sector.objects.filter(id__in=sectors_id) # Sorted and unique @property def super_orientation(self): "Return orientation of itself and its descendants" orientation = set( sum( self.get_descendants(include_self=True).values_list( 'orientation', flat=True), [])) return [o for o, _o in self.ORIENTATION_CHOICES if o in orientation] # Sorting @property def super_wind(self): "Return wind of itself and its descendants" wind = set( sum( self.get_descendants(include_self=True).values_list('wind', flat=True), [])) return [o for o, _o in self.ORIENTATION_CHOICES if o in wind] # Sorting
class Broadcast(models.Model): title = models.CharField(max_length=220) VIA = ( ('email', 'Email'), ('push_notification', 'Push Notification'), ('sms', 'SMS'), ) via = MultiSelectField(choices=VIA) short_content = models.TextField( max_length=140, blank=True, null=True, help_text="Kontek untuk siaran via Push Notification dan SMS") html_content = RichTextField(blank=True, null=True, help_text="Kontek untuk siaran via Email") def __str__(self): return self.title def preview(self, user): # get setting appearance from academy.apps.offices import utils sett = utils.get_settings(serializer=True) data = { 'host': settings.HOST, 'user': user, 'body': self.html_content, 'email_title': self.title } data.update(sett) html_message = render_to_string('emails/universal_template.html', context=data) return html_message def via_email(self): if 'email' in self.via: return True else: return False def via_push_notif(self): if 'push_notification' in self.via: return True else: return False def send(self, users): inbox_ids = [] for user in users: html_message = self.preview(user) inbox = Inbox.objects.create(user=user, subject=self.title, content=html_message) inbox_ids.append(inbox.id) queue = django_rq.get_queue('high') for inbox_id in inbox_ids: kwargs = { 'inbox_id': inbox_id, 'send_email': self.via_email, 'send_push_notif': self.via_push_notif } queue.enqueue(_send, **kwargs)
class ActivityProfile(models.Model): """ Model that represents a profile of an activity area """ activity_area = models.OneToOneField(ActivityArea, related_name='profile', on_delete=models.CASCADE, verbose_name='Tätigkeitsbereich') image = models.URLField('Bild-URL', null=True, blank=True, help_text='Direktlink zu einem Bild') image_credits = models.CharField( 'Bild-Namensnennung', max_length=100, null=True, blank=True, help_text= 'Falls für die Verwendung des Bilds eine Namensnennung erforderlich ist' ) image_credits_url = models.URLField( 'Bild-Namensnennung-URL', null=True, blank=True, help_text='Link zur Lizenz des Bilds (wenn erforderlich)') learn = RichTextField( 'Lernen / Vorkenntnisse', max_length=1500, null=True, blank=True, help_text= 'Was kann das Mitglied in dieser Gruppe lernen? Welche Kenntnisse werden vorausgesetzt?' ) introduction = RichTextField('Einführung', max_length=1000, null=True, blank=True, help_text='Ist eine Einführung nötig?') active_members = models.PositiveSmallIntegerField( 'Anzahl aktive Mitglieder', default=1) minimum_size = models.PositiveSmallIntegerField('Mindestgrösse', default=1) target_size = models.PositiveSmallIntegerField('Wunschgrösse', default=0, null=True, blank=True) wanted = models.CharField('Interessierte Gesucht?', default='no', max_length=10, choices=[('no', 'Nein'), ('yes', 'Ja'), ('urgent', 'Dringend')]) wanted_for = models.CharField( 'Interessierte Gesucht für', max_length=300, default='', null=True, blank=True, help_text='Wofür genau werden Interessierte gesucht? (optional)') group_extras = RichTextField( 'Gruppe / Mitglieder', max_length=1000, null=True, blank=True, help_text='Weitere Informationen zur Gruppe und deren Mitglieder') clothing = RichTextField('Kleidung', max_length=1000, null=True, blank=True) season = MultiSelectField('Saison', choices=SEASON, null=True) flexible = models.BooleanField( 'Einsätze Flexibel möglich?', default=False, help_text= 'Können eingeführte Mitglieder, jederzeit selbständig Einsätze leisten?' ) alone = models.BooleanField('Einsätze alleine möglich?', default=False) in_groups = models.BooleanField('Einsätze in Gruppen möglich?', default=False) days = models.CharField( 'Tage', max_length=100, null=True, blank=True, help_text='Welche Tage der Woche gibt es Einsätze?') jobs_more = RichTextField( 'Mehr Einsatzdetails', max_length=1000, null=True, blank=True, help_text='Was muss für den Einsatz sonst noch beachtet werden?') children = RichTextField( 'Kinderbegleitung Möglich?', max_length=500, null=True, blank=True, help_text= 'Falls ja, unter welchen Bedingungen. Falls nein, warum nicht?') email = models.EmailField( 'Gruppen-E-Mail', null=True, blank=True, help_text='E-Mail-Verteiler der Gruppe (falls vorhanden). ' 'Wenn leer wird Koordinations-E-Mail angezeigt.') chat = models.URLField( 'Gruppen-Chat-Link', null=True, blank=True, help_text='Link zu Chat der Gruppe in Telegram oder Whatsapp etc.') other_communication = models.CharField( 'Andere Kommunikationsmethoden', max_length=200, null=True, blank=True, help_text= 'Andere Links oder Beschreibungen, wie Mitglieder interagieren können.' ) def get_absolute_url(self): return reverse('area', args=[self.activity_area.pk]) @property def name(self): return self.activity_area.name @property def group_emails(self): return self.email if self.email else self.activity_area.get_emails()[0] @property def link(self): if self.chat: return self.chat return Config.server_url() + reverse('area', args=(self.activity_area.id, )) @property def output_file(self): return f'_activityprofile_pdfs/{self.name}.pdf' def __str__(self): return f'{self.name} Steckbrief' class Meta: verbose_name = _('Steckbrief') verbose_name_plural = _('Steckbriefe')
class VerifiedUser(models.Model): """ Verified informations class """ have_car = models.BooleanField( default=False, choices=BOOL_CHOICES, verbose_name=_("Disposez-vous d'une voiture ?")) can_wheelchair = models.BooleanField( default=False, choices=BOOL_CHOICES, verbose_name=_( "Pouvez-vous transporter une chaise roulante dans votre voiture ?") ) drive_license = MultiSelectField( choices=DRIVER_LICENSE, verbose_name=_("Type de permis de conduire"), blank=True) # ppl with you have ongoing job work_with = models.ManyToManyField('User', related_name="verified_work_with", blank=True, null=True) # network management favorites = models.ManyToManyField('User', related_name="verified_favorites", blank=True, null=True) personal_network = models.ManyToManyField( 'User', verbose_name="Votre réseau personnel", related_name="verified_personal_network", blank=True, null=True) ignore_list = models.ManyToManyField('User', verbose_name="Personne ignorée", related_name="verified_ignore_list", blank=True, null=True) mail_preferences = models.IntegerField( choices=INFORMED_BY, default=INBOX, verbose_name=_("Recevoir mes messages par")) receive_help_from_who = models.IntegerField( choices=MemberType.MEMBER_TYPES_GROUP, default=MemberType.ALL, verbose_name=_("Recevoir des demandes et des offres de")) offered_job = MultiSelectField( choices=JobCategory.JOB_CATEGORIES, verbose_name=_( "Quelles sont les tâches que vous souhaitez effectuer ?"), blank=True) # TODO : Schedule time facebook = models.URLField( verbose_name="Lien (URL) de votre profil Facebook", blank=True) hobbies = models.TextField(verbose_name=_("Vos hobbies"), blank=True, max_length=200) additional_info = models.TextField( verbose_name=_("Informations supplémentaires"), blank=True, max_length=300) def get_verbose_license(self): if not self.drive_license: return '' return ', '.join([ str(l[1]) for l in DRIVER_LICENSE if (str(l[0]) in self.drive_license) ]) def get_verbose_offered_job(self): if not self.offered_job: return '' return ', '.join([ str(l[1]) for l in JobCategory.JOB_CATEGORIES if (str(l[0]) in self.offered_job) ]) def get_verbose_mail(self): return str(INFORMED_BY[self.mail_preferences][1]) def get_verbose_receive(self): return ', '.join([ str(l[1]) for l in MemberType.MEMBER_TYPES_GROUP if (l[0] == self.receive_help_from_who) ]) def get_verbose_car(self): if self.have_car: return _("Oui") else: return _("Non") def get_verbose_can_wheelchair(self): if self.can_wheelchair: return _("Oui") else: return _("Non")
def test_to_python(self): f = MultiSelectField() self.assertEqual(f.to_python(''), []) self.assertEqual(f.to_python(None), None) self.assertEqual(f.to_python('a,b'), ['a', 'b']) self.assertEqual(f.to_python(['a', 'b']), ['a', 'b'])
class User(AbstractBaseUser, PermissionsMixin, CommonInfo, VerifiedUser): """ Custom user class AbstractBaseUser gives us the following fields : * password * last_login * is_active See https://github.com/django/django/blob/master/django/contrib/auth/models.py#L191 PermissionsMixin gives us the following fields : * is_superuser * groups * user_permissions See https://github.com/django/django/blob/master/django/contrib/auth/models.py#L299 """ email = models.EmailField(_("Adresse email"), unique=False) date_joined = models.DateTimeField(auto_now_add=True) photo = ThumbnailerImageField(upload_to='photos/', blank=False, default='photos/default_avatar.png') username = models.CharField(_("Nom d'utilisateur"), max_length=30, unique=True, validators=[ validators.RegexValidator( re.compile('^[\w.@+-]+$'), _("Entrez un nom d'utilisateur valide.\ 30 caractères ou moins. Peut contenir des lettres, nombres et les caractères @/./+/-/_ " ), 'invalid') ]) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_verified = models.BooleanField(default=False) status = models.IntegerField(choices=STATUS, default=ACTIVE) user_type = models.IntegerField( _("Type de compte"), choices=MemberType.MEMBER_TYPES, default=MemberType.MEMBER, help_text=_('Un member pourra aider ou être aidé alors qu\'un \ non-membre est un professionnel qui s\'inscrira pour avoir accès aux données d\'un \ patient. Veuillez choisir celui qui vous correspond' )) how_found = MultiSelectField( choices=HOW_FOUND_CHOICES, verbose_name=_("Comment avez-vous entendu parler de Care4Care ?")) birth_date = models.DateField(blank=True, null=True, verbose_name=_("Date de naissance")) credit = models.IntegerField(default=0, verbose_name=_("Crédit restant")) # in minuts #Verified member # social_media = [] # Commented since we don't know how it'll be traited by the third-app. #non member organization = models.CharField(_("Organization"), max_length=100, blank=True) work = models.CharField(_("Fonction"), max_length=100, blank=True, null=True) objects = UserManager() REQUIRED_FIELDS = [ 'email', 'first_name', 'last_name', ] USERNAME_FIELD = 'username' def get_full_name(self): return '{} {}'.format(self.first_name, self.last_name) def get_short_name(self): return self.first_name def get_verbose_credit(self): credit = self.credit chunks = ( (60 * 24 * 365, ('%d année', '%d années') ), #Yeah.. We never know. Maybe slaves will use this app. (60 * 24 * 30, ('%d mois', '%d mois')), (60 * 24 * 7, ('%d semaine', '%d semaines')), (60 * 24, ('%d jour', '%d jours')), (60, ('%d heure', '%d heures')), (1, ('%d minute', '%d minutes'))) if credit < 0: return str('<span class="text-danger">' + str(credit) + __(' minute(s)') + '</span>') for i, (minuts, name) in enumerate(chunks): count = credit // minuts if count != 0: break credit -= count * minuts if count > 2: result = (name[1] % count) else: result = (name[0] % count) while i + 1 < len(chunks): minuts2, name2 = chunks[i + 1] count2 = credit // minuts2 if count2 != 0: if count2 > 2: result += ', ' + (name2[1] % count2) else: result += ', ' + (name2[0] % count2) credit -= count2 * minuts2 i += 1 return result def get_verbose_status(self): return STATUS[self.status - 1][1] def get_account_type(self): if self.is_superuser: return _('superuser') if self.user_type == MemberType.MEMBER: return MemberType.VERBOSE_M if self.user_type == MemberType.NON_MEMBER: return MemberType.VERBOSE_NM if self.user_type == MemberType.VERIFIED_MEMBER: return MemberType.VERBOSE_VM return _('Inconnu') def __str__(self): return self.username @models.permalink def get_absolute_url(self): return ('user_profile', (), {'user_id': self.id})
def test_get_default(self): f = MultiSelectField() f.default = None self.assertEqual(f.get_default(), None) f.default = 'a,b,c' self.assertEqual(f.get_default(), 'a,b,c') f.default = 1 self.assertEqual(f.get_default(), '1') f.default = ['a','b'] self.assertEqual(f.get_default(), ['a','b']) f.default = ('a','b') self.assertEqual(f.get_default(), ('a','b')) f.default = set(['a','b']) self.assertEqual(f.get_default(), set(['a','b']))
class Customer(models.Model): """ 客户表 """ qq = models.CharField('QQ', max_length=64, unique=True, help_text='QQ号必须唯一') qq_name = models.CharField('QQ昵称', max_length=64, blank=True, null=True) name = models.CharField('姓名', max_length=32, blank=True, null=True, help_text='学员报名后,请改为真实姓名', default="") sex_type = (('male', '男'), ('female', '女')) sex = models.CharField("性别", choices=sex_type, max_length=16, default='male', blank=True, null=True) birthday = models.DateField('出生日期', default=None, help_text="格式yyyy-mm-dd", blank=True, null=True) phone = models.CharField('手机号', max_length=128, blank=True, null=True) source = models.CharField('客户来源', max_length=64, choices=source_type, default='qq') introduce_from = models.ForeignKey('Customer', verbose_name="转介绍自学员", blank=True, null=True, on_delete=models.CASCADE) course = MultiSelectField("咨询课程", choices=course_choices, null=True, blank=True) class_type = models.CharField("班级类型", max_length=64, choices=class_type_choices, default='fulltime') customer_note = models.TextField( "客户备注", blank=True, null=True, ) status = models.CharField("状态", choices=enroll_status_choices, max_length=64, default="unregistered", help_text="选择客户此时的状态") date = models.DateTimeField("咨询日期", auto_now_add=True) last_consult_date = models.DateField("最后跟进日期", auto_now_add=True) next_date = models.DateField("预计再次跟进时间", blank=True, null=True) consultant = models.ForeignKey('UserInfo', verbose_name="销售", related_name='customers', blank=True, null=True, on_delete=models.CASCADE) class_list = models.ManyToManyField('ClassList', verbose_name="已报班级", null=True, blank=True) def __str__(self): return self.name deal_date = models.DateField("成交日期", null=True, blank=True) def get_classlist(self): # Customer表中 获取对象的所报班级 li = [] for clas in self.class_list.all(): li.append(str(clas)) return mark_safe("<br>".join(li)) def get_status(self): # 在Customer表中加get_status方法 status_color = { "studying": "green", "signed": "grey", "unregistered": "red", "paid_in_full": "blue" } return mark_safe( "<span style='background-color:%s;color:white'>%s</span>" % (status_color[self.status], self.get_status_display()))