简体   繁体   中英

Django - update single entry in form from Model

I know there are a few solutions for this topic eg

but none of them work for me as expected.

The code works but it doesn't update , instead it inserts a new record.

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']

I only need grp_ana in this class; I have another class where I need alls the other fields from the models.py but if I use that class, the form.is_valid() always fails.

Template snippet

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

Can you see the mistake?

Thanks in advance!

You have made the grp_ana field the primary key; that means you should not ever change the value. If you do, of course it means an insert rather than an update: the pk is how a record is identified in the first place, and Django has no way of associating a model instance with a database row other than via the pk.

Generally you should let Django define an auto incrementing pk anyway; particularly in your case, when you want to edit the field, you should not make it the pk.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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