Django:如何输入外键来保存使用jQuery动态添加表单的表单集?

如何解决Django:如何输入外键来保存使用jQuery动态添加表单的表单集?

我正在使用modelFormsets渲染表单以编辑与页面上的项目相关的注释。 Note模型具有一个与Project模型的实例相关的外键,并且我使用Note模型的现有实例(属于用户项目)渲染表单。正在查看。效果很好。

现在,我正在尝试使用jQuery添加新的客户端表单。我基本上修改了管理数据,并克隆了属于该表单的所有元素,修改了它们的属性,然后将它们插入适当的位置。这也起作用(在前端)。但是,提交时遇到了麻烦。

最初,我只修改了'#id_form-TOTAL_FORMS',但收到一个错误消息:'django.db.utils.IntegrityError: null value in column "project_id" violates not-null constraint.'DETAIL: Failing row contains (63,3,This is the third note,null),其中pk是63(我假设是DB分配的,因为我没有输入任何内容),3是注释编号,“这是第三个注释”是注释文本(我以表格形式写出),并且null当然是项目ID的外键

然后,我也尝试更新'#id_form-INITIAL_FORMS',但是,当我使用添加的新表单提交时,我的formset.is_valid()方法返回false,并且formset.erros包含[{},{},{'id': ['This field is required.]}],我认为这是新行的ID,因为正如我所说,我没有将它传递到任何地方。

我已经阅读了一些有关如何向表单集动态添加表单的问题,但是没有一个问题涉及模型具有外键的情况,因此我在这里有些迷惑。我不知道如何为将从刚刚创建的新表单创建的新实例传递“ project_id”,或者如果我不知道如何传递要创建的新实例的id(pk)会的。

这是我的观点(我知道排序可能不是最好的;我已经做了很多修改)。 请查看评论。

def editor(request,project_id):

    if not Note.objects.filter(project_id=project_id).exists():
        NoteFormset = modelformset_factory(Note,extra=1,fields=('note_text','note_number'),labels={'note_text': (''),'note_number': ('')},widgets={'caption_number':
                                                    NumberInput(attrs={'class': 'disabled','readonly': 'readonly'})})
    
    else:
        NoteFormset = modelformset_factory(Note,extra=0,'readonly': 'readonly'})})

        formset = NoteFormset(queryset
                              =Note.objects.filter(project_id=project_id).order_by('note_number'))

    if request.is_ajax and request.method == POST:
        formset = NoteFormset(request.POST)
        
        if formset.is_valid():
            new_formset = formset.save()
            serialized_formset = serializers.serialize('json',new_formset)
            # This response is not actually being used by ajax
            # because I don't need to update anything
            # in the frontend after updating in the db.  The user input stays there.
            return JsonResponse({'new_formset': serialized_formset})

        else:
            print(formset.errors)

    else:
        return render(request,'NoteProj/editor.html',{'formset': formset})

这是呈现HTML的方式(相关部分)。 请查看评论。

<body>
    <form method="POST" class="note-form">
        <input type="hidden" name="csrfmiddlewaretoken" ...>
        <div class="note-pane">
            <!-- value="2" before adding the new form. Modified with jQuery-->
            <input type="hidden" name="form-TOTAL_FORMS" value="3" id="id_form-TOTAL_FORMS">
            <!-- value="2" before adding the new form. Modified with jQuery-->
            <input type="hidden" name="form-INITIAL_FORMS" value="3" id="id_form-INITIAL_FORMS">
            <input type="hidden" name="form-MIN_NUM_FORMS" value="0" id="id_form-MIN_NUM_FORMS">
            <input type="hidden" name="form-MAX_NUM_FORMS" value="1000" id="id_form-MAX_NUM_FORMS">
            <!-- First form -->
            <p>
                <textarea name="form-0-note_text" cols="70" rows="8" id="id_form-0-note_text">
                This is the first note</textarea>
                <!-- This button is added with jQuery to insert a new note after -->
                <button id="ins-after-0" class="ins-note-after" type="button" value="ins-after-0">
            </p>
            <p>
                <!-- Deleted styles for simplicity-->
                <input type="number" name="form-0-note_number" value="1" class="disabled"
                readonly="readonly" id="id_form-0-note_number">
                <input type="hidden" name="form-0-id" value="60" id="id_form-0-id">
            </p>
            <!-- Second form -->
            <p>
                <textarea name="form-1-note_text" cols="70" rows="8" id="id_form-1-note_text">
                This is the second note</textarea>
                <!-- This button is added with jQuery to insert a new note after -->
                <button id="ins-after-1" class="ins-note-after" type="button" value="ins-after-1">
            </p>
            <p>
                <!-- Deleted styles for simplicity-->
                <input type="number" name="form-1-note_number" value="2" class="disabled"
                readonly="readonly" id="id_form-1-note_number">
                <input type="hidden" name="form-1-id" value="61" id="id_form-1-id">
            </p>
            <!-- Third form. Added with jQuery -->
            <p>
                <textarea name="form-2-note_text" cols="70" rows="8" id="id_form-2-note_text">
                This is the third note</textarea>
                <!-- This button is added with jQuery to insert a new note after -->
                <button id="ins-after-2" class="ins-note-after" type="button" value="ins-after-2">
            </p>
            <p>
                <!-- Deleted styles for simplicity-->
                <input type="number" name="form-2-note_number" value="3" class="disabled"
                readonly="readonly" id="id_form-2-note_number">
                <!-- HERE'S A PROBLEM. I don't know how to determine the pk value to input here -->
                <input type="hidden" name="form-2-id" value="61" id="id_form-2-id">
            </p>
        </div>
    </form>
</body>

总结。没有将要在数据库中创建的行的pk,我无法提交这个新创建的表单,而且我不知道如何确定它。此外,尽管当我不更新#id_form-INITIAL_FORMS时会出现此问题,但我不知道如何输入project_id,它将新行与特定项目相关联。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-