Answer the question
In order to leave comments, you need to log in
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 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>
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
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question