3

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?

4
  • You can programm your own save() method into your form. Commented Apr 8, 2014 at 11:20
  • So, I have to check if the image is provided, and then decide whether to save it or not? Commented Apr 8, 2014 at 11:53
  • exactly, if there is an empty value send by your form, just ignore it, else set the send value... Commented Apr 8, 2014 at 12:31
  • why did you overwrite the avatar field in your form ? Commented Apr 24, 2017 at 11:40

4 Answers 4

0
avatar = models.ImageField(verbose_name='Avatar',upload_to='images/profile_pics',null=True) 

removing blank=True should solve it

Sign up to request clarification or add additional context in comments.

Comments

0

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) 

Comments

0

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.

Comments

0
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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.