我正在尝试为我的模型添加头像,但上传剂量工作。
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
有很多领域,所以简而言之:
<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')
答案 0 :(得分: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'
# ...