2
我寫了文件上傳的代碼,但它沒有顯示在我的目標頁面上。 請幫我編輯我的代碼或建議。 字段的其餘顯示而不是文件中的字段 我的models.pyDjango文件上傳不顯示
class Help(models.Model):
researcher = models.CharField(max_length=100)
study = models.CharField(max_length=500)
date = models.DateTimeField(auto_now_add=True)
document = models.FileField(upload_to='documents/', null=True, blank=True)
forms.py
from django import forms
from .models import Help
from django.forms import ModelForm
class AboutHelp(forms.ModelForm):
class Meta:
model = Help
fields = '__all__'
源頁面
<form action="{% url 'lazer.views.about_experiment' exp.link_name %}" method="POST" name="form">
{% csrf_token %}
<label>Researcher Name(s):
<input type="text" name="researcher"><br>
<lable>Study Summary
<textarea rows="10" cols="50" placeholder="Start typing..." maxlength="500" class="form-control" name="study"></textarea>
<br>
<label>Upload your IRB approval letter:
<input type ="file" id="irb-file" class="file_input" name="document"></label>
<br>
<input type = "submit" value="Submit" class="btn btn-primary" />
</form>
views.py
def about_experiment(request, ex_link_name):
researcher = None
study = None
posts = None
exp = get_object_or_404(Experiment,link_name = ex_link_name)
high_scores = ScoreItem.objects.filter(experiment=exp,active=True)
context = {
'request': request,
'exp':exp,
'high_scores': high_scores,
'awards':AwardItem.objects.filter(experiment=exp,visible=True),
}
if exp.about_file:
context['about_file'] = settings.EXPERIMENT_DIRS+exp.about_file.get_include_path()
return render(request, 'about_experiment.html', context)
if request.method == 'POST':
form = AboutHelp(request.POST, request.FILES)
posts = Help.objects.filter().order_by('-date')[0]
if form.is_valid():
obj = form.save(commit = False)
obj.save()
researcher = form.cleaned_data['researcher']
study = form.cleaned_data['study']
document = form.cleaned_data['document']
else:
form = AboutHelp()
posts = Help.objects.filter().order_by('-date')[0]
return render(request, 'about_experiment.html', {'posts': posts})
return render(request, 'about_experiment.html', {'posts': posts})
目的地頁面
<h4><b>{{ posts.researcher }}</b></h4>
<p>{{ posts.study }}</p>
<p>Uploaded file is : {{ posts.document }}</p>
問題是,每當我刷新我的目標頁面,文件一次又一次地在我的路徑上傳。如何排序? – unknown
提交了一個Web表單後,即使您只是重定向到相同的視圖,也可以使用返回的Django的另一種快捷方式呈現方法HttpResponseRedirect。否則,某些瀏覽器將最終提交表單兩次。但是,您可以使用URL欄進行刷新以避免頁面重新提交。 – Aniket