繁体   English   中英

Django-从模型更新表单中的单个条目

[英]Django - update single entry in form from Model

我知道该主题有一些解决方案,例如

但他们都不对我有用。

该代码有效,但不会更新 ,而是插入一条新记录。

views.py

def group_single(request, name):

# first get the instance i
try:
    i = GroupAnalysis.objects.get(pk=name) # name is unique and pk
except:
    raise Http404('{0} not found'.format(name))

if request.method == 'POST':
    # pass the instance i
    form = GroupAnalysisNameEditForm(request.POST, instance=i)
    if form.is_valid():
        # I tried different things here:
        # 1st:
        form.save()

        # 2nd:
        grp = form.save(commit=False)
        grp.save()

        # 3rd:
        new_name = form.cleaned_data["grp_ana"]
        instance = form.save(commit=False)
        instance.pk = new_name
        instance.save()

        # They are all actually the same and they work...
        # but they INSERT a new entry but they don't UPDATE
        # the existing one.

        return HttpResponseRedirect("/next/")
else:
    form = GroupAnalysisNameEditForm(instance=i)

context = {
    "form": form,
    "groupname": name,
    # ...
}

return render(request, "folder/site.html", context)

models.py

class GroupAnalysis(models.Model):
# grp=group ana=analysis crtr=creator
grp_ana = models.CharField(max_length=64, primary_key=True)
grp_crtr = models.ForeignKey(User)
ana_public = models.BooleanField(default=False)
ana_closed = models.BooleanField(default=False)
expiration_date = models.DateField(default=datetime.now()+timedelta(days=360))

def __str__(self):
    return "{0}".format(
        self.pk)

表格

class GroupAnalysisNameEditForm(ModelForm):

class Meta:
    model = GroupAnalysis
    fields = ['grp_ana']

我在这堂课只需要grp_ana ; 我有另一个类,我需要所有来自models.py的其他字段,但是如果我使用该类,则form.is_valid()总是失败。

模板片段

<form method=POST action="{% url 'group_single' name=groupname %}">
    {% csrf_token %}
    {{ form.grp_ana }}
    <input type="submit" value="Update">
</form>

你看到错误了吗?

提前致谢!

您已将grp_ana字段设为主键; 这意味着您永远不要更改该值。 如果这样做的话,当然意味着插入而不是更新:pk是首先识别记录的方式,并且Django除了通过pk之外,没有其他方法可以将模型实例与数据库行相关联。

通常,您应该让Django始终定义一个自动递增的pk; 特别是在您的情况下,当您要编辑字段时,请勿将其设为pk。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM