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
def change_contact(request, contact_id): try: form = AddToPhoneBookForm(instance=Contact.objects.get(pk=contact_id)) form.instance.user = request.user if form.is_valid(): form.save() form = AddToPhoneBookForm() context = { 'form': form } return render(request, "CallCenter/add_to_phone_book.html", context)
forms.py
class AddToPhoneBookForm(forms.ModelForm): class Meta: model = Contact fields = ['first_name', 'last_name', 'phone_number', 'phone_book']
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
contact = Contact.objects.get(phone_book__id=phone_book_id)
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
def change_contact(request, contact_id): contact = Contact.objects.get(pk=contact_id) form = AddToPhoneBookForm(instance=contact) if request.method == 'POST': form = AddToPhoneBookForm(request.POST,instance=contact) if form.is_valid(): obj=form.save(commit=False) obj.user = request.user obj.save() return redirect('some-path') context = { 'form': form,'contact':contact } return render(request, "CallCenter/add_to_phone_book.html", context)