def test_pre_save(self): p = Poll() p.image = SimpleUploadedFile(TEST_IMAGE, b'') c = CloudinaryField('image', width_field="image_width", height_field="image_height") c.set_attributes_from_name('image') mocked_resource = cloudinary.CloudinaryResource(metadata={"width": TEST_IMAGE_W, "height": TEST_IMAGE_H}, type="upload", public_id=TEST_IMAGE, resource_type="image") with mock.patch('cloudinary.uploader.upload_resource', return_value=mocked_resource) as upload_mock: prep_value = c.pre_save(p, None) self.assertTrue(upload_mock.called) self.assertEqual(".png", os.path.splitext(prep_value)[1]) self.assertEqual(TEST_IMAGE_W, p.image_width) self.assertEqual(TEST_IMAGE_H, p.image_height) # check empty values handling p.image = SimpleUploadedFile(TEST_IMAGE, b'') mocked_resource_empty = cloudinary.CloudinaryResource(metadata={}) with mock.patch('cloudinary.uploader.upload_resource', return_value=mocked_resource_empty) as upload_mock: c.pre_save(p, None) self.assertTrue(upload_mock.called) self.assertIsNone(p.image_width) self.assertIsNone(p.image_height)
class Author(models.Model): name = models.CharField(max_length=200) picture = CloudinaryField(blank=True) def __str__(self): return self.name
def test_get_prep_value(self): c = CloudinaryField('image') res = CloudinaryImage(public_id='sample', format='jpg') self.assertEqual(c.get_prep_value(res), "image/upload/sample.jpg")
def test_get_internal_type(self): c = CloudinaryField('image', null=True) self.assertEqual(c.get_internal_type(), "CharField")
def test_get_prep_value(self): c = CloudinaryField('image') res = CloudinaryImage(public_id=API_TEST_ID, format='jpg') self.assertEqual(c.get_prep_value(res), "image/upload/{}.jpg".format(API_TEST_ID))
def test_to_python(self): c = CloudinaryField('image') res = CloudinaryResource(public_id=API_TEST_ID, format='jpg') # Can't compare the objects, so compare url instead self.assertEqual(c.to_python('{}.jpg'.format(API_TEST_ID)).build_url(), res.build_url())
class Photo(models.Model): image = CloudinaryField('image')
class Pictures(models.Model): image = CloudinaryField('image')
class Photo(VoteModel,models.Model): image = CloudinaryField('image') image_name = models.CharField(max_length=50) image_caption = models.CharField(max_length=100) user = models.ForeignKey(User,on_delete=models.CASCADE)
class Photo(VoteModel, models.Model): image = CloudinaryField('image') image_name = CloudinaryField('name')
class Profile(models.Model): first_name = models.CharField(max_length=200, blank=True) last_name = models.CharField(max_length=200, blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(default='no bio...', max_length=300) email = models.EmailField(max_length=200, blank=True) gender = models.CharField(max_length=10, blank=True) date_of_birth = models.DateField(blank=True, null=True) city = models.CharField(max_length=30, default='Lagos', blank=True) country = models.CharField(max_length=200, blank=True) avatar = CloudinaryField( 'avatar', default='avatar.png', ) friends = models.ManyToManyField(User, blank=True, related_name='friends') work_place = models.CharField(blank=True, max_length=400) school = models.CharField(blank=True, max_length=300) slug = models.SlugField(unique=True, blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) objects = ProfileManager() def __str__(self): return f"{self.user.username}-{self.created.strftime('%d-%m-%y')}" def get_absolute_url(self): return reverse("profile-details", kwargs={"slug": self.slug}) def get_friends(self): return self.friends.all() def get_friends_no(self): return self.friends.all().count() def get_post_no(self): return self.posts.all().count() def get_all_authors_post(self): return self.posts.all() def get_likes_given_no(self): likes = self.like_set.all() total_liked = 0 for item in likes: if item.value == 'Like': total_liked += 1 return total_liked def get_likes_received_no(self): posts = self.posts.all() total_liked = 0 for item in posts: total_liked += item.liked.all().count() return total_liked __initial_first_name = None __initial_last_name = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__initial_first_name = self.first_name self.__initial_last_name = self.last_name def save(self, *args, **kwargs): ex = False to_slug = self.slug if self.first_name != self.__initial_first_name or self.last_name != self.__initial_last_name or self.slug == "": if self.first_name and self.last_name: to_slug = slugify( str(self.first_name) + '' + str(self.last_name)) ex = Profile.objects.filter(slug=to_slug).exists() while ex: to_slug = slugify(to_slug + '' + str(get_random_code())) ex = Profile.objects.filter(slug=to_slug).exists() else: to_slug = str(self.user) self.slug = to_slug super().save(*args, **kwargs)
class Game(models.Model): """ TABLE: games PARAMS: name logo_image main_image description start_date end_date is_active """ class Meta: db_table = "games" name = models.CharField(max_length=100) logo_image = CloudinaryField('image') description = models.TextField(blank=True, default='') start_date = models.DateTimeField(blank=True, null=True) end_date = models.DateTimeField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=False) def logo_image_tag(self): return format_html( "<a href='{0}' target='_blank' ><img src='{0}' width='144px'></a>", self.logo_image.build_url(), ) def competition_list(self): return format_html( '{}', Competition.objects.filter( game_id=self.id, is_active=True, ).values('name') ) def sponed_sponsor_list(self): return format_html( '{}', Sponsor.objects.filter( pk__in=Game2Sponsor.objects.filter( game_id=self.id, is_active=True ).values_list('sponsor_id', flat=True) ).values('name') ) def resources(self): return Resource.objects.filter( model_type=Resource.MODEL_TYPE_GAME, model_id=self.id, is_active=True, ).order_by('order')
class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(default="John", max_length=20) last_name = models.CharField(default="Doe", max_length=20) email = models.CharField(default="*****@*****.**", max_length=255) birth_date = models.DateField(null=True, blank=True) votes = models.ManyToManyField(Rushee, blank=True) image = CloudinaryField( "Image", default='https://res.cloudinary.com/texasakpsi/image/upload/c_thumb,w_200,g_face/v1566281324/profile_pics/blank-profile-picture_twrtwg.png', overwrite=True, resource_type="image", transformation={"quality": "auto:eco"}, format="jpg", folder='profile_pics', use_filename=True, unique_filename=False, ) img_src = models.URLField(null=True, blank=True) philanthropy_req = models.IntegerField(default='0') professional_req = models.IntegerField(default='0') tech_req = models.IntegerField(default='0') financial_req = models.BooleanField(default=False) pledge_class = models.CharField(max_length=5, blank=False) FRESHMAN = 0 SOPHOMORE = 1 JUNIOR = 2 SENIOR = 3 GRADUATE = 4 COLLEGE_YEAR = ((FRESHMAN, "Freshman"), (SOPHOMORE, "Sophomore"), (JUNIOR, "Junior"), (SENIOR, "Senior"), (GRADUATE, "Graduate")) college_year_selection = models.PositiveSmallIntegerField(choices=COLLEGE_YEAR, null=False, blank=False, default=0) isPhilDirector = models.BooleanField(default=False) isProfDirector = models.BooleanField(default=False) isTechDirector = models.BooleanField(default=False) isPresident = models.BooleanField(default=False) isVP = models.BooleanField(default=False) isSocialDirector = models.BooleanField(default=False) def is_exec(self): if self.isVP: return True if self.isProfDirector: return True if self.isTechDirector: return True if self.isSocialDirector: return True if self.isPresident: return True if self.isPhilDirector: return True return False def __str__(self): return self.user.get_full_name() def get_college_year(self): try: return self.COLLEGE_YEAR[self.college_year_selection][1] except Exception: return "N/A" def set_first_name(self, name): self.user.first_name = name self.first_name = name def set_last_name(self, name): self.user.last_name = name self.last_name = name def set_email(self, email): self.user.email = email self.email = email def clear_exec_position(self): self.isPhilDirector = False self.isProfDirector = False self.isTechDirector = False self.isPresident =False self.isVP = False self.isSocialDirector = False create_or_update_user_profile(instance=self, created=True)
class Image(models.Model): image = CloudinaryField('image')
class CustomerInvoice(models.Model): # Primary Key id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) # Foreign Keys order = models.ForeignKey(CustomerOrder, on_delete=models.DO_NOTHING) # File Info invoice_pdf = CloudinaryField('file', blank=True, null=True) # General Information invoice_number = models.IntegerField(default=1) invoice_number_text = models.CharField(max_length=100) invoice_date = models.DateField(default=datetime.date.today) invoice_street = models.CharField(max_length=500) invoice_city = models.CharField(max_length=500) invoice_zip = models.CharField(max_length=500) invoice_company_name = models.CharField(max_length=500) invoice_customer_name = models.CharField(max_length=500) invoice_paid = models.BooleanField(default=True) # Financial Information invoice_vat_amount_1 = models.FloatField(default=0) invoice_vat_amount_2 = models.FloatField(default=0) invoice_vat_amount_3 = models.FloatField(default=0) invoice_total_amount_vat_included = models.FloatField(default=0) invoice_total_amount_vat_excluded = models.FloatField(default=0) # Auto Timestamp Generation created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) def __str__(self): return self.invoice_number_text def get_serials(self): if not self.invoice_number_text: starting_day_of_current_year = self.invoice_date.replace(month=1, day=1) ending_day_of_current_year = self.invoice_date.replace(month=12, day=31) max_nb = 1 if not CustomerInvoice.objects.filter( invoice_date__gt=starting_day_of_current_year, invoice_date__lt=ending_day_of_current_year, order__merchant=self.order.merchant, invoice_number__isnull=False, ).order_by("-invoice_date").first( ).invoice_number else CustomerInvoice.objects.filter( invoice_date__gt=starting_day_of_current_year, invoice_date__lt=ending_day_of_current_year, order__merchant=self.order.merchant, invoice_number__isnull=False, ).order_by("-invoice_date").first().invoice_number + 1 serial_number = format(int(max_nb) / 10000000, '.7f')[2:] serial_text = str( str("FCUS-") + str(self.order.merchant.url_tag.upper()) + str("-") + str(self.invoice_date.year) + str(serial_number)) else: serial_text = self.invoice_number_text serial_number = self.invoice_number return serial_text, serial_number def delete_invoice_file(self): self.invoice_file.delete() return
class Image(models.Model): # image = models.ImageField(upload_to=get_image_path) image = CloudinaryField('image', blank=True, null=True)
class Product(ClusterableModel): """ A thing you can buy in stores and our review of it """ draft = models.BooleanField( help_text= 'When checked, this product will only show for CMS-authenticated users', default=True, ) adult_content = models.BooleanField( help_text= 'When checked, product thumbnail will appear blurred as well as have an 18+ badge on it', default=False, ) review_date = models.DateField(help_text='Review date of this product', ) @property def is_current(self): d = self.review_date review = datetime(d.year, d.month, d.day) cutoff = datetime(2019, 6, 1) return cutoff < review name = models.CharField( max_length=100, help_text='Name of Product', blank=True, ) slug = models.CharField(max_length=256, help_text='slug used in urls', blank=True, default=None, editable=False) company = models.CharField( max_length=100, help_text='Name of Company', blank=True, ) product_category = models.ManyToManyField( 'buyersguide.BuyersGuideProductCategory', related_name='product', blank=True) blurb = models.TextField(max_length=5000, help_text='Description of the product', blank=True) url = models.URLField( max_length=2048, help_text='Link to this product page', blank=True, ) price = models.CharField( max_length=100, help_text='Price', blank=True, ) image = models.FileField( max_length=2048, help_text='Image representing this product', upload_to=get_product_image_upload_path, blank=True, ) cloudinary_image = CloudinaryField( help_text='Image representing this product - hosted on Cloudinary', blank=True, verbose_name='image', folder='foundationsite/buyersguide', use_filename=True) meets_minimum_security_standards = models.BooleanField( null=True, help_text='Does this product meet minimum security standards?', ) # Minimum security standards (stars) uses_encryption = ExtendedYesNoField( help_text='Does the product use encryption?', ) uses_encryption_helptext = models.TextField(max_length=5000, blank=True) security_updates = ExtendedYesNoField(help_text='Security updates?', ) security_updates_helptext = models.TextField(max_length=5000, blank=True) strong_password = ExtendedYesNoField() strong_password_helptext = models.TextField(max_length=5000, blank=True) manage_vulnerabilities = ExtendedYesNoField( help_text='Manages security vulnerabilities?', ) manage_vulnerabilities_helptext = models.TextField(max_length=5000, blank=True) privacy_policy = ExtendedYesNoField( help_text='Does this product have a privacy policy?') privacy_policy_helptext = models.TextField( # REPURPOSED: WILL REQUIRE A 'clear' MIGRATION max_length=5000, blank=True) share_data = models.BooleanField( # TO BE REMOVED null=True, help_text='Does the maker share data with other companies?', ) share_data_helptext = models.TextField( # TO BE REMOVED max_length=5000, blank=True) # It uses your... camera_device = ExtendedYesNoField( help_text='Does this device have or access a camera?', ) camera_app = ExtendedYesNoField( help_text='Does the app have or access a camera?', ) microphone_device = ExtendedYesNoField( help_text='Does this Device have or access a microphone?', ) microphone_app = ExtendedYesNoField( help_text='Does this app have or access a microphone?', ) location_device = ExtendedYesNoField( help_text='Does this product access your location?', ) location_app = ExtendedYesNoField( help_text='Does this app access your location?', ) # How it handles privacy how_does_it_share = models.CharField( max_length=5000, help_text='How does this product handle data?', blank=True) delete_data = models.BooleanField( # TO BE REMOVED null=True, help_text='Can you request data be deleted?', ) delete_data_helptext = models.TextField( # TO BE REMOVED max_length=5000, blank=True) parental_controls = ExtendedYesNoField( null=True, help_text='Are there rules for children?', ) child_rules_helptext = models.TextField( # TO BE REMOVED max_length=5000, blank=True) collects_biometrics = ExtendedYesNoField( help_text='Does this product collect biometric data?', ) collects_biometrics_helptext = models.TextField(max_length=5000, blank=True) user_friendly_privacy_policy = ExtendedYesNoField( help_text='Does this product have a user-friendly privacy policy?') user_friendly_privacy_policy_helptext = models.TextField(max_length=5000, blank=True) """ privacy_policy_links = one to many, defined in PrivacyPolicyLink """ worst_case = models.CharField( max_length=5000, help_text= "What's the worst thing that could happen by using this product?", blank=True, ) PP_CHOICES = ( # TO BE REMOVED ('0', 'Can\'t Determine'), ('7', 'Grade 7'), ('8', 'Grade 8'), ('9', 'Grade 9'), ('10', 'Grade 10'), ('11', 'Grade 11'), ('12', 'Grade 12'), ('13', 'Grade 13'), ('14', 'Grade 14'), ('15', 'Grade 15'), ('16', 'Grade 16'), ('17', 'Grade 17'), ('18', 'Grade 18'), ('19', 'Grade 19'), ) privacy_policy_reading_level = models.CharField( # TO BE REMOVED IN FAVOUR OF USER_FRIENDLY_PRIVACY_POLICY choices=PP_CHOICES, default='0', max_length=2, ) privacy_policy_url = models.URLField( # TO BE REMOVED IN FAVOUR OF PRIVACY_POLICY_LINKS max_length=2048, help_text='Link to privacy policy', blank=True) privacy_policy_reading_level_url = models.URLField( # TO BE REMOVED max_length=2048, help_text='Link to privacy policy reading level', blank=True) # How to contact the company phone_number = models.CharField( max_length=100, help_text='Phone Number', blank=True, ) live_chat = models.CharField( max_length=100, help_text='Live Chat', blank=True, ) email = models.CharField( max_length=100, help_text='Email', blank=True, ) twitter = models.CharField( max_length=100, help_text='Twitter username', blank=True, ) updates = models.ManyToManyField('buyersguide.Update', related_name='products', blank=True) # comments are not a model field, but are "injected" on the product page instead related_products = models.ManyToManyField('self', related_name='rps', blank=True, symmetrical=False) # --- if settings.USE_CLOUDINARY: image_field = FieldPanel('cloudinary_image') else: image_field = FieldPanel('image') # List of fields to show in admin to hide the image/cloudinary_image field. There's probably a better way to do # this using `_meta.get_fields()`. To be refactored in the future. panels = [ MultiFieldPanel([ FieldPanel('draft'), ], heading="Publication status", classname="collapsible"), MultiFieldPanel([ FieldPanel('adult_content'), FieldPanel('review_date'), FieldPanel('name'), FieldPanel('company'), FieldPanel('product_category'), FieldPanel('blurb'), FieldPanel('url'), FieldPanel('price'), image_field, FieldPanel('meets_minimum_security_standards') ], heading="General Product Details", classname="collapsible"), MultiFieldPanel( [ FieldPanel('uses_encryption'), FieldPanel('uses_encryption_helptext'), FieldPanel('security_updates'), FieldPanel('security_updates_helptext'), FieldPanel('strong_password'), FieldPanel('strong_password_helptext'), FieldPanel('manage_vulnerabilities'), FieldPanel('manage_vulnerabilities_helptext'), FieldPanel('privacy_policy'), FieldPanel( 'privacy_policy_helptext'), # NEED A "clear" MIGRATION FieldPanel('share_data'), FieldPanel('share_data_helptext'), # DEPRECATED AND WILL BE REMOVED FieldPanel('privacy_policy_url'), FieldPanel('privacy_policy_reading_level'), FieldPanel('privacy_policy_reading_level_url'), ], heading="Minimum Security Standards", classname="collapsible"), MultiFieldPanel([ FieldPanel('camera_device'), FieldPanel('camera_app'), FieldPanel('microphone_device'), FieldPanel('microphone_app'), FieldPanel('location_device'), FieldPanel('location_app'), ], heading="Can it snoop?", classname="collapsible"), MultiFieldPanel([ FieldPanel('how_does_it_share'), FieldPanel('delete_data'), FieldPanel('delete_data_helptext'), FieldPanel('parental_controls'), FieldPanel('collects_biometrics'), FieldPanel('collects_biometrics_helptext'), FieldPanel('user_friendly_privacy_policy'), FieldPanel('user_friendly_privacy_policy_helptext'), FieldPanel('worst_case'), ], heading="How does it handle privacy", classname="collapsible"), MultiFieldPanel([ InlinePanel( 'privacy_policy_links', label='link', min_num=1, max_num=3, ), ], heading="Privacy policy links", classname="collapsible"), MultiFieldPanel([ FieldPanel('phone_number'), FieldPanel('live_chat'), FieldPanel('email'), FieldPanel('twitter'), ], heading="Ways to contact the company", classname="collapsible"), FieldPanel('updates'), FieldPanel('related_products'), ] @property def votes(self): return get_product_vote_information(self) @property def numeric_reading_grade(self): try: return int(self.privacy_policy_reading_level) except ValueError: return 0 @property def reading_grade(self): val = self.numeric_reading_grade if val == 0: return 0 if val <= 8: return 'Middle school' if val <= 12: return 'High school' if val <= 16: return 'College' return 'Grad school' def to_dict(self): """ Rather than rendering products based on the instance object, we serialize the product to a dictionary, and instead render the template based on that. NOTE: if you add indirect fields like Foreign/ParentalKey or @property definitions, those needs to be added! """ model_dict = model_to_dict(self) model_dict['votes'] = self.votes model_dict['slug'] = self.slug model_dict['delete_data'] = tri_to_quad(self.delete_data) # TODO: remove these two entries model_dict['numeric_reading_grade'] = self.numeric_reading_grade model_dict['reading_grade'] = self.reading_grade # model_to_dict does NOT capture related fields or @properties! model_dict['privacy_policy_links'] = list( self.privacy_policy_links.all()) model_dict['is_current'] = self.is_current return model_dict def save(self, *args, **kwargs): self.slug = slugify(self.name) models.Model.save(self, *args, **kwargs) def __str__(self): return str(self.name)
class Profile(TimeStampModel): photo = CloudinaryField(resource_type='image', blank=True, verbose_name=_("Photo de profile")) birthday = models.DateField(blank=True, null=True, verbose_name=_("Date de naissance")) birth_location = models.CharField(max_length=100, blank=True, verbose_name=_('Lieu de naissance')) filiere = models.CharField(max_length=50, verbose_name='Filière', blank=True) promo = models.CharField(max_length=50, blank=True, verbose_name='Promotion') gender = models.CharField(max_length=10, blank=True, choices=(('male', 'Masculin'), ('female', 'Feminin')), verbose_name='Sexe') degree = models.CharField(max_length=100, blank=True, verbose_name='Intitulé du Diplome') in_ensai_year = models.CharField(max_length=10, help_text='Exemple: 2002', verbose_name='Année d\'entrée à l\'ENSAI', blank=True, null=True) out_ensai_year = models.CharField(max_length=10, help_text='Exemple: 2005', verbose_name='Année de sortie', blank=True, null=True) situation = models.CharField(max_length=100, blank=True, verbose_name='Situation actuelle') entreprise = models.CharField( max_length=100, blank=True, verbose_name='Nom de l\'entreprise qui vous emploi') entreprise_link = models.URLField( verbose_name='Lien de l\'entreprise (url)', blank=True, help_text='https://www.monentreprise.com') poste = models.CharField(max_length=100, blank=True, verbose_name='Poste occupé') postes = models.TextField( verbose_name= 'Les postes precédements occupés et les entreprises respectives', help_text= 'Renseigner sous le format (post, entreprise) séparer par un point-virgule(;)', blank=True) phone = models.CharField(max_length=20, blank=True, verbose_name='Numéro de téléphone') waiting = models.TextField( blank=True, verbose_name='Quelles sont vos attentes du groupe ALUMNI ENSAI?') contribution = models.TextField( blank=True, verbose_name= 'Que pouvez vous apporter comme contribution pour que vos attentes soient comblées?' ) region = models.CharField(max_length=50, blank=True, verbose_name='Région') portrait_visible = models.BooleanField(verbose_name='Portrait visible', default=True) user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) objects = ProfileManager() def full_name(self): return self.user.first_name + ' ' + self.user.last_name def get_postes(self): return self.postes.split(';') def __str__(self): return str(self.user.email)
class Photo(models.Model): """ A class thaat determines how photos will be saved into the database """ name = models.CharField(max_length=244) description = models.TextField() # location = models.ForeignKey(Location) categories = models.ManyToManyField(Category) post_date = models.DateTimeField(auto_now_add=True) image = CloudinaryField('image') def __str__(self): """ String representation """ return self.name def save_photo(self): """ A method to save the photo """ return self.save() @classmethod def copy_url(cls, id): photo = cls.objects.get(id = id) pyperclip.copy(photo.image.url) @classmethod def show_all_photos(cls): """ A method to return all photos posted in order of the most recent to oldest """ return cls.objects.order_by("post_date")[::-1] @classmethod def show_random_photo(cls): """ A method which returns a random photo """ all_photos = cls.show_all_photos() random_id = random.randint(1, len(all_photos)) return cls.objects.get(id = random_id) @classmethod def delete_photo(cls, id): """ A method to delete an object """ return cls.objects.filter(id = id).delete() @classmethod def get_photo_by_id(cls, id): """ A method to get a photo based on its id """ return cls.objects.filter(id = id)[0] @classmethod def search_photo_by_category(cls, search): """ A method to return all photos that fall under a certain catergory """ return cls.objects.filter(categories__name__icontains = search) @classmethod def filter_by_location(cls, id): """ A method to filter all photos based on the location in which they were taken """ return cls.objects.filter(location__id = id)
def test_formfield(self): c = CloudinaryField('image') form_field = c.formfield() self.assertTrue(isinstance(form_field, CloudinaryFileField))
class DevelopmentTechnology(models.Model): name = models.CharField(max_length=50) image = CloudinaryField('image', null=True) def __unicode__(self): return self.name
def test_value_to_string(self): c = CloudinaryField('image') c.set_attributes_from_name('image') image_field = Poll.objects.get(question="with image") value_string = c.value_to_string(image_field) self.assertEqual("image/upload/v1234/{name}.jpg".format(name=API_TEST_ID), value_string)
class Image(models.Model): image = CloudinaryField('image', null=True) @property def full(self): return self.image.public_id
def test_to_python(self): c = CloudinaryField('image') res = CloudinaryResource(public_id='sample', format='jpg') # Can't compare the objects, so compare url instead self.assertEqual(c.to_python('sample.jpg').build_url(), res.build_url())
class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = CloudinaryField('image') def __str__(self): return f'{self.user.username} Profile'
def test_formfield(self): c = CloudinaryField('image') for_field = c.formfield() self.assertTrue(isinstance(for_field, CloudinaryFileField))
class Quizzer(models.Model): uuid = models.CharField(default=uuid.uuid4, editable=False, max_length=1028) # for postgres user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_quiz') title = models.CharField(max_length=250, null=False, unique=True) slug = models.SlugField(null=True, blank=True) bg_pic = CloudinaryField( 'bg_pic') # default='def.png', upload_to='quiz_pic' reattempt = models.BooleanField(default=True, verbose_name='Allow Reattempt') private = models.BooleanField(default=False, verbose_name='Make private') tags = TaggableManager(through=UUIDTaggedItem) objects = models.Manager() #default manager # custom_objects=CustomQueryManager() @property def user_quizzes(self): # Quizzes By this User return self.user.user_quiz.count() def __str__(self): return self.title @property def all_question(self): #all questions of the quiz return self.quizz_question.all() @property def all_tags(self): # all tags of this quiz return [i.name for i in self.tags.all()] @property def attempters(self): # numbers of users atempted this quiz return self.score_quiz.count() def user_tags(self): # unique tags used ny the creator g = [] for i in self.user.user_quiz.all(): for j in i.all_tags: if j not in g: g.append(j) return g @property def question_count(self): # number of questions on the quiz return self.quizz_question.count() def all_attempters(self): return self.score_quiz.all() def get_absolute_url(self): return reverse('quiz:quizz', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Quizzer, self).save(*args, **kwargs) # class Usertags(models.Model): '''works with signals but upgrade to python 3.9 for JSOn Field or update sql'''