0

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

设置.py

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

模型.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')
4

1 回答 1

1

我确实在您的视图中看到了很多不必要的代码,您在视图中主要需要做的事情如下:

    # ...
    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'
    # ...
于 2016-01-09T01:39:47.117 回答