1

I would like to implement the add button we have beside a ForeignKey field, so that we can add data to the field/database.

I have been following a couple tutorials, but none of them help me actually add data to the field, and in turn, my database. I have also been looking everywhere but I can't seem to find anyone that has accomplished this task.

A good tutorial I have been following is this one: https://djangopy.org/how-to/reverse-engineering-of-the-django-admin-foreign-keys-addedit-button/

However, the tutorial is very good until the end. He only implements the edit button, and not the add button. So I'm not sure which AJAX call I need to make in order to replicate that of which the admin add button does, when adding data for the ForeignKey.

For the sake of brevity, all code from the tutorial is exactly what I have, I just need to implement a function for the add button.

If anyone has any ideas or could point me into the right direction, that would be greatly appreciated.

juiceb0xk
  • 949
  • 3
  • 19
  • 46
  • Possible duplicate of [Django: adding an "Add new" button for a ForeignKey in a ModelForm](https://stackoverflow.com/questions/28068168/django-adding-an-add-new-button-for-a-foreignkey-in-a-modelform) – elke Jul 13 '18 at 12:35

1 Answers1

0

AJAX for adding data should be a POST request, but have you tried the add button as written? I'm on Django 2.0+ so I can't copy-paste exactly what he has without modification, but in his views.py:

def AuthorCreatePopup(request):
  form = AuthorForm(request.POST or None)
  if form.is_valid():
    instance = form.save()
    return HttpResponse('<script>opener.closePopup(window, "%s", "%s", "#id_author");</script>
  return render(request, "author_form.html", {"form" : form})

That LOOKS like it should handle the new record and update the field on the main form. If it's not working, I think you've got an error somewhere.

Supra621
  • 146
  • 3
  • 12