Django 无法上传图片

Django cant upload image

我正在尝试将头像添加到我的模型中,但正在上传代理工作。

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')

模板casting.html

有很多字段,所以简而言之:

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

forms.py(这里没有添加任何内容,可能是问题所在...)

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

views.py(这里没有添加任何内容,可能是问题所在...)

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')

我真的在你的视图中看到了很多不必要的代码,你主要需要在你的视图中做以下事情:

    # ...
    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'
    # ...