0

I am creating a webpage for users to upload images and share images

Here is the screenshot of the detail page of an image (without error, before I added lineno_of_download += 1 in models.py) enter image description here What I wanted here is: **when a I clicked downloadbutton on ImageDetail.html, the Image will be stored to my computer and the No. of downloads: 0 will change to No. of downloads: 1

here is my code:

views.py:

class ImageDetailView(generic.DetailView):
    model = Image
    template_name='ImageApp/ImageDetail.html'

ImageDetail.html:

<a href="{{ image.get_img_url }}">Download</a>   //this is for someone to click 'download'
<p>The no. of Downloads of this image: {{ image.no_of_download }}</p>   // to show the total no. of downloads of this specific image

models.py:

class Image(models.Model):
    category = models.ForeignKey(Category,  blank=True, null=True, on_delete=models.DO_NOTHING)
    tag = models.ManyToManyField(Tag, blank=True)
    title = models.CharField(max_length=100)
    photo = models.FileField()
    description = models.CharField(max_length=1000)
    no_of_download = models.IntegerField(default=0)

    def __str__(self):
        return self.title + '-' + self.description

    def get_absolute_url(self):
        return reverse('imagebank:image-detail', kwargs={'pk': self.pk})

    def get_img_url(self):
        no_of_download += 1
        return self.photo.url

ERROR: When I redirect to ImageDetail.html, there is this error message: local variable 'no_of_download' referenced before assignment

note that I DON'T want to use JavaScript here for some reason

ycsjose
  • 27
  • 7

1 Answers1

0

not sure I follow everything you're doing, but here's the first fix:

in get_img_url, change no_of_download += 1 to self.no_of_download += 1

that will at least fix your exception.

Then your next step will be to call save() on the Image instance so that the change to no_of_download get's persisted...but that's a different question

Chris Curvey
  • 9,738
  • 10
  • 48
  • 70