我刚刚部署了我的第一个Django应用程序,该应用程序是我所工作的小型公司的跟踪工作,费用的工具,并且有一个博客供客户查看。部署站点后,我意识到用于编辑作业模型的页面没有显示作业信息,而是显示了新实例的空白表格。提交编辑后,它会创建一个新实例,而不是更改要编辑的当前作业。通过管理控制台可以很好地进行编辑,但是我无法弄清楚为什么编辑页面不起作用。
我尝试调整视图功能以编辑作业,删除迁移和数据库以及重新迁移,但无济于事。
views.py
def job_edit(request, pk):
if request.user.is_authenticated:
job = get_object_or_404(Job, pk=pk)
if request.method == "POST":
form = JobForm(request.POST, request.FILES)
if form.is_valid():
job = form.save(commit=False)
job.author = request.user
job.last_updated = timezone.now()
job.image0 = form.cleaned_data['image0']
job.image1 = form.cleaned_data['image1']
job.image2 = form.cleaned_data['image2']
job.image3 = form.cleaned_data['image3']
job.save()
messages.success(request, 'Job updated successfully')
return redirect('job_detail', pk=job.pk)
else:
form = JobForm()
return render(request, 'job_edit.html', {'form': form})
else:
return render(request, 'job_edit.html')
forms.py
class JobForm(forms.ModelForm):
foreman = forms.ChoiceField(choices=FOREMEN, required=True)
status = forms.ChoiceField(choices=JOB_STATUS, required=True)
zip = forms.IntegerField(validators=[MinValueValidator(00000), MaxValueValidator(99999)])
class Meta:
model = Job
fields = ('title', 'foreman', 'crew_size', 'status', 'text', 'truck', 'trailer', 'service', 'client_name', 'client_phone', 'client_email', 'client_source', 'estimated_days', 'schedule_date', 'address', 'town', 'state', 'zip', 'image0', 'image1', 'image2', 'image3')
答案 0 :(得分:2)
如果您使用ModelForm
编辑现有记录,则应将现有记录传递给表单。
# When rendering the form on a GET
# This will populate the form with the jobs current data
form = JobForm(instance=job)
# When the form has been submitted
form = JobForm(request.POST, request.FILES, instance=job)