N
N
NyxDeveloper2020-12-24 12:03:49
Django
NyxDeveloper, 2020-12-24 12:03:49

How to modify a django model object stored in the database without creating a new one?

I am creating a view to edit objects in the contacts table, I need to add such functionality so that the lines in the table can be changed by their ID, but instead Django creates a new object, and does not update the old one
The view itself

def editContactView(request, key):
    if request.method == 'POST':
        form = EditContactForm(request.POST)
        if form.is_valid():
            contact = Contact.objects.get(id=key)
            if form.cleaned_data['type']:
                contact.type = form.cleaned_data['type']
            if form.cleaned_data['subject']:
                contact.subject = form.cleaned_data['subject']
            if form.cleaned_data['info']:
                contact.info = form.cleaned_data['info']
            contact.save()


Form in template
<form class="d-flex" method="post" action="">
                 {% csrf_token %}
                 {{ editContact.KEY }}
                 {{ editContact.subject }}
                 {{ editContact.type }}
                 {{ editContact.info }}
                 <button type="submit" class="btn btn-success">Изменить</button>
             </form>


Form in forms.py
class EditContactForm(ModelForm):
    class Meta:
        model = Contact
        fields = ['KEY', 'info', 'type', 'subject']
        widgets = {
            'KEY': forms.NumberInput(attrs={
               'placeholder': 'ID',
               'class': 'form-control w-25'
            }),
            'info': forms.TextInput(attrs={
                'placeholder': 'Данные контакта',
                'class': 'form-control w-25'
            }),
            'type': forms.Select(attrs={
                'class': 'form-control w-25'
            }),
            'subject': forms.Select(attrs={
                'class': 'form-control w-25'
            })
        }

    def __init__(self, *args, **kwargs):
        super(EditContactForm, self).__init__(*args, **kwargs)
        self.fields['info'].required = False
        self.fields['type'].required = False
        self.fields['subject'].required = False


Tell me what I'm doing wrong, how can I make changes to an existing object?
I have already tried deleting the old one and assigning its ID to the new one, it is not assigned

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-12-24
@NyxDeveloper

We open the docks https://docs.djangoproject.com/en/3.1/topics/forms... and in the first example we see the difference between the form of creating a new object and editing an existing one.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question