W
W
wingserg2019-08-28 09:56:59
Django
wingserg, 2019-08-28 09:56:59

Why is diango doing an insert instead of an update on a form?

Hello.
The view creates a record and you can immediately edit it through the form.
But after the form button, a new record is created instead of update:

def oper_next(request, oper_id_op, template_name="stage/otk_new.html"):  
    Op1 = Oper.objects.get(id_op = oper_id_op)  #Ok! получить объект..
    otk = Otk.objects.create( id_op = Op1,   techn_oper=Op1.techn_oper, 
          prod=Op1.prod, sostav=Op1.sostav, ispoln=Op1.ispoln, smena=Op1.smena, kolwo = Op1.kolwo,)
    if request.method == 'POST':
        f = EditOtkForm(request.POST, instance=otk) 
        if f.is_valid():
            f.save()
            return HttpResponseRedirect(reverse('oper')) 
    else:
        f = EditOtkForm(instance=otk) #

    ctx = {'otk': otk,'form': f, 'oper': Op1}
    return render(request, template_name, ctx)

already explicitly stated in the form:
class EditOperForm(OperForm):

    def save(self):
        oper = self.instance
        oper.save( force_insert=False, force_update = True ) # не добавлять, замещать
        return oper

sample:
{% extends "base_generic.html" %}

{% block content %}
  <a href="{% url 'stage_index' %}"> --- на Главную --- </a>

  <h3> НОВАЯ Запись в Журнал  </h3>  
  
  <p><strong>Запись провел:</strong> {{ otk.posted_by }} {{ otk.created_on }}</p>  
  <p><strong>(от техн.зад.)</strong> {{ oper.id_op }}</p> 

  <p><strong>Продукт:</strong> {{ otk.prod }}</p> <!--  -->
  <p><strong>Статус записи:</strong> {{ otk.status }}</p> 

======= <strong> отредактируйте необходимые поля внизу </strong> =============
    <h3> Редактирование записи:</h3> 
    <form method="POST" class="post-form">{% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="save btn btn-default">Сохранить изменения</button>
    </form>
{% endblock %}

It still adds.
And the best part is that something like this works in the same project, but this one doesn't.
Has anyone come across something like this?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
W
wingserg, 2019-08-28
@wingserg

Otk.objects.create just creates a record, then I edit it in the form
and, logically, the form should have an update on the existing record
An, no! What I didn’t try :(
Instead of create(), get_or_create() is needed here!!!
only after it the object must be pulled out of the cotreh, where it will be the 1st element

S
Sergey Tikhonov, 2019-08-28
@tumbler

You have Otk.objects.create two lines above the form.save call. Maybe it's in him?

Y
Yura Khlyan, 2019-08-28
@MAGistr_MTM

Look at generics and switch to CBV.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question