首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django模型编辑页面创建新模型,而不是编辑当前模型。

Django模型编辑页面创建新模型,而不是编辑当前模型。
EN

Stack Overflow用户
提问于 2019-07-09 01:22:23
回答 1查看 168关注 0票数 0

我刚刚部署了我的第一个Django应用程序,这是为我工作的小公司跟踪工作,费用,它有一个博客供客户查看。在部署站点之后,我意识到编辑作业模型的页面没有显示作业的信息,而是一个新实例的空白表单。提交编辑时,它会创建一个新实例,而不是更改要编辑的当前作业。编辑通过管理仪表板运行得很好,但是我不知道为什么编辑页面不能工作。

我试着调整视图函数,以编辑作业、删除迁移和数据库以及重新迁移,所有这些都没有效果。

views.py

代码语言:javascript
复制
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

代码语言:javascript
复制
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')
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-09 02:01:21

如果使用ModelForm编辑现有记录,则应将现有记录传递给表单。

代码语言:javascript
复制
# 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)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56944247

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档