W
W
Wiki-fan2015-03-23 11:30:01
Django
Wiki-fan, 2015-03-23 11:30:01

How to rename images on upload?

The model is like this:

class Picture(models.Model):
  ID = models.IntegerField(primary_key=True)
  name = models.CharField(max_length=256)
  pic_file = models.ImageField(upload_to='media/images')

The form is like this:
class PictureUploadForm(forms.ModelForm):
  name = forms.CharField(max_length=256, help_text="Enter picture name:")
  pic_file = forms.ImageField(help_text='Choose your file:')
  
  class Meta:
    model = Picture
    fields = ('name', 'pic_file',) #Ещё один вопрос мимоходом. Здесь указываются поля, содержимое которых переносится в модель автоматически, так?

Looks like this, just in case:
def add_picture(request):
  if request.method == 'POST':
    form = PictureUploadForm(request.POST, request.FILES)

    if form.is_valid():
      form.save(commit=True)
    else:
      print form.errors
  else:
    form = PictureUploadForm()

  return render(request, 'add_picture.html', {'form': form})

The picture is saved with the same name it had when it was loaded. That is, as a user. And I need it to be given a name of the form <ID>.<extension>, because my ID is primary_key and does not repeat. How to do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yuri Shikanov, 2015-03-23
@dizballanze

Usually use the upload_to parameter of the FileField field from which ImageField is inherited.
But, because you need to save the instance first, in order to know its ID (in case of adding), you will have to use the post_save model signal in the handler of which to rename the file and save the field value in the database.

U
un1t, 2015-03-23
@un1t

You need to make your own FileField or ImageField and override the generate_filename method
https://github.com/django/django/blob/master/djang...
You can get to the model, respectively, through self.instance.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question