Answer the question
In order to leave comments, you need to log in
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')
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',) #Ещё один вопрос мимоходом. Здесь указываются поля, содержимое которых переносится в модель автоматически, так?
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})
Answer the question
In order to leave comments, you need to log in
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question