You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于现有记录为模板创建新记录的Django实现方案问询

实现方案及代码修正

核心问题解答

这种实现并非ListView到UpdateView的流程,本质是在CreateView中复用已有记录的字段值作为表单初始值,最终执行的是新建记录操作——和UpdateView的更新逻辑完全不同,UpdateView是针对已有记录修改,而这里是基于模板创建全新记录。

代码修正步骤

1. URL配置(urls.py)

无需修改路径,只需确保后续跳转时传递记录ID作为GET参数:

path('create/movie', movies_create.as_view(), name='movies_create'),

2. 列表页模板(movies_list.html)

  • 修复循环变量错误:ListView默认上下文是object_list或模型名小写_list(即movies_list),原代码{% for movie in movie %}会引发循环异常
  • 跳转链接携带要复制的记录ID作为GET参数copy_id
<table>
  <tr>
   <th>No.</th>
   <th>Title</th>
  </tr>
  {% for movie in movies_list %}
  <tr>
    <td>{{ forloop.counter }}</td>
    <td><a href="{% url 'movies_create' %}?copy_id={{ movie.id }}">{{ movie.title }}</a></td>
  </tr>
  {% endfor %}
</table>

3. 创建视图(Views.py)

  • 移除未定义的MyFormClass,直接复用CreateView默认的ModelForm
  • 通过get_initial方法获取选中记录的字段值,作为表单初始值
  • 修正form_valid逻辑,调用父类方法完成保存并跳转至指定页面
from django.shortcuts import get_object_or_404

class movies_list(LoginRequiredMixin, ListView):
    model = movies
    template_name = 'movies_list.html'

class movies_create(LoginRequiredMixin, CreateView):
    model = movies
    fields = ['title', 'fk_producer']
    template_name = 'movies_create.html'
    success_url = '/path/to/movies/list'  # 替换为你的列表页实际URL,或使用reverse_lazy生成

    def get_initial(self):
        initial = super().get_initial()
        copy_id = self.request.GET.get('copy_id')
        if copy_id:
            # 获取要复制的模板记录,无效ID返回404
            template_movie = get_object_or_404(movies, id=copy_id)
            # 将模板记录的字段值设为表单初始值
            initial['title'] = template_movie.title
            initial['fk_producer'] = template_movie.fk_producer
        return initial

    def form_valid(self, form):
        form.instance.fk_user = self.request.user
        return super().form_valid(form)

4. 创建页模板(movies_create.html)

移除重复的<form>标签和多余的</fieldset>标签:

{% load static %}
{% block content %}
{% load crispy_forms_tags %}
<form method="POST">
    {% csrf_token %}
    <div>{{ form|crispy }}</div>
    <button class="btn btn-outline-info" type="submit">Post</button>
</form>
{% endblock content %}

补充说明

  • 模型类名建议遵循PEP8规范改为Movies(首字母大写),同时修正所有相关引用
  • get_object_or_404用于处理无效ID的情况,避免直接调用get()抛出异常
  • 如果需要复制更多字段,只需在get_initial方法中添加对应字段的初始值即可

内容的提问来源于stack exchange,提问作者Game Analysis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 20:55:17