pythondjangodjango-formsdjango-uploads

Django cant upload image


I am trying to add avatar to my model, but uploading dosent work.

settings.py

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

models.py

class Casting(models.Model):
...
casting_picture = ImageField(upload_to='/media/photos')

template casting.html

there a lot of fields, so in short:

  <form method="post">
    ...
    {{form.casting_picture}}
  </form>

forms.py (didnt added anything here, may be thats a problem...)

class CastingForm(forms.ModelForm):
    class Meta:
        model = Casting
        exclude = ['availability', 'castweight', 'userFavorites', 'typos', 'applicants']

views.py (didnt added anything here, may be thats a problem...)

def createCasting(request):
    Ext=request.user    
    if Ext.is_authenticated():
        isemployer = Ext.isempl
        if isemployer == 1: 
            tpg=1
            form = CastingForm(request.POST or None)
            typoformset = modelformset_factory(Typo,form=TypoForm,extra=tpg)
            formset = typoformset(queryset=Typo.objects.none())
            context = {'form': form, 'formset': formset}
            if request.method == "POST":
                form = CastingForm(request.POST)
                formset=typoformset(request.POST,queryset=Typo.objects.none())
                if form.is_valid() and formset.is_valid():
                    mainform = form.save(commit=False)    
                    for f_form in formset:                       
                        typofo=f_form.save()                     
                        mainform.save()                   
                        mainform.typos.add(typofo)
                    mainform.save()
                    context = ({'title': u'created'})
                    return render(request, 'app/successpage.html', context)
            return render(request, "app/createCasting.html",context)
        else:
            return redirect('noempl')
    else:
        return redirect('noauth')

Solution

  • I really see lot of unnecessary code in you views, what your mainly need to do in you view is the following:

        # ...
        form = CastingForm(request.POST, request.FILES) # request.FILES contains the uploaded files
        if form.is_valid():
           Casting.objects.create(**form.cleaned_data)
        else:
           # handels errors in 'form.errors'
        # ...