Я пытаюсь загрузить изображение, используя django необработанную форму. Как я могу получить изображение из формы? Чтобы я мог присвоить его модели и сохранить? Есть ли такой метод, как cleaned_data.get()
для изображений?
models.py
class University(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
name = models.CharField(max_length=255)
about = models.TextField(max_length = 2083)
facts = models.TextField(max_length=2083, blank=True, null=True)
type_of_university = models.CharField(max_length = 20, choices = UNIVERSITY_TYPE_CHOICES)
logo = models.ImageField(upload_to = 'logo', blank=True, null=True)
cover_photo = models.ImageField(upload_to= 'cover_photo', blank=True, null=True)
def __str__(self):
return self.name
forms.py
class UniversityForm(forms.Form):
name = forms.CharField(max_length=255)
about = forms.CharField()
facts = forms.CharField(required=False)
type_of_university = forms.ChoiceField(choices=UNIVERSITY_TYPE_CHOICES)
logo = forms.ImageField(required=False)
cover_photo = forms.ImageField(required=False)
views.py
class UniversityFormView(View):
def get(self, *args, **kwargs):
main_form = UniversityForm()
context = {
'main_form':main_form
}
return render (self.request, 'university/initial_form.html', context)
def post(self, *args, **kwargs):
main_form = UniversityForm(self.request.POST, self.request.FILES)
context = {
'main_form': main_form
}
if main_form.is_valid():
name = main_form.cleaned_data.get('name')
about = main_form.cleaned_data.get('about')
facts = main_form.cleaned_data.get('facts')
type_of_university = main_form.cleaned_data.get('type_of_university')
logo = main_form.cleaned_data.get()'logo')
cover_photo = main_form.cleaned_data.get('cover_photo')
university = University(
user = self.request.user,
name = name,
about = about,
facts = facts,
type_of_university = type_of_university,
logo = logo,
cover_photo = cover_photo
)
university.save()
messages.success(self.request, "Form submitted successfully!")
return redirect('address_form')
else:
messages.warning(self.request, "Something went wrong!")
return redirect('university_form')
return render (self.request, 'university/initial_form.html', context)
Спасибо!