我正在尝试使用文件上传来执行表单。即使我在表单中选择了一个文件,我也“需要这个字段”。以下是我的代码。 它曾经工作过一次,我不知道它为什么突然不起作用。谢谢你。
模型
from django.db import models
from django.contrib.auth.models import User
from time import time
def get_upload_file_name(instance, filename):
return "uploaded_files/%s_%s" % (str(time()).replace('.', '_'), filename)
# Create your models here.
class UserProfile(models.Model):
user = models.OneToOneField(User)
contact_number = models.CharField(max_length=10)
tag_id = models.CharField(max_length=20)
layout = models.FileField(upload_to=get_upload_file_name)
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
表格
from django import forms
from models import UserProfile
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('contact_number','tag_id', 'layout')
查看
@login_required
def user_profile(request):
if request.method == 'POST' and request.is_ajax():
form = UserProfileForm(request.POST, request.FILES,instance=request.user.profile)
if form.is_valid():
form.save()
#return HttpResponseRedirect('/accounts/loggedin')
return HttpResponse("Update success")
else:
#return HttpResponseRedirect('/accounts/loggedin')
return HttpResponse("Update error")
else:
user = request.user
profile = user.profile
form = UserProfileForm(instance=profile)
args = {}
args.update(csrf(request))
args['form'] = form
args['full_name'] = request.user.username
return render_to_response('profile.html', args)
profile.html
<div align = "center">
<h2 >Profile</h2>
<form id="profile_form" method="POST" action="/accounts/profile/" enctype="multipart/form-data">
{% csrf_token %}
<table>
<tbody>
<tr>
<td>Name:</td>
<td>{{full_name}}</td>
</tr>
<tr>
<td>Tag ID</td>
<td>{{form.tag_id}}</td>
</tr>
<tr>
<td>Contact number</td>
<td>{{form.contact_number}}</td>
</tr>
<tr>
<td>Layout</td>
<td>{{form.layout}}</td>
</tr>
</tbody>
</table>
<input type="submit" id="update" value="Update" />
</form>
<DIV id="saved"></DIV>
</div>