Search code examples
pythondjangocloudinary

Django - how to make a CloudinaryField not mandatory and how to allow user to delete their uploaded image?


Hej, I am just beginning to learn Django and I want my users to be able to upload a profile picture, so I extended the User model with a Profile model, however, so far I have not figured out how to make the image upload non-mandatory. And when the user has added a picture, I would like them to be able to remove it as well.

Screenshot - Not able to Submit without adding file

Screenshot - Not able to remove the added file

models.py

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField()
profile_image = CloudinaryField('profile_image')

def __str__(self):
    return self.user.username

forms.py

class ProfileForm(ModelForm):
class Meta:
    model = Profile
    fields = ('bio', 'profile_image',)

views.py

@login_required(login_url='login')
def createPost(request):
form = PostForm()

if request.method == "POST":
    form = PostForm(request.POST, request.FILES)
    # request.FILES necessary so that file is submitted
    # also required to add enctype to the form
    if form.is_valid():
        post = form.save(commit=False)
        post.author = request.user
        post.save()
        return redirect('home')

context = {'form': form}
return render(request, 'my8gag/post_form.html', context)

Couldn't find anything about this in the documentation or here on SO, so would appreciate any kind of help/hints! Thanks in advance.


Solution

  • Allow the field to be null

    class Profile(models.Model):
      user = models.OneToOneField(User, on_delete=models.CASCADE)
      bio = models.TextField()
      profile_image = CloudinaryField('profile_image', null=True, default=None, blank=True)
    
      def __str__(self):
        return self.user.username