我刚刚部署了我的第一个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')发布于 2019-07-09 02:01:21
如果使用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)https://stackoverflow.com/questions/56944247
复制相似问题