Django.fun

Problem in uploading image from form in django

I am trying to upload image from django form but it is not taking any image. It shows no file chosen. I have done all media setting in settings.py and urls.py. Still unable to upload image.

settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media/')

urls.py

urlpatterns+=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Also, I tried by using FileField in models.py

models.py

class Shop(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    name = models.CharField(max_length=255)
    image = models.ImageField(upload_to='profile/',default='/profile/my.jpg')
    phone = models.CharField(max_length=10)
    shop_code = models.CharField(max_length=10,null=True,blank=True)

forms.py

class ShopForm(forms.ModelForm):

    class Meta:
        model = Shop
        exclude = ['user']
        fields = ['name','image','phone']


        widgets = {
            'name':forms.TextInput(attrs={'class':'form-control'}),
            'image':forms.FileInput(attrs={'class':'form-control'}),
            'phone':forms.TextInput(attrs={'class':'form-control'}),          
        }

views.py

def create_shop(request):

    if request.method == "POST":
        form = ShopForm(request.POST or request.FILES)

        if form.is_valid():
            shop = form.save(commit=False)
            shop.user = request.user
            shop.shop_code = get_random_string(8)
            shop.save()
            return redirect('shop_profile_info')

    else:
        form = ShopForm()

    context = {

        'form':form

    }

    return render(request,'shop_create.html',context)

shop_create.html

<form method="POST" enctype="multipart/form-data">
   {% csrf_token %}
    
   {{ form }}
                            
                            
   <input type="submit" value="Submit" class="btn btn-dark mt-4">
</form>

Answers: 0