I’m trying to show the user the details they entered in an editable format as we can see in
Edit:
Changed the code and tried to explain the question in a better way
view.py
JavaScript
x
14
14
1
def change_contact(request, contact_id):
2
try:
3
form = AddToPhoneBookForm(instance=Contact.objects.get(pk=contact_id))
4
form.instance.user = request.user
5
if form.is_valid():
6
form.save()
7
form = AddToPhoneBookForm()
8
9
context = {
10
'form': form
11
}
12
13
return render(request, "CallCenter/add_to_phone_book.html", context)
14
forms.py
JavaScript
1
5
1
class AddToPhoneBookForm(forms.ModelForm):
2
class Meta:
3
model = Contact
4
fields = ['first_name', 'last_name', 'phone_number', 'phone_book']
5
This view loads the forms as I want it to but the changes made here is not reflected in the database. Where am I going wrong?
Advertisement
Answer
For this you need to use get() instead of filter() .Get returns the single object whereas filter will returns the queryset
JavaScript
1
2
1
contact = Contact.objects.get(phone_book__id=phone_book_id)
2
And in template you don’t need to use forloop {{contact.first_name}}
will give the result for you
EDIT: you will save the data with POST request so you need to handle for POST request also and there are a lots of things you need to know please read the docs
And change your view like this
JavaScript
1
16
16
1
def change_contact(request, contact_id):
2
contact = Contact.objects.get(pk=contact_id)
3
form = AddToPhoneBookForm(instance=contact)
4
if request.method == 'POST':
5
form = AddToPhoneBookForm(request.POST,instance=contact)
6
if form.is_valid():
7
obj=form.save(commit=False)
8
obj.user = request.user
9
obj.save()
10
return redirect('some-path')
11
context = {
12
'form': form,'contact':contact
13
}
14
15
return render(request, "CallCenter/add_to_phone_book.html", context)
16