Django - 从模型

时间:2015-11-18 17:25:17

标签: python django

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

但是没有一个像我预期的那样对我有用。

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

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)

forms.py

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>

你能看到错误吗?

提前致谢!

1 个答案:

答案 0 :(得分:1)

您已将grp_ana字段设为主键;这意味着你不应该改变价值。如果你这样做,当然它意味着插入而不是更新:pk是首先识别记录的方式,而Django无法通过pk将模型实例与数据库行相关联。

一般来说,你应该让Django定义一个自动递增的pk;特别是在你的情况下,当你想编辑字段时,你不应该把它变成pk。