5

I am learning django with the book django2 by example, and i am building a social media website that user can share image in the website. There is one function completed, it is using a bookmarks tool(javascript) to load the image from other website then upload to my website, but i want to create one more function on th basic of that. I want to let user upload the image in the local host.

models.py

class Image(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='images_created', on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200,blank=True)
    url = models.URLField()
    image = models.ImageField(upload_to='images/%Y/%m/%d')
    description = models.TextField(blank=True)
    created = models.DateField(auto_now_add=True,db_index=True)
    users_like = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='images_liked', blank=True)
    total_likes = models.PositiveIntegerField(db_index=True, default=0)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        super(Image, self).save(*args, **kwargs)

    def get_absolute_url(self):
            return reverse('images:detail', args=[self.id, self.slug])

When i write a url like that"file://localhost/D:%5C1stu%5Cu=1422291456,3249037427&fm=173&app=25&f=JPEG.jpg" The django website remind me that "(Hidden field url) Enter a valid URL." Could anyone tell me that Can URLField() in django load a localhost path?And how?

ZHU LIU
  • 71
  • 4

1 Answers1

2

Yes, You can but the reason you get error is django URLfield use url validator to validate urls, You can check it on this link: https://docs.djangoproject.com/en/3.0/ref/validators/#django.core.validators.URLValidator

Now, the URL Validator use ['http', 'https', 'ftp', 'ftps'] by default if doesn't provide any validation for it that is reason the you get error, you use "file". If you have to use localhost url give validation to url field.

Visit to this link: Django URLField with custom scheme

I hope this will be helpful to you.