所以我有一个包含多个字段的模型,其中两个是photo
和video
字段。它们都是FileField
类型。我在使用FileField
类型之前已经创建了一个表单,一切正常,但由于某种原因,这次不是。 settings.py
配置正确,因为我可以通过其他表单上传文件。
我可以进入Django管理员并从那里为photo
和video
字段添加图像和视频,然后创建新目录并存储图像和视频,并可以使用没问题。我对这个有点难过。提前谢谢。
这是我的模特:
def get_image_path(instance, filename):
return os.path.join('images', str(instance.id), filename)
def get_video_path(instance, filename):
return os.path.join('videos', str(instance.id), filename)
class User(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField()
photo = models.FileField(upload_to=get_image_path, blank=True)
video = models.FileField(upload_to=get_video_path, blank=True)
def __unicode__(self):
return self.first_name + ' ' + self.last_name + ' - ' + self.email
这是我的表单,ModelForm
:
class UserForm(forms.ModelForm):
class Meta:
model = User
以下是观点:
def index(request):
latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
pollform = PollForm()
choiceform = ChoiceForm()
userform = UserForm()
all_users = User.objects.all()
if request.method == 'POST':
pollform = PollForm(request.POST, request.FILES)
choiceform = ChoiceForm(request.POST)
userform = UserForm(request.POST)
if pollform.is_valid():
pollform.comments = pollform.cleaned_data['comments']
pollform.save()
else:
pollform = PollForm()
if choiceform.is_valid():
choiceform.save()
else:
choiceform = ChoiceForm()
if userform.is_valid():
userform.save()
else:
userform = UserForm()
context = {'latest_poll_list': latest_poll_list, 'pollform': pollform,
'choiceform': choiceform, 'userform': userform, 'all_users': all_users}
return render(request, 'polls/index.html', context)
以下是与ModelForm
相关联的表单:
<form action="{% url 'polls:index' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ userform.as_p }}
<input type="submit" value="Submit">
</form>
答案 0 :(得分:0)
确保enctype="multipart/form-data"
标记中包含form
作为属性。
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<your form code>
</form>
答案 1 :(得分:0)