Reputation: 35
So, that's the problem: I currently have a model:
class UserData(models.Model): avatar = models.ImageField(verbose_name='Avatar',upload_to='images/profile_pics',blank=True,null=True) doc_type = models.CharField(verbose_name='Document type',max_length=1,default='0')
And a form:
class UserCreationForm(forms.ModelForm): avatar = forms.ImageField(label='Avatar',required=False, error_messages = {'invalid':"Images only"}, widget=forms.FileInput) class Meta: model = UserData
So, the problem occurs when the user tries to edit his data. When no image is provided, the current image path in the db overwrites with the empty string. Is there any way to solve that problem?
Upvotes: 3
Views: 1076
Reputation: 1
from django.db import connection
@login_required
def card_photo_remove(request, pk): card = get_object_or_404(Cards, cardid=pk)
if card.sponsorimage:
default_storage.delete(card.sponsorimage.path)
with connection.cursor() as cursor:
cursor.execute("UPDATE Cards SET SponsorImage=NULL WHERE cardid=%s", [pk])
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Here u can see exaple how to write manyal SQL code. It worked to me perfectly!
Upvotes: 0
Reputation: 25
Remove both blank and null
equal to True
blank=True
Allows the field to be empty
null=True
Allows the empty data to be saved in database
so you can choose which one will work for you the best.
Upvotes: 0
Reputation: 949
You can solve the problem by making image field required.
avatar = forms.ImageField(label='Avatar', required=True, error_messages={'invalid':"Images only"}, widget=forms.FileInput)
Upvotes: 0
Reputation: 165
avatar = models.ImageField(verbose_name='Avatar',upload_to='images/profile_pics',null=True)
removing blank=True
should solve it
Upvotes: 0