gpt4 book ai didi

python-3.x - 如何在不覆盖当前记录的情况下预填充和保存 Django 模型记录?

转载 作者:行者123 更新时间:2023-12-04 08:40:17 25 4
gpt4 key购买 nike

我有一个表单,我想用用户以前的输入来预填充。我用了 Form(instance = object)代码来做到这一点。但是,在用户提交表单后,之前的表单条目会被新条目更新。我不希望那样,相反,我希望它创建一个不同的实例,以便跟踪更改历史记录。有什么方法可以做到这一点,同时仍然能够预先填写表格?
查看.py

from django.shortcuts import render, redirect
from .models import Topic, Entry
from .forms import TopicForm, EntryForm

def edit_entry(request, entry_id):
entry = Entry.objects.get(id = entry_id)
topic = entry.topic

if request.method != 'POST':
# Initial request; pre-fill for with the current entry.
form = EntryForm(instance = entry)

else:
# POST data submitted.
form = EntryForm(instance = entry, data = request.POST)
if form.is_valid():
form.save()
return redirect('learning_logs:topic', topic_id = topic.id)

context = {'entry': entry, 'topic': topic, 'form': form}
return render(request, 'learning_logs/edit_entry.html', context)
表格.py
from django import forms
from .models import Topic, Entry

class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['text']
labels = {'text':''}

class EntryForm(forms.ModelForm):
class Meta:
model = Entry
fields = ['text']
labels = {'text':''}
widgets = {'text': forms.Textarea(attrs = {'cols': 80, 'spellcheck':True})}
模型.py
from django.db import models
from django.contrib.auth.models import User

class Topic(models.Model):
text = models.CharField(max_length = 200)
date_added = models.DateTimeField(auto_now_add = True)
owner = models.ForeignKey(User, on_delete = models.CASCADE)

class Entry(models.Model):
topic = models.ForeignKey(Topic, on_delete = models.CASCADE)
text = models.TextField()
date_added = models.DateTimeField(auto_now_add = True)

最佳答案

可以设置主键.pk的条目 None ,这样它将创建一个新记录:

from django.shortcuts import render, redirect
from .models import Topic, Entry
from .forms import TopicForm, EntryForm

def edit_entry(request, entry_id):
entry = Entry.objects.get(id = entry_id)
topic = entry.topic

if request.method != 'POST':
# Initial request; pre-fill for with the current entry.
form = EntryForm(instance=entry)

else:
# POST data submitted.
entry.pk = None # ← set .pk entry to None
form = EntryForm(request.POST, instance=entry)
if form.is_valid():
form.save()
return redirect('learning_logs:topic', topic_id = topic.id)

context = {'entry': entry, 'topic': topic, 'form': form}
return render(request, 'learning_logs/edit_entry.html', context)

关于python-3.x - 如何在不覆盖当前记录的情况下预填充和保存 Django 模型记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64600322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com