About Lesson
Uploading Files in Django
To allow users to upload files through forms, you need to handle both the form and the file storage in your settings.
- Model with FileField:
- Form for File Upload:
- Handling File Upload in Views: In
views.py
, modify the view to handle the uploaded file:def upload_profile(request): if request.method == 'POST' and request.FILES: form = ProfileForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('profile') else: form = ProfileForm() return render(request, 'upload_profile.html', {'form': form})
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to='avatars/')
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['avatar']
Join the conversation