У меня был пост React Axios, работающий с текстовыми полями, но сейчас я пытаюсь добавить поле изображения в мою модель.
Вот моя новая модель с полем изображения:
def get_image_path(instance, filename):
return os.path.join('posts', str(instance.author), filename)
class TripReport(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
countries = models.ManyToManyField(Country, blank=False, related_name='trip_countries')
title = models.CharField(max_length=100)
content = models.TextField()
image = models.ImageField(upload_to=get_image_path, null=True, blank=False)
date_posted = models.DateTimeField(default=timezone.now)
slug = models.SlugField(max_length=12, unique=True, blank=True)
favoriters = models.ManyToManyField(User, related_name='favoriters')
Я извлекаю файл из своей формы следующим образом:
e.target.image.files[0]
, который регистрирует объект файла следующим образом:
{ name: "DSCF6638.JPG", lastModified: 1340012616000, webkitRelativePath: "", size: 5395895, type: "image/jpeg" }
, когда я его консоль регистрирую.
Я добавил переменную image в свой запрос POST в axios:
export const postTripReport = (author, title, content, countries, image) => {
const token = localStorage.getItem('token');
return dispatch => {
dispatch(postTripReportsPending());
axios.post(
'http://localhost:8000/api/v1/reports/',
{
title: title,
content: content,
author: author,
countries: countries,
image: image
},
{headers: { 'Authorization': `Token ${token}`}}
)
.then(response => {
dispatch(postTripReportsFulfilled(response.data));
})
.catch(err => {
dispatch(postTripReportsRejected());
dispatch({type: "ADD_ERROR", error: err});
})
}
}
Я новичок в этом, поэтому я не уверен, как форма в настоящее время кодируется.Это простой ввод:
<input
name='image'
accept="image/*"
id="flat-button-file"
multiple={false}
type="file"
/>
Я пытался добавить заголовки multipart / forms-data в запрос axios, но затем он сказал, что файл не был загружен и что все остальные поля были пустыми,Спасибо!